0%

Tomcat 鉴权配置小记

在部署 OpenGrok 时, 场景需要对应用增加权限控制, 研究一番发现复用 Tomcat 的鉴权机制实现成本比较低, 这里记录一下实现过程.

开启 Tomcat 鉴权可以分为三步:

  • 配置权限数据源
  • 配置应用登录方式
  • 配置应用鉴权组

配置权限数据源

修改文件 {tomcat}/conf/server.xml:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
...
<Realm className="org.apache.catalina.realm.UserDatabaseRealm"
resourceName="UserDatabase"/>atabase"/>

<!-- 认证新增开始-->
<Realm className="org.apache.catalina.realm.JNDIRealm"
connectionURL="ldap://ldap.example.org:389"
connectionName="cn=zhangsan,OU=Users,DC=example,DC=org"
connectionPassword="password"

userBase="OU=Users,DC=example,DC=org"
userSearch="(username={0})"

roleBase="OU=Group,DC=example,DC=org"
roleName="cn"
roleSearch="(member={0})"

/>
<!-- 认证新增结束-->
...

配置应用登录方式

登录方式可以使用经典的 BASIC, 也可以自定义登录界面, 任选其一即可.

使用 BASIC 登录

修改文件 {tomcat}/webapps/{WEBAPP}/WEB-INF/web.xml:

1
2
3
4
<login-config>
<auth-method>BASIC</auth-method>
<realm-name>Example Form-Based Authentication Area</realm-name>
</login-config>

自定义登录界面

修改文件 {tomcat}/webapps/{WEBAPP}/WEB-INF/web.xml:

1
2
3
4
5
6
7
8
<login-config>
<auth-method>FORM</auth-method>
<realm-name>Example Form-Based Authentication Area</realm-name>
<form-login-config>
<form-login-page>/jsp/security/protected/login.jsp</form-login-page>
<form-error-page>/jsp/security/protected/error.jsp</form-error-page>
</form-login-config>
</login-config>

可参考 Tomcat 自带的 Examples 应用:http://localhost:8080/examples

配置应用鉴权组

修改文件 {tomcat}/webapps/{WEBAPP}/WEB-INF/web.xml, 在一级节点新增权限名称:

1
2
3
4
5
6
<security-role>
<role-name>ROLE_OPENGROK_GROUP_1</role-name>
</security-role>
<security-role>
<role-name>ROLE_OPENGROK_GROUP_2</role-name>
</security-role>

权限组可定义多个.

修改文件 {tomcat}/webapps/{WEBAPP}/WEB-INF/web.xml, 在一级节点新增权限规则:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
<security-constraint>
<display-name>Example Security Constraint - part 1</display-name>
<web-resource-collection>
<web-resource-name>Protected Area - Allow methods</web-resource-name>
<!-- Define the context-relative URL(s) to be protected -->
<url-pattern>/jsp/security/protected/*</url-pattern>
<!-- If you list http methods, only those methods are protected so -->
<!-- the constraint below ensures all other methods are denied -->
<http-method>DELETE</http-method>
<http-method>GET</http-method>
<http-method>POST</http-method>
<http-method>PUT</http-method>
</web-resource-collection>
<auth-constraint>
<!-- Anyone with one of the listed roles may access this area -->
<role-name>ROLE_OPENGROK_GROUP_1</role-name>
<role-name>ROLE_OPENGROK_GROUP_2</role-name>
</auth-constraint>
</security-constraint>

权限规则可定义多个.

可参考 Tomcat 自带的 Examples 应用:http://localhost:8080/examples

  • 本文作者: 6x
  • 本文链接: https://6xyun.cn/article/167
  • 版权声明: 本博客所有文章除特别声明外,均采用 BY-NC-ND 许可协议。转载请注明出处!