第十四章 SSL——《跟我学Shiro》

对于SSL的支持,Shiro只是判断当前url是否需要SSL登录,如果需要自动重定向到https进行访问。

首先生成数字证书,生成证书到D:\localhost.keystore

使用JDK的keytool命令,生成证书(包含证书/公钥/私钥)到D:\localhost.keystore:

keytool -genkey -keystore "D:\localhost.keystore" -alias localhost -keyalg RSA

输入密钥库口令:

再次输入新口令:

您的名字与姓氏是什么?

[Unknown]:  localhost

您的组织单位名称是什么?

您的组织名称是什么?

[Unknown]:

您所在的城市或区域名称是什么?

[Unknown]:  beijing

您所在的省/市/自治区名称是什么?

[Unknown]:  beijing

该单位的双字母国家/地区代码是什么?

[Unknown]:  cn

CN=localhost, OU= L=beijing, ST=beijing, C=cn是否正确

?

[否]:  y

输入 <localhost> 的密钥口令

(如果和密钥库口令相同, 按回车):

再次输入新口令:

通过如上步骤,生成证书到D:\ localhost.keystore;

然后设置tomcat下的server.xml

此处使用了apache-tomcat-7.0.40版本,打开conf/server.xml,找到:

  1. <!--
  2. <Connector port="8443" protocol="HTTP/1.1" SSLEnabled="true"
  3. maxThreads="150" scheme="https" secure="true"
  4. clientAuth="false" sslProtocol="TLS" />
  5. -->

替换为

  1. <Connector port="8443" protocol="HTTP/1.1" SSLEnabled="true"
  2. maxThreads="150" scheme="https" secure="true"
  3. clientAuth="false" sslProtocol="TLS"
  4. keystoreFile="D:\localhost.keystore" keystorePass="123456"/>

keystorePass就是生成keystore时设置的密码。

添加SSL到配置文件(spring-shiro-web.xml

此处使用了和十三章一样的代码:

  1. <bean id="sslFilter" class="org.apache.shiro.web.filter.authz.SslFilter">
  2. <property name="port" value="8443"/>
  3. </bean>
  4. <bean id="shiroFilter" class="org.apache.shiro.spring.web.ShiroFilterFactoryBean">
  5. ……
  6. <property name="filters">
  7. <util:map>
  8. <entry key="authc" value-ref="formAuthenticationFilter"/>
  9. <entry key="ssl" value-ref="sslFilter"/>
  10. </util:map>
  11. </property>
  12. <property name="filterChainDefinitions">
  13. <value>
  14. /login.jsp = ssl,authc
  15. /logout = logout
  16. /authenticated.jsp = authc
  17. /** = user
  18. </value>
  19. </property>
  20. </bean>

SslFilter默认端口是443,此处使用了8443;“/login.jsp = ssl,authc”表示访问登录页面时需要走SSL。

测试

最后把shiro-example-chapter14打成war包(mvn:package),放到tomcat下的webapps中,启动服务器测试,如访问localhost:9080/chapter14/,会自动跳转到https://localhost:8443/chapter14/login.jsp

如果使用Maven Jetty插件,可以直接如下插件配置:

  1. <plugin>
  2. <groupId>org.mortbay.jetty</groupId>
  3. <artifactId>jetty-maven-plugin</artifactId>
  4. <version>8.1.8.v20121106</version>
  5. <configuration>
  6. <webAppConfig>
  7. <contextPath>/${project.build.finalName}</contextPath>
  8. </webAppConfig>
  9. <connectors>
  10. <connector implementation="org.eclipse.jetty.server.nio.SelectChannelConnector">
  11. <port>8080</port>
  12. </connector>
  13. <connector implementation="org.eclipse.jetty.server.ssl.SslSocketConnector">
  14. <port>8443</port>
  15. <keystore>${project.basedir}/localhost.keystore</keystore>
  16. <password>123456</password>
  17. <keyPassword>123456</keyPassword>
  18. </connector>
  19. </connectors>
  20. </configuration>
  21. </plugin>

第十五章 单点登录——《跟我学Shiro》

Shiro 1.2开始提供了Jasig CAS单点登录的支持,单点登录主要用于多系统集成,即在多个系统中,用户只需要到一个中央服务器登录一次即可访问这些系统中的任何一个,无须多次登录。此处我们使用Jasig CAS v4.0.0-RC3版本:

https://github.com/Jasig/cas/tree/v4.0.0-RC3

Jasig CAS单点登录系统分为服务器端和客户端,服务器端提供单点登录,多个客户端(子系统)将跳转到该服务器进行登录验证,大体流程如下:

1、访问客户端需要登录的页面http://localhost:9080/ client/,此时会跳到单点登录服务器https://localhost:8443/ server/login?service=https://localhost:9443/ client/cas;

2、如果此时单点登录服务器也没有登录的话,会显示登录表单页面,输入用户名/密码进行登录;

3、登录成功后服务器端会回调客户端传入的地址:https://localhost:9443/client/cas?ticket=ST-1-eh2cIo92F9syvoMs5DOg-cas01.example.org,且带着一个ticket;

4、客户端会把ticket提交给服务器来验证ticket是否有效;如果有效服务器端将返回用户身份;

5、客户端可以再根据这个用户身份获取如当前系统用户/角色/权限信息。

本章使用了和《第十四章 SSL》一样的数字证书。

服务器端

我们使用了Jasig CAS服务器v4.0.0-RC3版本,可以到其官方的github下载:https://github.com/Jasig/cas/tree/v4.0.0-RC3下载,然后将其cas-server-webapp模块封装到shiro-example-chapter15-server模块中,具体请参考源码。

1、数字证书使用和《第十四章 SSL》一样的数字证书,即将localhost.keystore拷贝到shiro-example-chapter15-server模块根目录下;

2、在pom.xml中添加Jetty Maven插件,并添加SSL支持:

  1. <plugin>
  2. <groupId>org.mortbay.jetty</groupId>
  3. <artifactId>jetty-maven-plugin</artifactId>
  4. <version>8.1.8.v20121106</version>
  5. <configuration>
  6. <webAppConfig>
  7. <contextPath>/${project.build.finalName}</contextPath>
  8. </webAppConfig>
  9. <connectors>
  10. <connector implementation="org.eclipse.jetty.server.nio.SelectChannelConnector">
  11. <port>8080</port>
  12. </connector>
  13. <connector implementation="org.eclipse.jetty.server.ssl.SslSocketConnector">
  14. <port>8443</port>
  15. <keystore>${project.basedir}/localhost.keystore</keystore>
  16. <password>123456</password>
  17. <keyPassword>123456</keyPassword>
  18. </connector>
  19. </connectors>
  20. </configuration>
  21. </plugin>

3、修改src/main/webapp/WEB-INF/deployerConfigContext.xml,找到primaryAuthenticationHandler,然后添加一个账户:

  1. <entry key="zhang" value="123"/>

其也支持如JDBC查询,可以自己定制;具体请参考文档。

4、mvn jetty:run启动服务器测试即可:

访问https://localhost:8443/chapter15-server/login将弹出如下登录页面:

输入用户名/密码,如zhang/123,将显示登录成功页面:

到此服务器端的简单配置就完成了。

客户端

1、首先使用localhost.keystore导出数字证书(公钥)到D:\localhost.cer

  1. keytool -export -alias localhost -file D:\localhost.cer -keystore D:\localhost.keystore

2、因为CAS client需要使用该证书进行验证,需要将证书导入到JDK中:

  1. cd D:\jdk1.7.0_21\jre\lib\security
  2. keytool -import -alias localhost -file D:\localhost.cer -noprompt -trustcacerts -storetype jks -keystore cacerts -storepass 123456

如果导入失败,可以先把security 目录下的cacerts删掉;

3、按照服务器端的Jetty Maven插件的配置方式配置Jetty插件;

4、在shiro-example-chapter15-client模块中导入shiro-cas依赖,具体请参考其pom.xml;

5、自定义CasRealm:

  1. public class MyCasRealm extends CasRealm {
  2. private UserService userService;
  3. public void setUserService(UserService userService) {
  4. this.userService = userService;
  5. }
  6. @Override
  7. protected AuthorizationInfo doGetAuthorizationInfo(PrincipalCollection principals) {
  8. String username = (String)principals.getPrimaryPrincipal();
  9. SimpleAuthorizationInfo authorizationInfo = new SimpleAuthorizationInfo();
  10. authorizationInfo.setRoles(userService.findRoles(username));
  11. authorizationInfo.setStringPermissions(userService.findPermissions(username));
  12. return authorizationInfo;
  13. }
  14. }

CasRealm根据CAS服务器端返回的用户身份获取相应的角色/权限信息。

6、spring-shiro-web.xml配置:

  1. <bean id="casRealm" class="com.github.zhangkaitao.shiro.chapter13.realm.MyCasRealm">
  2. <property name="userService" ref="userService"/>
  3. ……
  4. <property name="casServerUrlPrefix" value="https://localhost:8443/chapter14-server"/>
  5. <property name="casService" value="https://localhost:9443/chapter14-client/cas"/>
  6. </bean>

casServerUrlPrefix:是CAS Server服务器端地址;

casService:是当前应用CAS服务URL,即用于接收并处理登录成功后的Ticket的;

如果角色/权限信息是由服务器端提供的话,我们可以直接使用CasRealm:

  1. <bean id="casRealm" class="org.apache.shiro.cas.CasRealm">
  2. ……
  3. <property name="defaultRoles" value="admin,user"/>
  4. <property name="defaultPermissions" value="user:create,user:update"/>
  5. <property name="roleAttributeNames" value="roles"/>
  6. <property name="permissionAttributeNames" value="permissions"/>
  7. <property name="casServerUrlPrefix" value="https://localhost:8443/chapter14-server"/>
  8. <property name="casService" value="https://localhost:9443/chapter14-client/cas"/>
  9. </bean>

defaultRoles/ defaultPermissions:默认添加给所有CAS登录成功用户的角色和权限信息;

roleAttributeNames/ permissionAttributeNames:角色属性/权限属性名称,如果用户的角色/权限信息是从服务器端返回的(即返回的CAS Principal中除了Principal之外还有如一些Attributes),此时可以使用roleAttributeNames/ permissionAttributeNames得到Attributes中的角色/权限数据;请自行查询CAS获取用户更多信息。

  1. <bean id="casFilter" class="org.apache.shiro.cas.CasFilter">
  2. <property name="failureUrl" value="/casFailure.jsp"/>
  3. </bean>

CasFilter类似于FormAuthenticationFilter,只不过其验证服务器端返回的CAS Service Ticket。

  1. <bean id="shiroFilter" class="org.apache.shiro.spring.web.ShiroFilterFactoryBean">
  2. <property name="securityManager" ref="securityManager"/>
  3. <property name="loginUrl" value="https://localhost:8443/chapter14-server/login?service=https://localhost:9443/chapter14-client/cas"/>
  4. <property name="successUrl" value="/"/>
  5. <property name="filters">
  6. <util:map>
  7. <entry key="cas" value-ref="casFilter"/>
  8. </util:map>
  9. </property>
  10. <property name="filterChainDefinitions">
  11. <value>
  12. /casFailure.jsp = anon
  13. /cas = cas
  14. /logout = logout
  15. /** = user
  16. </value>
  17. </property>
  18. </bean>

loginUrl:https://localhost:8443/chapter15-server/login表示服务端端登录地址,登录成功后跳转到?service参数对于的地址进行客户端验证及登录;

“/cas=cas”:即/cas地址是服务器端回调地址,使用CasFilter获取Ticket进行登录。

7、测试,输入http://localhost:9080/chapter15-client地址进行测试即可,可以使用如Chrome开这debug观察网络请求的变化。

如果遇到以下异常,一般是证书导入错误造成的,请尝试重新导入,如果还是不行,有可能是运行应用的JDK和安装数字证书的JDK不是同一个造成的:

Caused by: sun.security.validator.ValidatorException: PKIX path building failed: sun.security.provider.certpath.SunCertPathBuilderException: unable to find valid certification path to requested target

at sun.security.validator.PKIXValidator.doBuild(PKIXValidator.java:385)

at sun.security.validator.PKIXValidator.engineValidate(PKIXValidator.java:292)

at sun.security.validator.Validator.validate(Validator.java:260)

at sun.security.ssl.X509TrustManagerImpl.validate(X509TrustManagerImpl.java:326)

at sun.security.ssl.X509TrustManagerImpl.checkTrusted(X509TrustManagerImpl.java:231)

at sun.security.ssl.X509TrustManagerImpl.checkServerTrusted(X509TrustManagerImpl.java:126)

at sun.security.ssl.ClientHandshaker.serverCertificate(ClientHandshaker.java:1323)

... 67 more

Caused by: sun.security.provider.certpath.SunCertPathBuilderException: unable to find valid certification path to requested target

at sun.security.provider.certpath.SunCertPathBuilder.engineBuild(SunCertPathBuilder.java:196)

at java.security.cert.CertPathBuilder.build(CertPathBuilder.java:268)

at sun.security.validator.PKIXValidator.doBuild(PKIXValidator.java:380)

... 73 more

第十六章 综合实例——《跟我学Shiro》

简单的实体关系图

简单数据字典

用户(sys_user)

名称

类型

长度

描述

id

bigint

编号 主键

username

varchar

100

用户名

password

varchar

100

密码

salt

varchar

50

role_ids

varchar

100

角色列表

locked

bool

账户是否锁定

组织机构(sys_organization)

名称

类型

长度

描述

id

bigint

编号 主键

name

varchar

100

组织机构名

priority

int

显示顺序

parent_id

bigint

父编号

parent_ids

varchar

100

父编号列表

available

bool

是否可用

资源(sys_resource)

名称

类型

长度

描述

id

bigint

编号 主键

name

varchar

100

资源名称

type

varchar

50

资源类型,

priority

int

显示顺序

parent_id

bigint

父编号

parent_ids

varchar

100

父编号列表

permission

varchar

100

权限字符串

available

bool

是否可用

角色(sys_role)

名称

类型

长度

描述

id

bigint

编号 主键

role

varchar

100

角色名称

description

varchar

100

角色描述

resource_ids

varchar

100

授权的资源

available

bool

是否可用

资源:表示菜单元素、页面按钮元素等;菜单元素用来显示界面菜单的,页面按钮是每个页面可进行的操作,如新增、修改、删除按钮;使用type来区分元素类型(如menu表示菜单,button代表按钮),priority是元素的排序,如菜单显示顺序;permission表示权限;如用户菜单使用user:*;也就是把菜单授权给用户后,用户就拥有了user:*权限;如用户新增按钮使用user:create,也就是把用户新增按钮授权给用户后,用户就拥有了user:create权限了;available表示资源是否可用,如菜单显示/不显示。

角色:role表示角色标识符,如admin,用于后台判断使用;description表示角色描述,如超级管理员,用于前端显示给用户使用;resource_ids表示该角色拥有的资源列表,即该角色拥有的权限列表(显示角色),即角色是权限字符串集合;available表示角色是否可用。

组织机构:name表示组织机构名称,priority是组织机构的排序,即显示顺序;available表示组织机构是否可用。

用户:username表示用户名;password表示密码;salt表示加密密码的盐;role_ids表示用户拥有的角色列表,可以通过角色再获取其权限字符串列表;locked表示用户是否锁定。

此处如资源、组织机构都是树型结构:

id

name

parent_id

parent_ids

1

总公司

0

0/

2

山东分公司

1

0/1/

3

河北分公司

1

0/1/

4

济南分公司

2

0/1/2/

parent_id表示父编号,parent_ids表示所有祖先编号;如0/1/2/表示其祖先是2、1、0;其中根节点父编号为0。

为了简单性,如用户-角色,角色-资源关系直接在实体(用户表中的role_ids,角色表中的resource_ids)里完成的,没有建立多余的关系表,如要查询拥有admin角色的用户时,建议建立关联表,否则就没必要建立了。在存储关系时如role_ids=1,2,3,;多个之间使用逗号分隔。

用户组、组织机构组本实例没有实现,即可以把一组权限授权给这些组,组中的用户/组织机构就自动拥有这些角色/权限了;另外对于用户组可以实现一个默认用户组,如论坛,不管匿名/登录用户都有查看帖子的权限。

更复杂的权限请参考我的《JavaEE项目开发脚手架》:http://github.com/zhangkaitao/es

/数据SQL

具体请参考

sql/ shiro-schema.sql (表结构)

sql/ shiro-data.sql  (初始数据)

默认用户名/密码是admin/123456。

实体

具体请参考com.github.zhangkaitao.shiro.chapter16.entity包下的实体,此处就不列举了。

DAO

具体请参考com.github.zhangkaitao.shiro.chapter16.dao包下的DAO接口及实现。

Service

具体请参考com.github.zhangkaitao.shiro.chapter16.service包下的Service接口及实现。以下是出了基本CRUD之外的关键接口:

  1. public interface ResourceService {
  2. Set<String> findPermissions(Set<Long> resourceIds); //得到资源对应的权限字符串
  3. List<Resource> findMenus(Set<String> permissions); //根据用户权限得到菜单
  4. }
  1. public interface RoleService {
  2. Set<String> findRoles(Long... roleIds); //根据角色编号得到角色标识符列表
  3. Set<String> findPermissions(Long[] roleIds); //根据角色编号得到权限字符串列表
  4. }
  1. public interface UserService {
  2. public void changePassword(Long userId, String newPassword); //修改密码
  3. public User findByUsername(String username); //根据用户名查找用户
  4. public Set<String> findRoles(String username);// 根据用户名查找其角色
  5. public Set<String> findPermissions(String username);// 根据用户名查找其权限
  6. }

Service实现请参考源代码,此处就不列举了。

UserRealm实现

  1. public class UserRealm extends AuthorizingRealm {
  2. @Autowired private UserService userService;
  3. protected AuthorizationInfo doGetAuthorizationInfo(PrincipalCollection principals) {
  4. String username = (String)principals.getPrimaryPrincipal();
  5. SimpleAuthorizationInfo authorizationInfo = new SimpleAuthorizationInfo();
  6. authorizationInfo.setRoles(userService.findRoles(username));
  7. authorizationInfo.setStringPermissions(userService.findPermissions(username));
  8. System.out.println(userService.findPermissions(username));
  9. return authorizationInfo;
  10. }
  11. protected AuthenticationInfo doGetAuthenticationInfo(AuthenticationToken token) throws AuthenticationException {
  12. String username = (String)token.getPrincipal();
  13. User user = userService.findByUsername(username);
  14. if(user == null) {
  15. throw new UnknownAccountException();//没找到帐号
  16. }
  17. if(Boolean.TRUE.equals(user.getLocked())) {
  18. throw new LockedAccountException(); //帐号锁定
  19. }
  20. return new SimpleAuthenticationInfo(
  21. user.getUsername(), //用户名
  22. user.getPassword(), //密码
  23. ByteSource.Util.bytes(user.getCredentialsSalt()),//salt=username+salt
  24. getName()  //realm name
  25. );
  26. }
  27. }

此处的UserRealm和《第六章Realm及相关对象》中的UserRealm类似,通过UserService获取帐号及角色/权限信息。

Web层控制器 

  1. @Controller
  2. public class IndexController {
  3. @Autowired
  4. private ResourceService resourceService;
  5. @Autowired
  6. private UserService userService;
  7. @RequestMapping("/")
  8. public String index(@CurrentUser User loginUser, Model model) {
  9. Set<String> permissions = userService.findPermissions(loginUser.getUsername());
  10. List<Resource> menus = resourceService.findMenus(permissions);
  11. model.addAttribute("menus", menus);
  12. return "index";
  13. }
  14. }

IndexController中查询菜单在前台界面显示,请参考相应的jsp页面;

  1. @Controller
  2. public class LoginController {
  3. @RequestMapping(value = "/login")
  4. public String showLoginForm(HttpServletRequest req, Model model) {
  5. String exceptionClassName = (String)req.getAttribute("shiroLoginFailure");
  6. String error = null;
  7. if(UnknownAccountException.class.getName().equals(exceptionClassName)) {
  8. error = "用户名/密码错误";
  9. } else if(IncorrectCredentialsException.class.getName().equals(exceptionClassName)) {
  10. error = "用户名/密码错误";
  11. } else if(exceptionClassName != null) {
  12. error = "其他错误:" + exceptionClassName;
  13. }
  14. model.addAttribute("error", error);
  15. return "login";
  16. }
  17. }

LoginController用于显示登录表单页面,其中shiro authc拦截器进行登录,登录失败的话会把错误存到shiroLoginFailure属性中,在该控制器中获取后来显示相应的错误信息。

  1. @RequiresPermissions("resource:view")
  2. @RequestMapping(method = RequestMethod.GET)
  3. public String list(Model model) {
  4. model.addAttribute("resourceList", resourceService.findAll());
  5. return "resource/list";
  6. }

在控制器方法上使用@RequiresPermissions指定需要的权限信息,其他的都是类似的,请参考源码。

Web层标签库

com.github.zhangkaitao.shiro.chapter16.web.taglib.Functions提供了函数标签实现,有根据编号显示资源/角色/组织机构名称,其定义放在src/main/webapp/tld/zhang-functions.tld。

Web层异常处理器 

  1. @ControllerAdvice
  2. public class DefaultExceptionHandler {
  3. @ExceptionHandler({UnauthorizedException.class})
  4. @ResponseStatus(HttpStatus.UNAUTHORIZED)
  5. public ModelAndView processUnauthenticatedException(NativeWebRequest request, UnauthorizedException e) {
  6. ModelAndView mv = new ModelAndView();
  7. mv.addObject("exception", e);
  8. mv.setViewName("unauthorized");
  9. return mv;
  10. }
  11. }

如果抛出UnauthorizedException,将被该异常处理器截获来显示没有权限信息。

Spring配置——spring-config.xml

定义了context:component-scan来扫描除web层的组件、dataSource(数据源)、事务管理器及事务切面等;具体请参考配置源码。

Spring配置——spring-config-cache.xml

定义了spring通用cache,使用ehcache实现;具体请参考配置源码。

Spring配置——spring-config-shiro.xml

定义了shiro相关组件。

  1. <bean id="userRealm" class="com.github.zhangkaitao.shiro.chapter16.realm.UserRealm">
  2. <property name="credentialsMatcher" ref="credentialsMatcher"/>
  3. <property name="cachingEnabled" value="false"/>
  4. </bean>

userRealm组件禁用掉了cache,可以参考https://github.com/zhangkaitao/es/tree/master/web/src/main/java/com/sishuok/es/extra/aop实现自己的cache切面;否则需要在修改如资源/角色等信息时清理掉缓存。

  1. <bean id="sysUserFilter"
  2. class="com.github.zhangkaitao.shiro.chapter16.web.shiro.filter.SysUserFilter"/>

sysUserFilter用于根据当前登录用户身份获取User信息放入request;然后就可以通过request获取User。

  1. <property name="filterChainDefinitions">
  2. <value>
  3. /login = authc
  4. /logout = logout
  5. /authenticated = authc
  6. /** = user,sysUser
  7. </value>
  8. </property>

如上是shiroFilter的filterChainDefinitions定义。

Spring MVC配置——spring-mvc.xml

定义了spring mvc相关组件。

  1. <mvc:annotation-driven>
  2. <mvc:argument-resolvers>
  3. <bean class="com.github.zhangkaitao.shiro.chapter16
  4. .web.bind.method.CurrentUserMethodArgumentResolver"/>
  5. </mvc:argument-resolvers>
  6. </mvc:annotation-driven>

此处注册了一个@CurrentUser参数解析器。如之前的IndexController,从request获取shiro sysUser拦截器放入的当前登录User对象。

Spring MVC配置——spring-mvc-shiro.xml

定义了spring mvc相关组件。

  1. <aop:config proxy-target-class="true"></aop:config>
  2. <bean class="org.apache.shiro.spring.security
  3. .interceptor.AuthorizationAttributeSourceAdvisor">
  4. <property name="securityManager" ref="securityManager"/>
  5. </bean>

定义aop切面,用于代理如@RequiresPermissions注解的控制器,进行权限控制。

web.xml配置文件

定义Spring ROOT上下文加载器、ShiroFilter、及SpringMVC拦截器。具体请参考源码。

JSP页面 

  1. <shiro:hasPermission name="user:create">
  2. <a href="${pageContext.request.contextPath}/user/create">用户新增</a><br/>
  3. </shiro:hasPermission>

使用shiro标签进行权限控制。具体请参考源码。

系统截图

访问http://localhost:8080/chapter16/

首先进入登录页面,输入用户名/密码(默认admin/123456)登录:

登录成功后到达整个页面主页,并根据当前用户权限显示相应的菜单,此处菜单比较简单,没有树型结构显示

然后就可以进行一些操作,如组织机构维护、用户修改、资源维护、角色授权

第十七章 OAuth2集成——《跟我学Shiro》

目前很多开放平台如新浪微博开放平台都在使用提供开放API接口供开发者使用,随之带来了第三方应用要到开放平台进行授权的问题,OAuth就是干这个的,OAuth2是OAuth协议的下一个版本,相比OAuth1,OAuth2整个授权流程更简单安全了,但不兼容OAuth1,具体可以到OAuth2官网http://oauth.net/2/查看,OAuth2协议规范可以参考http://tools.ietf.org/html/rfc6749。目前有好多参考实现供选择,可以到其官网查看下载。

本文使用Apache Oltu,其之前的名字叫Apache Amber ,是Java版的参考实现。使用文档可参考https://cwiki.apache.org/confluence/display/OLTU/Documentation

OAuth角色

资源拥有者(resource owner:能授权访问受保护资源的一个实体,可以是一个人,那我们称之为最终用户;如新浪微博用户zhangsan;

资源服务器(resource server:存储受保护资源,客户端通过access token请求资源,资源服务器响应受保护资源给客户端;存储着用户zhangsan的微博等信息。

授权服务器(authorization server:成功验证资源拥有者并获取授权之后,授权服务器颁发授权令牌(Access Token)给客户端。

客户端(client:如新浪微博客户端weico、微格等第三方应用,也可以是它自己的官方应用;其本身不存储资源,而是资源拥有者授权通过后,使用它的授权(授权令牌)访问受保护资源,然后客户端把相应的数据展示出来/提交到服务器。“客户端”术语不代表任何特定实现(如应用运行在一台服务器、桌面、手机或其他设备)。

OAuth2协议流程

1、客户端从资源拥有者那请求授权。授权请求可以直接发给资源拥有者,或间接的通过授权服务器这种中介,后者更可取。

2、客户端收到一个授权许可,代表资源服务器提供的授权。

3、客户端使用它自己的私有证书及授权许可到授权服务器验证。

4、如果验证成功,则下发一个访问令牌。

5、客户端使用访问令牌向资源服务器请求受保护资源。

6、资源服务器会验证访问令牌的有效性,如果成功则下发受保护资源。

更多流程的解释请参考OAuth2的协议规范http://tools.ietf.org/html/rfc6749

服务器端

本文把授权服务器和资源服务器整合在一起实现。

POM依赖

此处我们使用apache oltu oauth2服务端实现,需要引入authzserver(授权服务器依赖)和resourceserver(资源服务器依赖)。

  1. <dependency>
  2. <groupId>org.apache.oltu.oauth2</groupId>
  3. <artifactId>org.apache.oltu.oauth2.authzserver</artifactId>
  4. <version>0.31</version>
  5. </dependency>
  6. <dependency>
  7. <groupId>org.apache.oltu.oauth2</groupId>
  8. <artifactId>org.apache.oltu.oauth2.resourceserver</artifactId>
  9. <version>0.31</version>
  10. </dependency>

其他的请参考pom.xml。

数据字典

用户(oauth2_user)

名称

类型

长度

描述

id

bigint

10

编号 主键

username

varchar

100

用户名

password

varchar

100

密码

salt

varchar

50

客户端(oauth2_client)

名称

类型

长度

描述

id

bigint

10

编号 主键

client_name

varchar

100

客户端名称

client_id

varchar

100

客户端id

client_secret

varchar

100

客户端安全key

用户表存储着认证/资源服务器的用户信息,即资源拥有者;比如用户名/密码;客户端表存储客户端的的客户端id及客户端安全key;在进行授权时使用。

表及数据SQL

具体请参考

sql/ shiro-schema.sql (表结构)

sql/ shiro-data.sql  (初始数据)

默认用户名/密码是admin/123456。

 

实体

具体请参考com.github.zhangkaitao.shiro.chapter17.entity包下的实体,此处就不列举了。

DAO

具体请参考com.github.zhangkaitao.shiro.chapter17.dao包下的DAO接口及实现。

Service

具体请参考com.github.zhangkaitao.shiro.chapter17.service包下的Service接口及实现。以下是出了基本CRUD之外的关键接口:

  1. public interface UserService {
  2. public User createUser(User user);// 创建用户
  3. public User updateUser(User user);// 更新用户
  4. public void deleteUser(Long userId);// 删除用户
  5. public void changePassword(Long userId, String newPassword); //修改密码
  6. User findOne(Long userId);// 根据id查找用户
  7. List<User> findAll();// 得到所有用户
  8. public User findByUsername(String username);// 根据用户名查找用户
  9. }
  1. public interface ClientService {
  2. public Client createClient(Client client);// 创建客户端
  3. public Client updateClient(Client client);// 更新客户端
  4. public void deleteClient(Long clientId);// 删除客户端
  5. Client findOne(Long clientId);// 根据id查找客户端
  6. List<Client> findAll();// 查找所有
  7. Client findByClientId(String clientId);// 根据客户端id查找客户端
  8. Client findByClientSecret(String clientSecret);//根据客户端安全KEY查找客户端
  9. }
  1. public interface OAuthService {
  2. public void addAuthCode(String authCode, String username);// 添加 auth code
  3. public void addAccessToken(String accessToken, String username); // 添加 access token
  4. boolean checkAuthCode(String authCode); // 验证auth code是否有效
  5. boolean checkAccessToken(String accessToken); // 验证access token是否有效
  6. String getUsernameByAuthCode(String authCode);// 根据auth code获取用户名
  7. String getUsernameByAccessToken(String accessToken);// 根据access token获取用户名
  8. long getExpireIn();//auth code / access token 过期时间
  9. public boolean checkClientId(String clientId);// 检查客户端id是否存在
  10. public boolean checkClientSecret(String clientSecret);// 坚持客户端安全KEY是否存在
  11. }

此处通过OAuthService实现进行auth code和access token的维护。

后端数据维护控制器

具体请参考com.github.zhangkaitao.shiro.chapter17.web.controller包下的IndexController、LoginController、UserController和ClientController,其用于维护后端的数据,如用户及客户端数据;即相当于后台管理。

授权控制器AuthorizeController 

  1. @Controller
  2. public class AuthorizeController {
  3. @Autowired
  4. private OAuthService oAuthService;
  5. @Autowired
  6. private ClientService clientService;
  7. @RequestMapping("/authorize")
  8. public Object authorize(Model model,  HttpServletRequest request)
  9. throws URISyntaxException, OAuthSystemException {
  10. try {
  11. //构建OAuth 授权请求
  12. OAuthAuthzRequest oauthRequest = new OAuthAuthzRequest(request);
  13. //检查传入的客户端id是否正确
  14. if (!oAuthService.checkClientId(oauthRequest.getClientId())) {
  15. OAuthResponse response = OAuthASResponse
  16. .errorResponse(HttpServletResponse.SC_BAD_REQUEST)
  17. .setError(OAuthError.TokenResponse.INVALID_CLIENT)
  18. .setErrorDescription(Constants.INVALID_CLIENT_DESCRIPTION)
  19. .buildJSONMessage();
  20. return new ResponseEntity(
  21. response.getBody(), HttpStatus.valueOf(response.getResponseStatus()));
  22. }
  23. Subject subject = SecurityUtils.getSubject();
  24. //如果用户没有登录,跳转到登陆页面
  25. if(!subject.isAuthenticated()) {
  26. if(!login(subject, request)) {//登录失败时跳转到登陆页面
  27. model.addAttribute("client",
  28. clientService.findByClientId(oauthRequest.getClientId()));
  29. return "oauth2login";
  30. }
  31. }
  32. String username = (String)subject.getPrincipal();
  33. //生成授权码
  34. String authorizationCode = null;
  35. //responseType目前仅支持CODE,另外还有TOKEN
  36. String responseType = oauthRequest.getParam(OAuth.OAUTH_RESPONSE_TYPE);
  37. if (responseType.equals(ResponseType.CODE.toString())) {
  38. OAuthIssuerImpl oauthIssuerImpl = new OAuthIssuerImpl(new MD5Generator());
  39. authorizationCode = oauthIssuerImpl.authorizationCode();
  40. oAuthService.addAuthCode(authorizationCode, username);
  41. }
  42. //进行OAuth响应构建
  43. OAuthASResponse.OAuthAuthorizationResponseBuilder builder =
  44. OAuthASResponse.authorizationResponse(request,
  45. HttpServletResponse.SC_FOUND);
  46. //设置授权码
  47. builder.setCode(authorizationCode);
  48. //得到到客户端重定向地址
  49. String redirectURI = oauthRequest.getParam(OAuth.OAUTH_REDIRECT_URI);
  50. //构建响应
  51. final OAuthResponse response = builder.location(redirectURI).buildQueryMessage();
  52. //根据OAuthResponse返回ResponseEntity响应
  53. HttpHeaders headers = new HttpHeaders();
  54. headers.setLocation(new URI(response.getLocationUri()));
  55. return new ResponseEntity(headers, HttpStatus.valueOf(response.getResponseStatus()));
  56. } catch (OAuthProblemException e) {
  57. //出错处理
  58. String redirectUri = e.getRedirectUri();
  59. if (OAuthUtils.isEmpty(redirectUri)) {
  60. //告诉客户端没有传入redirectUri直接报错
  61. return new ResponseEntity(
  62. "OAuth callback url needs to be provided by client!!!", HttpStatus.NOT_FOUND);
  63. }
  64. //返回错误消息(如?error=)
  65. final OAuthResponse response =
  66. OAuthASResponse.errorResponse(HttpServletResponse.SC_FOUND)
  67. .error(e).location(redirectUri).buildQueryMessage();
  68. HttpHeaders headers = new HttpHeaders();
  69. headers.setLocation(new URI(response.getLocationUri()));
  70. return new ResponseEntity(headers, HttpStatus.valueOf(response.getResponseStatus()));
  71. }
  72. }
  73. private boolean login(Subject subject, HttpServletRequest request) {
  74. if("get".equalsIgnoreCase(request.getMethod())) {
  75. return false;
  76. }
  77. String username = request.getParameter("username");
  78. String password = request.getParameter("password");
  79. if(StringUtils.isEmpty(username) || StringUtils.isEmpty(password)) {
  80. return false;
  81. }
  82. UsernamePasswordToken token = new UsernamePasswordToken(username, password);
  83. try {
  84. subject.login(token);
  85. return true;
  86. } catch (Exception e) {
  87. request.setAttribute("error", "登录失败:" + e.getClass().getName());
  88. return false;
  89. }
  90. }
  91. }

如上代码的作用:

1、首先通过如http://localhost:8080/chapter17-server/authorize

?client_id=c1ebe466-1cdc-4bd3-ab69-77c3561b9dee&response_type=code&redirect_uri=http://localhost:9080/chapter17-client/oauth2-login访问授权页面;

2、该控制器首先检查clientId是否正确;如果错误将返回相应的错误信息;

3、然后判断用户是否登录了,如果没有登录首先到登录页面登录;

4、登录成功后生成相应的auth code即授权码,然后重定向到客户端地址,如http://localhost:9080/chapter17-client/oauth2-login?code=52b1832f5dff68122f4f00ae995da0ed;在重定向到的地址中会带上code参数(授权码),接着客户端可以根据授权码去换取access token。

访问令牌控制器AccessTokenController 

  1. @RestController
  2. public class AccessTokenController {
  3. @Autowired
  4. private OAuthService oAuthService;
  5. @Autowired
  6. private UserService userService;
  7. @RequestMapping("/accessToken")
  8. public HttpEntity token(HttpServletRequest request)
  9. throws URISyntaxException, OAuthSystemException {
  10. try {
  11. //构建OAuth请求
  12. OAuthTokenRequest oauthRequest = new OAuthTokenRequest(request);
  13. //检查提交的客户端id是否正确
  14. if (!oAuthService.checkClientId(oauthRequest.getClientId())) {
  15. OAuthResponse response = OAuthASResponse
  16. .errorResponse(HttpServletResponse.SC_BAD_REQUEST)
  17. .setError(OAuthError.TokenResponse.INVALID_CLIENT)
  18. .setErrorDescription(Constants.INVALID_CLIENT_DESCRIPTION)
  19. .buildJSONMessage();
  20. return new ResponseEntity(
  21. response.getBody(), HttpStatus.valueOf(response.getResponseStatus()));
  22. }
  23. // 检查客户端安全KEY是否正确
  24. if (!oAuthService.checkClientSecret(oauthRequest.getClientSecret())) {
  25. OAuthResponse response = OAuthASResponse
  26. .errorResponse(HttpServletResponse.SC_UNAUTHORIZED)
  27. .setError(OAuthError.TokenResponse.UNAUTHORIZED_CLIENT)
  28. .setErrorDescription(Constants.INVALID_CLIENT_DESCRIPTION)
  29. .buildJSONMessage();
  30. return new ResponseEntity(
  31. response.getBody(), HttpStatus.valueOf(response.getResponseStatus()));
  32. }
  33. String authCode = oauthRequest.getParam(OAuth.OAUTH_CODE);
  34. // 检查验证类型,此处只检查AUTHORIZATION_CODE类型,其他的还有PASSWORD或REFRESH_TOKEN
  35. if (oauthRequest.getParam(OAuth.OAUTH_GRANT_TYPE).equals(
  36. GrantType.AUTHORIZATION_CODE.toString())) {
  37. if (!oAuthService.checkAuthCode(authCode)) {
  38. OAuthResponse response = OAuthASResponse
  39. .errorResponse(HttpServletResponse.SC_BAD_REQUEST)
  40. .setError(OAuthError.TokenResponse.INVALID_GRANT)
  41. .setErrorDescription("错误的授权码")
  42. .buildJSONMessage();
  43. return new ResponseEntity(
  44. response.getBody(), HttpStatus.valueOf(response.getResponseStatus()));
  45. }
  46. }
  47. //生成Access Token
  48. OAuthIssuer oauthIssuerImpl = new OAuthIssuerImpl(new MD5Generator());
  49. final String accessToken = oauthIssuerImpl.accessToken();
  50. oAuthService.addAccessToken(accessToken,
  51. oAuthService.getUsernameByAuthCode(authCode));
  52. //生成OAuth响应
  53. OAuthResponse response = OAuthASResponse
  54. .tokenResponse(HttpServletResponse.SC_OK)
  55. .setAccessToken(accessToken)
  56. .setExpiresIn(String.valueOf(oAuthService.getExpireIn()))
  57. .buildJSONMessage();
  58. //根据OAuthResponse生成ResponseEntity
  59. return new ResponseEntity(
  60. response.getBody(), HttpStatus.valueOf(response.getResponseStatus()));
  61. } catch (OAuthProblemException e) {
  62. //构建错误响应
  63. OAuthResponse res = OAuthASResponse
  64. .errorResponse(HttpServletResponse.SC_BAD_REQUEST).error(e)
  65. .buildJSONMessage();
  66. return new ResponseEntity(res.getBody(), HttpStatus.valueOf(res.getResponseStatus()));
  67. }
  68. }
  69. }

如上代码的作用:

1、首先通过如http://localhost:8080/chapter17-server/accessToken,POST提交如下数据:client_id= c1ebe466-1cdc-4bd3-ab69-77c3561b9dee& client_secret= d8346ea2-6017-43ed-ad68-19c0f971738b&grant_type=authorization_code&code=828beda907066d058584f37bcfd597b6&redirect_uri=http://localhost:9080/chapter17-client/oauth2-login访问;

2、该控制器会验证client_id、client_secret、auth code的正确性,如果错误会返回相应的错误;

3、如果验证通过会生成并返回相应的访问令牌access token。

资源控制器UserInfoController 

  1. @RestController
  2. public class UserInfoController {
  3. @Autowired
  4. private OAuthService oAuthService;
  5. @RequestMapping("/userInfo")
  6. public HttpEntity userInfo(HttpServletRequest request) throws OAuthSystemException {
  7. try {
  8. //构建OAuth资源请求
  9. OAuthAccessResourceRequest oauthRequest =
  10. new OAuthAccessResourceRequest(request, ParameterStyle.QUERY);
  11. //获取Access Token
  12. String accessToken = oauthRequest.getAccessToken();
  13. //验证Access Token
  14. if (!oAuthService.checkAccessToken(accessToken)) {
  15. // 如果不存在/过期了,返回未验证错误,需重新验证
  16. OAuthResponse oauthResponse = OAuthRSResponse
  17. .errorResponse(HttpServletResponse.SC_UNAUTHORIZED)
  18. .setRealm(Constants.RESOURCE_SERVER_NAME)
  19. .setError(OAuthError.ResourceResponse.INVALID_TOKEN)
  20. .buildHeaderMessage();
  21. HttpHeaders headers = new HttpHeaders();
  22. headers.add(OAuth.HeaderType.WWW_AUTHENTICATE,
  23. oauthResponse.getHeader(OAuth.HeaderType.WWW_AUTHENTICATE));
  24. return new ResponseEntity(headers, HttpStatus.UNAUTHORIZED);
  25. }
  26. //返回用户名
  27. String username = oAuthService.getUsernameByAccessToken(accessToken);
  28. return new ResponseEntity(username, HttpStatus.OK);
  29. } catch (OAuthProblemException e) {
  30. //检查是否设置了错误码
  31. String errorCode = e.getError();
  32. if (OAuthUtils.isEmpty(errorCode)) {
  33. OAuthResponse oauthResponse = OAuthRSResponse
  34. .errorResponse(HttpServletResponse.SC_UNAUTHORIZED)
  35. .setRealm(Constants.RESOURCE_SERVER_NAME)
  36. .buildHeaderMessage();
  37. HttpHeaders headers = new HttpHeaders();
  38. headers.add(OAuth.HeaderType.WWW_AUTHENTICATE,
  39. oauthResponse.getHeader(OAuth.HeaderType.WWW_AUTHENTICATE));
  40. return new ResponseEntity(headers, HttpStatus.UNAUTHORIZED);
  41. }
  42. OAuthResponse oauthResponse = OAuthRSResponse
  43. .errorResponse(HttpServletResponse.SC_UNAUTHORIZED)
  44. .setRealm(Constants.RESOURCE_SERVER_NAME)
  45. .setError(e.getError())
  46. .setErrorDescription(e.getDescription())
  47. .setErrorUri(e.getUri())
  48. .buildHeaderMessage();
  49. HttpHeaders headers = new HttpHeaders();
  50. headers.add(OAuth.HeaderType.WWW_AUTHENTICATE, 、
  51. oauthResponse.getHeader(OAuth.HeaderType.WWW_AUTHENTICATE));
  52. return new ResponseEntity(HttpStatus.BAD_REQUEST);
  53. }
  54. }
  55. }

如上代码的作用:

1、首先通过如http://localhost:8080/chapter17-server/userInfo? access_token=828beda907066d058584f37bcfd597b6进行访问;

2、该控制器会验证access token的有效性;如果无效了将返回相应的错误,客户端再重新进行授权;

3、如果有效,则返回当前登录用户的用户名。

Spring配置文件

具体请参考resources/spring*.xml,此处只列举spring-config-shiro.xml中的shiroFilter的filterChainDefinitions属性:

  1. <property name="filterChainDefinitions">
  2. <value>
  3. / = anon
  4. /login = authc
  5. /logout = logout
  6. /authorize=anon
  7. /accessToken=anon
  8. /userInfo=anon
  9. /** = user
  10. </value>
  11. </property>

对于oauth2的几个地址/authorize、/accessToken、/userInfo都是匿名可访问的。

其他源码请直接下载文档查看。

服务器维护

访问localhost:8080/chapter17-server/,登录后进行客户端管理和用户管理。

客户端管理就是进行客户端的注册,如新浪微博的第三方应用就需要到新浪微博开发平台进行注册;用户管理就是进行如新浪微博用户的管理。

对于授权服务和资源服务的实现可以参考新浪微博开发平台的实现:

http://open.weibo.com/wiki/授权机制说明

http://open.weibo.com/wiki/微博API

客户端

客户端流程:如果需要登录首先跳到oauth2服务端进行登录授权,成功后服务端返回auth code,然后客户端使用auth code去服务器端换取access token,最好根据access token获取用户信息进行客户端的登录绑定。这个可以参照如很多网站的新浪微博登录功能,或其他的第三方帐号登录功能。

POM依赖

此处我们使用apache oltu oauth2客户端实现。

  1. <dependency>
  2. <groupId>org.apache.oltu.oauth2</groupId>
  3. <artifactId>org.apache.oltu.oauth2.client</artifactId>
  4. <version>0.31</version>
  5. </dependency>

其他的请参考pom.xml。

OAuth2Token

类似于UsernamePasswordToken和CasToken;用于存储oauth2服务端返回的auth code。

  1. public class OAuth2Token implements AuthenticationToken {
  2. private String authCode;
  3. private String principal;
  4. public OAuth2Token(String authCode) {
  5. this.authCode = authCode;
  6. }
  7. //省略getter/setter
  8. }

OAuth2AuthenticationFilter

该filter的作用类似于FormAuthenticationFilter用于oauth2客户端的身份验证控制;如果当前用户还没有身份验证,首先会判断url中是否有code(服务端返回的auth code),如果没有则重定向到服务端进行登录并授权,然后返回auth code;接着OAuth2AuthenticationFilter会用auth code创建OAuth2Token,然后提交给Subject.login进行登录;接着OAuth2Realm会根据OAuth2Token进行相应的登录逻辑。

  1. public class OAuth2AuthenticationFilter extends AuthenticatingFilter {
  2. //oauth2 authc code参数名
  3. private String authcCodeParam = "code";
  4. //客户端id
  5. private String clientId;
  6. //服务器端登录成功/失败后重定向到的客户端地址
  7. private String redirectUrl;
  8. //oauth2服务器响应类型
  9. private String responseType = "code";
  10. private String failureUrl;
  11. //省略setter
  12. protected AuthenticationToken createToken(ServletRequest request, ServletResponse response) throws Exception {
  13. HttpServletRequest httpRequest = (HttpServletRequest) request;
  14. String code = httpRequest.getParameter(authcCodeParam);
  15. return new OAuth2Token(code);
  16. }
  17. protected boolean isAccessAllowed(ServletRequest request, ServletResponse response, Object mappedValue) {
  18. return false;
  19. }
  20. protected boolean onAccessDenied(ServletRequest request, ServletResponse response) throws Exception {
  21. String error = request.getParameter("error");
  22. String errorDescription = request.getParameter("error_description");
  23. if(!StringUtils.isEmpty(error)) {//如果服务端返回了错误
  24. WebUtils.issueRedirect(request, response, failureUrl + "?error=" + error + "error_description=" + errorDescription);
  25. return false;
  26. }
  27. Subject subject = getSubject(request, response);
  28. if(!subject.isAuthenticated()) {
  29. if(StringUtils.isEmpty(request.getParameter(authcCodeParam))) {
  30. //如果用户没有身份验证,且没有auth code,则重定向到服务端授权
  31. saveRequestAndRedirectToLogin(request, response);
  32. return false;
  33. }
  34. }
  35. //执行父类里的登录逻辑,调用Subject.login登录
  36. return executeLogin(request, response);
  37. }
  38. //登录成功后的回调方法 重定向到成功页面
  39. protected boolean onLoginSuccess(AuthenticationToken token, Subject subject, ServletRequest request,  ServletResponse response) throws Exception {
  40. issueSuccessRedirect(request, response);
  41. return false;
  42. }
  43. //登录失败后的回调
  44. protected boolean onLoginFailure(AuthenticationToken token, AuthenticationException ae, ServletRequest request,
  45. ServletResponse response) {
  46. Subject subject = getSubject(request, response);
  47. if (subject.isAuthenticated() || subject.isRemembered()) {
  48. try { //如果身份验证成功了 则也重定向到成功页面
  49. issueSuccessRedirect(request, response);
  50. } catch (Exception e) {
  51. e.printStackTrace();
  52. }
  53. } else {
  54. try { //登录失败时重定向到失败页面
  55. WebUtils.issueRedirect(request, response, failureUrl);
  56. } catch (IOException e) {
  57. e.printStackTrace();
  58. }
  59. }
  60. return false;
  61. }
  62. }

该拦截器的作用:

1、首先判断有没有服务端返回的error参数,如果有则直接重定向到失败页面;

2、接着如果用户还没有身份验证,判断是否有auth code参数(即是不是服务端授权之后返回的),如果没有则重定向到服务端进行授权;

3、否则调用executeLogin进行登录,通过auth code创建OAuth2Token提交给Subject进行登录;

4、登录成功将回调onLoginSuccess方法重定向到成功页面;

5、登录失败则回调onLoginFailure重定向到失败页面。

OAuth2Realm

  1. public class OAuth2Realm extends AuthorizingRealm {
  2. private String clientId;
  3. private String clientSecret;
  4. private String accessTokenUrl;
  5. private String userInfoUrl;
  6. private String redirectUrl;
  7. //省略setter
  8. public boolean supports(AuthenticationToken token) {
  9. return token instanceof OAuth2Token; //表示此Realm只支持OAuth2Token类型
  10. }
  11. protected AuthorizationInfo doGetAuthorizationInfo(PrincipalCollection principals) {
  12. SimpleAuthorizationInfo authorizationInfo = new SimpleAuthorizationInfo();
  13. return authorizationInfo;
  14. }
  15. protected AuthenticationInfo doGetAuthenticationInfo(AuthenticationToken token) throws AuthenticationException {
  16. OAuth2Token oAuth2Token = (OAuth2Token) token;
  17. String code = oAuth2Token.getAuthCode(); //获取 auth code
  18. String username = extractUsername(code); // 提取用户名
  19. SimpleAuthenticationInfo authenticationInfo =
  20. new SimpleAuthenticationInfo(username, code, getName());
  21. return authenticationInfo;
  22. }
  23. private String extractUsername(String code) {
  24. try {
  25. OAuthClient oAuthClient = new OAuthClient(new URLConnectionClient());
  26. OAuthClientRequest accessTokenRequest = OAuthClientRequest
  27. .tokenLocation(accessTokenUrl)
  28. .setGrantType(GrantType.AUTHORIZATION_CODE)
  29. .setClientId(clientId).setClientSecret(clientSecret)
  30. .setCode(code).setRedirectURI(redirectUrl)
  31. .buildQueryMessage();
  32. //获取access token
  33. OAuthAccessTokenResponse oAuthResponse =
  34. oAuthClient.accessToken(accessTokenRequest, OAuth.HttpMethod.POST);
  35. String accessToken = oAuthResponse.getAccessToken();
  36. Long expiresIn = oAuthResponse.getExpiresIn();
  37. //获取user info
  38. OAuthClientRequest userInfoRequest =
  39. new OAuthBearerClientRequest(userInfoUrl)
  40. .setAccessToken(accessToken).buildQueryMessage();
  41. OAuthResourceResponse resourceResponse = oAuthClient.resource(
  42. userInfoRequest, OAuth.HttpMethod.GET, OAuthResourceResponse.class);
  43. String username = resourceResponse.getBody();
  44. return username;
  45. } catch (Exception e) {
  46. throw new OAuth2AuthenticationException(e);
  47. }
  48. }
  49. }

此Realm首先只支持OAuth2Token类型的Token;然后通过传入的auth code去换取access token;再根据access token去获取用户信息(用户名),然后根据此信息创建AuthenticationInfo;如果需要AuthorizationInfo信息,可以根据此处获取的用户名再根据自己的业务规则去获取。

Spring shiro配置(spring-config-shiro.xml) 

  1. <bean id="oAuth2Realm"
  2. class="com.github.zhangkaitao.shiro.chapter18.oauth2.OAuth2Realm">
  3. <property name="cachingEnabled" value="true"/>
  4. <property name="authenticationCachingEnabled" value="true"/>
  5. <property name="authenticationCacheName" value="authenticationCache"/>
  6. <property name="authorizationCachingEnabled" value="true"/>
  7. <property name="authorizationCacheName" value="authorizationCache"/>
  8. <property name="clientId" value="c1ebe466-1cdc-4bd3-ab69-77c3561b9dee"/>
  9. <property name="clientSecret" value="d8346ea2-6017-43ed-ad68-19c0f971738b"/>
  10. <property name="accessTokenUrl"
  11. value="http://localhost:8080/chapter17-server/accessToken"/>
  12. <property name="userInfoUrl" value="http://localhost:8080/chapter17-server/userInfo"/>
  13. <property name="redirectUrl" value="http://localhost:9080/chapter17-client/oauth2-login"/>
  14. </bean>

此OAuth2Realm需要配置在服务端申请的clientId和clientSecret;及用于根据auth code换取access token的accessTokenUrl地址;及用于根据access token换取用户信息(受保护资源)的userInfoUrl地址。

  1. <bean id="oAuth2AuthenticationFilter"
  2. class="com.github.zhangkaitao.shiro.chapter18.oauth2.OAuth2AuthenticationFilter">
  3. <property name="authcCodeParam" value="code"/>
  4. <property name="failureUrl" value="/oauth2Failure.jsp"/>
  5. </bean>

此OAuth2AuthenticationFilter用于拦截服务端重定向回来的auth code。

  1. <bean id="shiroFilter" class="org.apache.shiro.spring.web.ShiroFilterFactoryBean">
  2. <property name="securityManager" ref="securityManager"/>
  3. <property name="loginUrl" value="http://localhost:8080/chapter17-server/authorize?client_id=c1ebe466-1cdc-4bd3-ab69-77c3561b9dee&amp;response_type=code&amp;redirect_uri=http://localhost:9080/chapter17-client/oauth2-login"/>
  4. <property name="successUrl" value="/"/>
  5. <property name="filters">
  6. <util:map>
  7. <entry key="oauth2Authc" value-ref="oAuth2AuthenticationFilter"/>
  8. </util:map>
  9. </property>
  10. <property name="filterChainDefinitions">
  11. <value>
  12. / = anon
  13. /oauth2Failure.jsp = anon
  14. /oauth2-login = oauth2Authc
  15. /logout = logout
  16. /** = user
  17. </value>
  18. </property>
  19. </bean>

此处设置loginUrl为http://localhost:8080/chapter17-server/authorize

?client_id=c1ebe466-1cdc-4bd3-ab69-77c3561b9dee&amp;response_type=code&amp;redirect_uri=http://localhost:9080/chapter17-client/oauth2-login";其会自动设置到所有的AccessControlFilter,如oAuth2AuthenticationFilter;另外/oauth2-login = oauth2Authc表示/oauth2-login地址使用oauth2Authc拦截器拦截并进行oauth2客户端授权。

测试

1、首先访问http://localhost:9080/chapter17-client/,然后点击登录按钮进行登录,会跳到如下页面:

2、输入用户名进行登录并授权;

3、如果登录成功,服务端会重定向到客户端,即之前客户端提供的地址http://localhost:9080/chapter17-client/oauth2-login?code=473d56015bcf576f2ca03eac1a5bcc11,并带着auth code过去;

4、客户端的OAuth2AuthenticationFilter会收集此auth code,并创建OAuth2Token提交给Subject进行客户端登录;

5、客户端的Subject会委托给OAuth2Realm进行身份验证;此时OAuth2Realm会根据auth code换取access token,再根据access token获取受保护的用户信息;然后进行客户端登录。

到此OAuth2的集成就完成了,此处的服务端和客户端相对比较简单,没有进行一些异常检测,请参考如新浪微博进行相应API及异常错误码的设计。

第十八章 并发登录人数控制——《跟我学Shiro》

在某些项目中可能会遇到如每个账户同时只能有一个人登录或几个人同时登录,如果同时有多人登录:要么不让后者登录;要么踢出前者登录(强制退出)。比如spring security就直接提供了相应的功能;Shiro的话没有提供默认实现,不过可以很容易的在Shiro中加入这个功能。

示例代码基于《第十六章 综合实例》完成,通过Shiro Filter机制扩展KickoutSessionControlFilter完成。

首先来看看如何配置使用(spring-config-shiro.xml

kickoutSessionControlFilter用于控制并发登录人数的

  1. <bean id="kickoutSessionControlFilter"
  2. class="com.github.zhangkaitao.shiro.chapter18.web.shiro.filter.KickoutSessionControlFilter">
  3. <property name="cacheManager" ref="cacheManager"/>
  4. <property name="sessionManager" ref="sessionManager"/>
  5. <property name="kickoutAfter" value="false"/>
  6. <property name="maxSession" value="2"/>
  7. <property name="kickoutUrl" value="/login?kickout=1"/>
  8. </bean>

cacheManager:使用cacheManager获取相应的cache来缓存用户登录的会话;用于保存用户—会话之间的关系的;

sessionManager:用于根据会话ID,获取会话进行踢出操作的;

kickoutAfter:是否踢出后来登录的,默认是false;即后者登录的用户踢出前者登录的用户;

maxSession:同一个用户最大的会话数,默认1;比如2的意思是同一个用户允许最多同时两个人登录;

kickoutUrl:被踢出后重定向到的地址;

shiroFilter配置

  1. <bean id="shiroFilter" class="org.apache.shiro.spring.web.ShiroFilterFactoryBean">
  2. <property name="securityManager" ref="securityManager"/>
  3. <property name="loginUrl" value="/login"/>
  4. <property name="filters">
  5. <util:map>
  6. <entry key="authc" value-ref="formAuthenticationFilter"/>
  7. <entry key="sysUser" value-ref="sysUserFilter"/>
  8. <entry key="kickout" value-ref="kickoutSessionControlFilter"/>
  9. </util:map>
  10. </property>
  11. <property name="filterChainDefinitions">
  12. <value>
  13. /login = authc
  14. /logout = logout
  15. /authenticated = authc
  16. /** = kickout,user,sysUser
  17. </value>
  18. </property>
  19. </bean>

此处配置除了登录等之外的地址都走kickout拦截器进行并发登录控制。

测试

此处因为maxSession=2,所以需要打开3个浏览器(需要不同的浏览器,如IE、Chrome、Firefox),分别访问http://localhost:8080/chapter18/进行登录;然后刷新第一次打开的浏览器,将会被强制退出,如显示下图:

KickoutSessionControlFilter核心代码:

  1. protected boolean onAccessDenied(ServletRequest request, ServletResponse response) throws Exception {
  2. Subject subject = getSubject(request, response);
  3. if(!subject.isAuthenticated() && !subject.isRemembered()) {
  4. //如果没有登录,直接进行之后的流程
  5. return true;
  6. }
  7. Session session = subject.getSession();
  8. String username = (String) subject.getPrincipal();
  9. Serializable sessionId = session.getId();
  10. //TODO 同步控制
  11. Deque<Serializable> deque = cache.get(username);
  12. if(deque == null) {
  13. deque = new LinkedList<Serializable>();
  14. cache.put(username, deque);
  15. }
  16. //如果队列里没有此sessionId,且用户没有被踢出;放入队列
  17. if(!deque.contains(sessionId) && session.getAttribute("kickout") == null) {
  18. deque.push(sessionId);
  19. }
  20. //如果队列里的sessionId数超出最大会话数,开始踢人
  21. while(deque.size() > maxSession) {
  22. Serializable kickoutSessionId = null;
  23. if(kickoutAfter) { //如果踢出后者
  24. kickoutSessionId = deque.removeFirst();
  25. } else { //否则踢出前者
  26. kickoutSessionId = deque.removeLast();
  27. }
  28. try {
  29. Session kickoutSession =
  30. sessionManager.getSession(new DefaultSessionKey(kickoutSessionId));
  31. if(kickoutSession != null) {
  32. //设置会话的kickout属性表示踢出了
  33. kickoutSession.setAttribute("kickout", true);
  34. }
  35. } catch (Exception e) {//ignore exception
  36. }
  37. }
  38. //如果被踢出了,直接退出,重定向到踢出后的地址
  39. if (session.getAttribute("kickout") != null) {
  40. //会话被踢出了
  41. try {
  42. subject.logout();
  43. } catch (Exception e) { //ignore
  44. }
  45. saveRequest(request);
  46. WebUtils.issueRedirect(request, response, kickoutUrl);
  47. return false;
  48. }
  49. return true;
  50. }

此处使用了Cache缓存用户名—会话id之间的关系;如果量比较大可以考虑如持久化到数据库/其他带持久化的Cache中;另外此处没有并发控制的同步实现,可以考虑根据用户名获取锁来控制,减少锁的粒度。

第十九章 动态URL权限控制——《跟我学Shiro》

用过Spring Security的朋友应该比较熟悉对URL进行全局的权限控制,即访问URL时进行权限匹配;如果没有权限直接跳到相应的错误页面。Shiro也支持类似的机制,不过需要稍微改造下来满足实际需求。不过在Shiro中,更多的是通过AOP进行分散的权限控制,即方法级别的;而通过URL进行权限控制是一种集中的权限控制。本章将介绍如何在Shiro中完成动态URL权限控制。

本章代码基于《第十六章 综合实例》,请先了解相关数据模型及基本流程后再学习本章。

表及数据SQL

请运行shiro-example-chapter19/sql/ shiro-schema.sql 表结构

请运行shiro-example-chapter19/sql/ shiro-schema.sql 数据

实体

具体请参考com.github.zhangkaitao.shiro.chapter19包下的实体。

  1. public class UrlFilter implements Serializable {
  2. private Long id;
  3. private String name; //url名称/描述
  4. private String url; //地址
  5. private String roles; //所需要的角色,可省略
  6. private String permissions; //所需要的权限,可省略
  7. }

表示拦截的URL和角色/权限之间的关系,多个角色/权限之间通过逗号分隔,此处还可以扩展其他的关系,另外可以加如available属性表示是否开启该拦截。

DAO

具体请参考com.github.zhangkaitao.shiro.chapter19.dao包下的DAO接口及实现。

Service

具体请参考com.github.zhangkaitao.shiro.chapter19.service包下的Service接口及实现。

  1. public interface UrlFilterService {
  2. public UrlFilter createUrlFilter(UrlFilter urlFilter);
  3. public UrlFilter updateUrlFilter(UrlFilter urlFilter);
  4. public void deleteUrlFilter(Long urlFilterId);
  5. public UrlFilter findOne(Long urlFilterId);
  6. public List<UrlFilter> findAll();
  7. }

基本的URL拦截的增删改查实现。

  1. @Service
  2. public class UrlFilterServiceImpl implements UrlFilterService {
  3. @Autowired
  4. private ShiroFilerChainManager shiroFilerChainManager;
  5. @Override
  6. public UrlFilter createUrlFilter(UrlFilter urlFilter) {
  7. urlFilterDao.createUrlFilter(urlFilter);
  8. initFilterChain();
  9. return urlFilter;
  10. }
  11. //其他方法请参考源码
  12. @PostConstruct
  13. public void initFilterChain() {
  14. shiroFilerChainManager.initFilterChains(findAll());
  15. }
  16. }

UrlFilterServiceImpl在进行新增、修改、删除时会调用initFilterChain来重新初始化Shiro的URL拦截器链,即同步数据库中的URL拦截器定义到Shiro中。此处也要注意如果直接修改数据库是不会起作用的,因为只要调用这几个Service方法时才同步。另外当容器启动时会自动回调initFilterChain来完成容器启动后的URL拦截器的注册。

ShiroFilerChainManager

  1. @Service
  2. public class ShiroFilerChainManager {
  3. @Autowired private DefaultFilterChainManager filterChainManager;
  4. private Map<String, NamedFilterList> defaultFilterChains;
  5. @PostConstruct
  6. public void init() {
  7. defaultFilterChains =
  8. new HashMap<String, NamedFilterList>(filterChainManager.getFilterChains());
  9. }
  10. public void initFilterChains(List<UrlFilter> urlFilters) {
  11. //1、首先删除以前老的filter chain并注册默认的
  12. filterChainManager.getFilterChains().clear();
  13. if(defaultFilterChains != null) {
  14. filterChainManager.getFilterChains().putAll(defaultFilterChains);
  15. }
  16. //2、循环URL Filter 注册filter chain
  17. for (UrlFilter urlFilter : urlFilters) {
  18. String url = urlFilter.getUrl();
  19. //注册roles filter
  20. if (!StringUtils.isEmpty(urlFilter.getRoles())) {
  21. filterChainManager.addToChain(url, "roles", urlFilter.getRoles());
  22. }
  23. //注册perms filter
  24. if (!StringUtils.isEmpty(urlFilter.getPermissions())) {
  25. filterChainManager.addToChain(url, "perms", urlFilter.getPermissions());
  26. }
  27. }
  28. }
  29. }

1、init:Spring容器启动时会调用init方法把在spring配置文件中配置的默认拦截器保存下来,之后会自动与数据库中的配置进行合并。

2、initFilterChains:UrlFilterServiceImpl会在Spring容器启动或进行增删改UrlFilter时进行注册URL拦截器到Shiro。

拦截器及拦截器链知识请参考《第八章 拦截器机制》,此处再介绍下Shiro拦截器的流程:

AbstractShiroFilter //如ShiroFilter/ SpringShiroFilter都继承该Filter

doFilter //Filter的doFilter

doFilterInternal //转调doFilterInternal

executeChain(request, response, chain) //执行拦截器链

FilterChain chain = getExecutionChain(request, response, origChain) //使用原始拦截器链获取新的拦截器链

chain.doFilter(request, response) //执行新组装的拦截器链

getExecutionChain(request, response, origChain) //获取拦截器链流程

FilterChainResolver resolver = getFilterChainResolver(); //获取相应的FilterChainResolver

FilterChain resolved = resolver.getChain(request, response, origChain); //通过FilterChainResolver根据当前请求解析到新的FilterChain拦截器链

默认情况下如使用ShiroFilterFactoryBean创建shiroFilter时,默认使用PathMatchingFilterChainResolver进行解析,而它默认是根据当前请求的URL获取相应的拦截器链,使用Ant模式进行URL匹配;默认使用DefaultFilterChainManager进行拦截器链的管理。

PathMatchingFilterChainResolver默认流程:

  1. public FilterChain getChain(ServletRequest request, ServletResponse response, FilterChain originalChain) {
  2. //1、首先获取拦截器链管理器
  3. FilterChainManager filterChainManager = getFilterChainManager();
  4. if (!filterChainManager.hasChains()) {
  5. return null;
  6. }
  7. //2、接着获取当前请求的URL(不带上下文)
  8. String requestURI = getPathWithinApplication(request);
  9. //3、循环拦截器管理器中的拦截器定义(拦截器链的名字就是URL模式)
  10. for (String pathPattern : filterChainManager.getChainNames()) {
  11. //4、如当前URL匹配拦截器名字(URL模式)
  12. if (pathMatches(pathPattern, requestURI)) {
  13. //5、返回该URL模式定义的拦截器链
  14. return filterChainManager.proxy(originalChain, pathPattern);
  15. }
  16. }
  17. return null;
  18. }

默认实现有点小问题:

如果多个拦截器链都匹配了当前请求URL,那么只返回第一个找到的拦截器链;后续我们可以修改此处的代码,将多个匹配的拦截器链合并返回。

DefaultFilterChainManager内部使用Map来管理URL模式-拦截器链的关系;也就是说相同的URL模式只能定义一个拦截器链,不能重复定义;而且如果多个拦截器链都匹配时是无序的(因为使用map.keySet()获取拦截器链的名字,即URL模式)。

FilterChainManager接口:

  1. public interface FilterChainManager {
  2. Map<String, Filter> getFilters(); //得到注册的拦截器
  3. void addFilter(String name, Filter filter); //注册拦截器
  4. void addFilter(String name, Filter filter, boolean init); //注册拦截器
  5. void createChain(String chainName, String chainDefinition); //根据拦截器链定义创建拦截器链
  6. void addToChain(String chainName, String filterName); //添加拦截器到指定的拦截器链
  7. void addToChain(String chainName, String filterName, String chainSpecificFilterConfig) throws ConfigurationException; //添加拦截器(带有配置的)到指定的拦截器链
  8. NamedFilterList getChain(String chainName); //获取拦截器链
  9. boolean hasChains(); //是否有拦截器链
  10. Set<String> getChainNames(); //得到所有拦截器链的名字
  11. FilterChain proxy(FilterChain original, String chainName); //使用指定的拦截器链代理原始拦截器链
  12. }

此接口主要三个功能:注册拦截器,注册拦截器链,对原始拦截器链生成代理之后的拦截器链,比如

  1. <bean id="shiroFilter" class="org.apache.shiro.spring.web.ShiroFilterFactoryBean">
  2. ……
  3. <property name="filters">
  4. <util:map>
  5. <entry key="authc" value-ref="formAuthenticationFilter"/>
  6. <entry key="sysUser" value-ref="sysUserFilter"/>
  7. </util:map>
  8. </property>
  9. <property name="filterChainDefinitions">
  10. <value>
  11. /login = authc
  12. /logout = logout
  13. /authenticated = authc
  14. /** = user,sysUser
  15. </value>
  16. </property>
  17. </bean>

filters属性定义了拦截器;filterChainDefinitions定义了拦截器链;如/**就是拦截器链的名字;而user,sysUser就是拦截器名字列表。

之前说过默认的PathMatchingFilterChainResolver和DefaultFilterChainManager不能满足我们的需求,我们稍微扩展了一下:

CustomPathMatchingFilterChainResolver

  1. public class CustomPathMatchingFilterChainResolver
  2. extends PathMatchingFilterChainResolver {
  3. private CustomDefaultFilterChainManager customDefaultFilterChainManager;
  4. public void setCustomDefaultFilterChainManager(
  5. CustomDefaultFilterChainManager customDefaultFilterChainManager) {
  6. this.customDefaultFilterChainManager = customDefaultFilterChainManager;
  7. setFilterChainManager(customDefaultFilterChainManager);
  8. }
  9. public FilterChain getChain(ServletRequest request, ServletResponse response, FilterChain originalChain) {
  10. FilterChainManager filterChainManager = getFilterChainManager();
  11. if (!filterChainManager.hasChains()) {
  12. return null;
  13. }
  14. String requestURI = getPathWithinApplication(request);
  15. List<String> chainNames = new ArrayList<String>();
  16. for (String pathPattern : filterChainManager.getChainNames()) {
  17. if (pathMatches(pathPattern, requestURI)) {
  18. chainNames.add(pathPattern);
  19. }
  20. }
  21. if(chainNames.size() == 0) {
  22. return null;
  23. }
  24. return customDefaultFilterChainManager.proxy(originalChain, chainNames);
  25. }
  26. }

和默认的PathMatchingFilterChainResolver区别是,此处得到所有匹配的拦截器链,然后通过调用CustomDefaultFilterChainManager.proxy(originalChain, chainNames)进行合并后代理。

CustomDefaultFilterChainManager

  1. public class CustomDefaultFilterChainManager extends DefaultFilterChainManager {
  2. private Map<String, String> filterChainDefinitionMap = null;
  3. private String loginUrl;
  4. private String successUrl;
  5. private String unauthorizedUrl;
  6. public CustomDefaultFilterChainManager() {
  7. setFilters(new LinkedHashMap<String, Filter>());
  8. setFilterChains(new LinkedHashMap<String, NamedFilterList>());
  9. addDefaultFilters(true);
  10. }
  11. public Map<String, String> getFilterChainDefinitionMap() {
  12. return filterChainDefinitionMap;
  13. }
  14. public void setFilterChainDefinitionMap(Map<String, String> filterChainDefinitionMap) {
  15. this.filterChainDefinitionMap = filterChainDefinitionMap;
  16. }
  17. public void setCustomFilters(Map<String, Filter> customFilters) {
  18. for(Map.Entry<String, Filter> entry : customFilters.entrySet()) {
  19. addFilter(entry.getKey(), entry.getValue(), false);
  20. }
  21. }
  22. public void setDefaultFilterChainDefinitions(String definitions) {
  23. Ini ini = new Ini();
  24. ini.load(definitions);
  25. Ini.Section section = ini.getSection(IniFilterChainResolverFactory.URLS);
  26. if (CollectionUtils.isEmpty(section)) {
  27. section = ini.getSection(Ini.DEFAULT_SECTION_NAME);
  28. }
  29. setFilterChainDefinitionMap(section);
  30. }
  31. public String getLoginUrl() {
  32. return loginUrl;
  33. }
  34. public void setLoginUrl(String loginUrl) {
  35. this.loginUrl = loginUrl;
  36. }
  37. public String getSuccessUrl() {
  38. return successUrl;
  39. }
  40. public void setSuccessUrl(String successUrl) {
  41. this.successUrl = successUrl;
  42. }
  43. public String getUnauthorizedUrl() {
  44. return unauthorizedUrl;
  45. }
  46. public void setUnauthorizedUrl(String unauthorizedUrl) {
  47. this.unauthorizedUrl = unauthorizedUrl;
  48. }
  49. @PostConstruct
  50. public void init() {
  51. Map<String, Filter> filters = getFilters();
  52. if (!CollectionUtils.isEmpty(filters)) {
  53. for (Map.Entry<String, Filter> entry : filters.entrySet()) {
  54. String name = entry.getKey();
  55. Filter filter = entry.getValue();
  56. applyGlobalPropertiesIfNecessary(filter);
  57. if (filter instanceof Nameable) {
  58. ((Nameable) filter).setName(name);
  59. }
  60. addFilter(name, filter, false);
  61. }
  62. }
  63. Map<String, String> chains = getFilterChainDefinitionMap();
  64. if (!CollectionUtils.isEmpty(chains)) {
  65. for (Map.Entry<String, String> entry : chains.entrySet()) {
  66. String url = entry.getKey();
  67. String chainDefinition = entry.getValue();
  68. createChain(url, chainDefinition);
  69. }
  70. }
  71. }
  72. protected void initFilter(Filter filter) {
  73. //ignore
  74. }
  75. public FilterChain proxy(FilterChain original, List<String> chainNames) {
  76. NamedFilterList configured = new SimpleNamedFilterList(chainNames.toString());
  77. for(String chainName : chainNames) {
  78. configured.addAll(getChain(chainName));
  79. }
  80. return configured.proxy(original);
  81. }
  82. private void applyGlobalPropertiesIfNecessary(Filter filter) {
  83. applyLoginUrlIfNecessary(filter);
  84. applySuccessUrlIfNecessary(filter);
  85. applyUnauthorizedUrlIfNecessary(filter);
  86. }
  87. private void applyLoginUrlIfNecessary(Filter filter) {
  88. //请参考源码
  89. }
  90. private void applySuccessUrlIfNecessary(Filter filter) {
  91. //请参考源码
  92. }
  93. private void applyUnauthorizedUrlIfNecessary(Filter filter) {
  94. //请参考源码
  95. }
  96. }

1、CustomDefaultFilterChainManager:调用其构造器时,会自动注册默认的拦截器;

2、loginUrl、successUrl、unauthorizedUrl:分别对应登录地址、登录成功后默认跳转地址、未授权跳转地址,用于给相应拦截器的;

3、filterChainDefinitionMap:用于存储如ShiroFilterFactoryBean在配置文件中配置的拦截器链定义,即可以认为是默认的静态拦截器链;会自动与数据库中加载的合并;

4、setDefaultFilterChainDefinitions:解析配置文件中传入的字符串拦截器链配置,解析为相应的拦截器链;

5、setCustomFilters:注册我们自定义的拦截器;如ShiroFilterFactoryBean的filters属性;

6、init:初始化方法,Spring容器启动时会调用,首先其会自动给相应的拦截器设置如loginUrl、successUrl、unauthorizedUrl;其次根据filterChainDefinitionMap构建默认的拦截器链;

7、initFilter:此处我们忽略实现initFilter,因为交给spring管理了,所以Filter的相关配置会在Spring配置中完成;

8、proxy:组合多个拦截器链为一个生成一个新的FilterChain代理。

Web层控制器 

请参考com.github.zhangkaitao.shiro.chapter19.web.controller包,相对于第十六章添加了UrlFilterController用于UrlFilter的维护。另外,移除了控制器方法上的权限注解,而是使用动态URL拦截进行控制。

Spring配置——spring-config-shiro.xml

  1. <bean id="filterChainManager"
  2. class="com.github.zhangkaitao.shiro.spring.CustomDefaultFilterChainManager">
  3. <property name="loginUrl" value="/login"/>
  4. <property name="successUrl" value="/"/>
  5. <property name="unauthorizedUrl" value="/unauthorized.jsp"/>
  6. <property name="customFilters">
  7. <util:map>
  8. <entry key="authc" value-ref="formAuthenticationFilter"/>
  9. <entry key="sysUser" value-ref="sysUserFilter"/>
  10. </util:map>
  11. </property>
  12. <property name="defaultFilterChainDefinitions">
  13. <value>
  14. /login = authc
  15. /logout = logout
  16. /unauthorized.jsp = authc
  17. /** = user,sysUser
  18. </value>
  19. </property>
  20. </bean>

filterChainManager是我们自定义的CustomDefaultFilterChainManager,注册相应的拦截器及默认的拦截器链。

  1. <bean id="filterChainResolver"
  2. class="com.github.zhangkaitao.shiro.spring.CustomPathMatchingFilterChainResolver">
  3. <property name="customDefaultFilterChainManager" ref="filterChainManager"/>
  4. </bean>

filterChainResolver是自定义的CustomPathMatchingFilterChainResolver,使用上边的filterChainManager进行拦截器链的管理。

  1. <bean id="shiroFilter" class="org.apache.shiro.spring.web.ShiroFilterFactoryBean">
  2. <property name="securityManager" ref="securityManager"/>
  3. </bean>

shiroFilter不再定义filters及filterChainDefinitions,而是交给了filterChainManager进行完成。

  1. <bean class="org.springframework.beans.factory.config.MethodInvokingFactoryBean">
  2. <property name="targetObject" ref="shiroFilter"/>
  3. <property name="targetMethod" value="setFilterChainResolver"/>
  4. <property name="arguments" ref="filterChainResolver"/>
  5. </bean>

最后把filterChainResolver注册给shiroFilter,其使用它进行动态URL权限控制。

其他配置和第十六章一样,请参考第十六章。

测试

1、首先执行shiro-data.sql初始化数据。

2、然后再URL管理中新增如下数据:

3、访问http://localhost:8080/chapter19/user时要求用户拥有aa角色,此时是没有的所以会跳转到未授权页面;

4、添加aa角色然后授权给用户,此时就有权限访问http://localhost:8080/chapter19/user。

实际项目可以在此基础上进行扩展。

第二十章 无状态Web应用集成——《跟我学Shiro》

在一些环境中,可能需要把Web应用做成无状态的,即服务器端无状态,就是说服务器端不会存储像会话这种东西,而是每次请求时带上相应的用户名进行登录。如一些REST风格的API,如果不使用OAuth2协议,就可以使用如REST+HMAC认证进行访问。HMAC(Hash-based Message Authentication Code):基于散列的消息认证码,使用一个密钥和一个消息作为输入,生成它们的消息摘要。注意该密钥只有客户端和服务端知道,其他第三方是不知道的。访问时使用该消息摘要进行传播,服务端然后对该消息摘要进行验证。如果只传递用户名+密码的消息摘要,一旦被别人捕获可能会重复使用该摘要进行认证。解决办法如:

1、每次客户端申请一个Token,然后使用该Token进行加密,而该Token是一次性的,即只能用一次;有点类似于OAuth2的Token机制,但是简单些;

2、客户端每次生成一个唯一的Token,然后使用该Token加密,这样服务器端记录下这些Token,如果之前用过就认为是非法请求。

为了简单,本文直接对请求的数据(即全部请求的参数)生成消息摘要,即无法篡改数据,但是可能被别人窃取而能多次调用。解决办法如上所示。

服务器端

对于服务器端,不生成会话,而是每次请求时带上用户身份进行认证。

服务控制器

  1. @RestController
  2. public class ServiceController {
  3. @RequestMapping("/hello")
  4. public String hello1(String[] param1, String param2) {
  5. return "hello" + param1[0] + param1[1] + param2;
  6. }
  7. }

当访问/hello服务时,需要传入param1、param2两个请求参数。

加密工具类

com.github.zhangkaitao.shiro.chapter20.codec.HmacSHA256Utils:

  1. //使用指定的密码对内容生成消息摘要(散列值)
  2. public static String digest(String key, String content);
  3. //使用指定的密码对整个Map的内容生成消息摘要(散列值)
  4. public static String digest(String key, Map<String, ?> map)

对Map生成消息摘要主要用于对客户端/服务器端来回传递的参数生成消息摘要。

Subject工厂

  1. public class StatelessDefaultSubjectFactory extends DefaultWebSubjectFactory {
  2. public Subject createSubject(SubjectContext context) {
  3. //不创建session
  4. context.setSessionCreationEnabled(false);
  5. return super.createSubject(context);
  6. }
  7. }

通过调用context.setSessionCreationEnabled(false)表示不创建会话;如果之后调用Subject.getSession()将抛出DisabledSessionException异常。

StatelessAuthcFilter

类似于FormAuthenticationFilter,但是根据当前请求上下文信息每次请求时都要登录的认证过滤器。

  1. public class StatelessAuthcFilter extends AccessControlFilter {
  2. protected boolean isAccessAllowed(ServletRequest request, ServletResponse response, Object mappedValue) throws Exception {
  3. return false;
  4. }
  5. protected boolean onAccessDenied(ServletRequest request, ServletResponse response) throws Exception {
  6. //1、客户端生成的消息摘要
  7. String clientDigest = request.getParameter(Constants.PARAM_DIGEST);
  8. //2、客户端传入的用户身份
  9. String username = request.getParameter(Constants.PARAM_USERNAME);
  10. //3、客户端请求的参数列表
  11. Map<String, String[]> params =
  12. new HashMap<String, String[]>(request.getParameterMap());
  13. params.remove(Constants.PARAM_DIGEST);
  14. //4、生成无状态Token
  15. StatelessToken token = new StatelessToken(username, params, clientDigest);
  16. try {
  17. //5、委托给Realm进行登录
  18. getSubject(request, response).login(token);
  19. } catch (Exception e) {
  20. e.printStackTrace();
  21. onLoginFail(response); //6、登录失败
  22. return false;
  23. }
  24. return true;
  25. }
  26. //登录失败时默认返回401状态码
  27. private void onLoginFail(ServletResponse response) throws IOException {
  28. HttpServletResponse httpResponse = (HttpServletResponse) response;
  29. httpResponse.setStatus(HttpServletResponse.SC_UNAUTHORIZED);
  30. httpResponse.getWriter().write("login error");
  31. }
  32. }

获取客户端传入的用户名、请求参数、消息摘要,生成StatelessToken;然后交给相应的Realm进行认证。

StatelessToken 

  1. public class StatelessToken implements AuthenticationToken {
  2. private String username;
  3. private Map<String, ?> params;
  4. private String clientDigest;
  5. //省略部分代码
  6. public Object getPrincipal() {  return username;}
  7. public Object getCredentials() {  return clientDigest;}
  8. }

用户身份即用户名;凭证即客户端传入的消息摘要。

StatelessRealm

用于认证的Realm。

  1. public class StatelessRealm extends AuthorizingRealm {
  2. public boolean supports(AuthenticationToken token) {
  3. //仅支持StatelessToken类型的Token
  4. return token instanceof StatelessToken;
  5. }
  6. protected AuthorizationInfo doGetAuthorizationInfo(PrincipalCollection principals) {
  7. //根据用户名查找角色,请根据需求实现
  8. String username = (String) principals.getPrimaryPrincipal();
  9. SimpleAuthorizationInfo authorizationInfo =  new SimpleAuthorizationInfo();
  10. authorizationInfo.addRole("admin");
  11. return authorizationInfo;
  12. }
  13. protected AuthenticationInfo doGetAuthenticationInfo(AuthenticationToken token) throws AuthenticationException {
  14. StatelessToken statelessToken = (StatelessToken) token;
  15. String username = statelessToken.getUsername();
  16. String key = getKey(username);//根据用户名获取密钥(和客户端的一样)
  17. //在服务器端生成客户端参数消息摘要
  18. String serverDigest = HmacSHA256Utils.digest(key, statelessToken.getParams());
  19. //然后进行客户端消息摘要和服务器端消息摘要的匹配
  20. return new SimpleAuthenticationInfo(
  21. username,
  22. serverDigest,
  23. getName());
  24. }
  25. private String getKey(String username) {//得到密钥,此处硬编码一个
  26. if("admin".equals(username)) {
  27. return "dadadswdewq2ewdwqdwadsadasd";
  28. }
  29. return null;
  30. }
  31. }

此处首先根据客户端传入的用户名获取相应的密钥,然后使用密钥对请求参数生成服务器端的消息摘要;然后与客户端的消息摘要进行匹配;如果匹配说明是合法客户端传入的;否则是非法的。这种方式是有漏洞的,一旦别人获取到该请求,可以重复请求;可以考虑之前介绍的解决方案。

Spring配置——spring-config-shiro.xml

  1. <!-- Realm实现 -->
  2. <bean id="statelessRealm"
  3. class="com.github.zhangkaitao.shiro.chapter20.realm.StatelessRealm">
  4. <property name="cachingEnabled" value="false"/>
  5. </bean>
  6. <!-- Subject工厂 -->
  7. <bean id="subjectFactory"
  8. class="com.github.zhangkaitao.shiro.chapter20.mgt.StatelessDefaultSubjectFactory"/>
  9. <!-- 会话管理器 -->
  10. <bean id="sessionManager" class="org.apache.shiro.session.mgt.DefaultSessionManager">
  11. <property name="sessionValidationSchedulerEnabled" value="false"/>
  12. </bean>
  13. <!-- 安全管理器 -->
  14. <bean id="securityManager" class="org.apache.shiro.web.mgt.DefaultWebSecurityManager">
  15. <property name="realm" ref="statelessRealm"/>
  16. <property name="subjectDAO.sessionStorageEvaluator.sessionStorageEnabled"
  17. value="false"/>
  18. <property name="subjectFactory" ref="subjectFactory"/>
  19. <property name="sessionManager" ref="sessionManager"/>
  20. </bean>
  21. <!-- 相当于调用SecurityUtils.setSecurityManager(securityManager) -->
  22. <bean class="org.springframework.beans.factory.config.MethodInvokingFactoryBean">
  23. <property name="staticMethod"
  24. value="org.apache.shiro.SecurityUtils.setSecurityManager"/>
  25. <property name="arguments" ref="securityManager"/>
  26. </bean>

sessionManager通过sessionValidationSchedulerEnabled禁用掉会话调度器,因为我们禁用掉了会话,所以没必要再定期过期会话了。

  1. <bean id="statelessAuthcFilter"
  2. class="com.github.zhangkaitao.shiro.chapter20.filter.StatelessAuthcFilter"/>

每次请求进行认证的拦截器。

  1. <!-- Shiro的Web过滤器 -->
  2. <bean id="shiroFilter" class="org.apache.shiro.spring.web.ShiroFilterFactoryBean">
  3. <property name="securityManager" ref="securityManager"/>
  4. <property name="filters">
  5. <util:map>
  6. <entry key="statelessAuthc" value-ref="statelessAuthcFilter"/>
  7. </util:map>
  8. </property>
  9. <property name="filterChainDefinitions">
  10. <value>
  11. /**=statelessAuthc
  12. </value>
  13. </property>
  14. </bean>

所有请求都将走statelessAuthc拦截器进行认证。

其他配置请参考源代码。

SpringMVC学习请参考:

5分钟构建spring web mvc REST风格HelloWorld

http://jinnianshilongnian.iteye.com/blog/1996071

跟我学SpringMVC

http://www.iteye.com/blogs/subjects/kaitao-springmvc

客户端

此处使用SpringMVC提供的RestTemplate进行测试。请参考如下文章进行学习:

Spring MVC测试框架详解——客户端测试

http://jinnianshilongnian.iteye.com/blog/2007180

Spring MVC测试框架详解——服务端测试

http://jinnianshilongnian.iteye.com/blog/2004660

此处为了方便,使用内嵌jetty服务器启动服务端:

  1. public class ClientTest {
  2. private static Server server;
  3. private RestTemplate restTemplate = new RestTemplate();
  4. @BeforeClass
  5. public static void beforeClass() throws Exception {
  6. //创建一个server
  7. server = new Server(8080);
  8. WebAppContext context = new WebAppContext();
  9. String webapp = "shiro-example-chapter20/src/main/webapp";
  10. context.setDescriptor(webapp + "/WEB-INF/web.xml");  //指定web.xml配置文件
  11. context.setResourceBase(webapp);  //指定webapp目录
  12. context.setContextPath("/");
  13. context.setParentLoaderPriority(true);
  14. server.setHandler(context);
  15. server.start();
  16. }
  17. @AfterClass
  18. public static void afterClass() throws Exception {
  19. server.stop(); //当测试结束时停止服务器
  20. }
  21. }

在整个测试开始之前开启服务器,整个测试结束时关闭服务器。

测试成功情况 

  1. @Test
  2. public void testServiceHelloSuccess() {
  3. String username = "admin";
  4. String param11 = "param11";
  5. String param12 = "param12";
  6. String param2 = "param2";
  7. String key = "dadadswdewq2ewdwqdwadsadasd";
  8. MultiValueMap<String, String> params = new LinkedMultiValueMap<String, String>();
  9. params.add(Constants.PARAM_USERNAME, username);
  10. params.add("param1", param11);
  11. params.add("param1", param12);
  12. params.add("param2", param2);
  13. params.add(Constants.PARAM_DIGEST, HmacSHA256Utils.digest(key, params));
  14. String url = UriComponentsBuilder
  15. .fromHttpUrl("http://localhost:8080/hello")
  16. .queryParams(params).build().toUriString();
  17. ResponseEntity responseEntity = restTemplate.getForEntity(url, String.class);
  18. Assert.assertEquals("hello" + param11 + param12 + param2, responseEntity.getBody());
  19. }

对请求参数生成消息摘要后带到参数中传递给服务器端,服务器端验证通过后访问相应服务,然后返回数据。

测试失败情况 

  1. @Test
  2. public void testServiceHelloFail() {
  3. String username = "admin";
  4. String param11 = "param11";
  5. String param12 = "param12";
  6. String param2 = "param2";
  7. String key = "dadadswdewq2ewdwqdwadsadasd";
  8. MultiValueMap<String, String> params = new LinkedMultiValueMap<String, String>();
  9. params.add(Constants.PARAM_USERNAME, username);
  10. params.add("param1", param11);
  11. params.add("param1", param12);
  12. params.add("param2", param2);
  13. params.add(Constants.PARAM_DIGEST, HmacSHA256Utils.digest(key, params));
  14. params.set("param2", param2 + "1");
  15. String url = UriComponentsBuilder
  16. .fromHttpUrl("http://localhost:8080/hello")
  17. .queryParams(params).build().toUriString();
  18. try {
  19. ResponseEntity responseEntity = restTemplate.getForEntity(url, String.class);
  20. } catch (HttpClientErrorException e) {
  21. Assert.assertEquals(HttpStatus.UNAUTHORIZED, e.getStatusCode());
  22. Assert.assertEquals("login error", e.getResponseBodyAsString());
  23. }
  24. }

在生成请求参数消息摘要后,篡改了参数内容,服务器端接收后进行重新生成消息摘要发现不一样,报401错误状态码。

到此,整个测试完成了,需要注意的是,为了安全性,请考虑本文开始介绍的相应解决方案。

学Shiro完结版-4的更多相关文章

  1. 跟我学Shiro目录贴

    转发地址:https://www.iteye.com/blog/jinnianshilongnian-2018398 扫一扫,关注我的公众号 购买地址 历经三个月左右时间,<跟我学Shiro&g ...

  2. 【知识整理】这可能是最好的RxJava 2.x 教程(完结版)

    为什么要学 RxJava? 提升开发效率,降低维护成本一直是开发团队永恒不变的宗旨.近两年来国内的技术圈子中越来越多的开始提及 RxJava ,越来越多的应用和面试中都会有 RxJava ,而就目前的 ...

  3. 第十七章 OAuth2集成——《跟我学Shiro》

    目录贴:跟我学Shiro目录贴 目前很多开放平台如新浪微博开放平台都在使用提供开放API接口供开发者使用,随之带来了第三方应用要到开放平台进行授权的问题,OAuth就是干这个的,OAuth2是OAut ...

  4. 第一章 Shiro简介——《跟我学Shiro》(转)

    目录贴:跟我学Shiro目录贴 1.1  简介 Apache Shiro是Java的一个安全框架.目前,使用Apache Shiro的人越来越多,因为它相当简单,对比Spring Security,可 ...

  5. 跟开涛老师学shiro -- 编码/加密

    在涉及到密码存储问题上,应该加密/生成密码摘要存储,而不是存储明文密码.比如之前的600w csdn账号泄露对用户可能造成很大损失,因此应加密/生成不可逆的摘要方式存储. 5.1 编码/解码 Shir ...

  6. 跟开涛老师学shiro -- INI配置

    之前章节我们已经接触过一些INI配置规则了,如果大家使用过如spring之类的IoC/DI容器的话,Shiro提供的INI配置也是非常类似的,即可以理解为是一个IoC/DI容器,但是区别在于它从一个根 ...

  7. 跟开涛老师学shiro -- 授权

    授权,也叫访问控制,即在应用中控制谁能访问哪些资源(如访问页面/编辑数据/页面操作等).在授权中需了解的几个关键对象:主体(Subject).资源(Resource).权限(Permission).角 ...

  8. 跟开涛老师学shiro -- 身份验证

    身份验证,即在应用中谁能证明他就是他本人.一般提供如他们的身份ID一些标识信息来表明他就是他本人,如提供身份证,用户名/密码来证明. 在shiro中,用户需要提供principals (身份)和cre ...

  9. 跟开涛老师学shiro -- shiro简介

    1.1  简介 Apache Shiro是Java的一个安全框架.目前,使用Apache Shiro的人越来越多,因为它相当简单,对比Spring Security,可能没有Spring Securi ...

  10. 【转】Android 开发规范(完结版)

    摘要 1 前言 2 AS 规范 3 命名规范 4 代码样式规范 5 资源文件规范 6 版本统一规范 7 第三方库规范 8 注释规范 9 测试规范 10 其他的一些规范 1 前言 为了有利于项目维护.增 ...

随机推荐

  1. C++ STL之map、multimap

    map和multimap是C++ STL(Standard Template Library)中的关联容器,它们提供键值对的存储和访问. map是一个有序关联容器,它存储一组键值对,其中每个键都是唯一 ...

  2. 关于MNN工程框架编译出来的静态库和动态库的使用

    一.MNN.lib文件路径 如果你看过之前的博客内容,应该可以在编译的的工程当中 C:\Users\Administrator\Desktop\MNN\MNN-master\MNN-CPU-OPENC ...

  3. DDCA —— 大缓存、虚拟内存:多核缓存、NUCA缓存、页表等

    1. 缓存中的多核问题 1.1 多核系统中的缓存 Intel Montecito缓存 两个 core,每个都有一个私有的12 MB的L3缓存和一个1 MB的L2缓存,图中深蓝色部分均为L3缓存. 在多 ...

  4. 鸿蒙Navigation入门使用

    Navigation组件适用于模块内和跨模块的路由切换,通过组件级路由能力实现更加自然流畅的转场体验,并提供多种标题栏样式来呈现更好的标题和内容联动效果.一次开发,多端部署场景下,Navigation ...

  5. 抓包工具之Fiddler(详解)

    Fiddle简介 Fiddler是最强大最好用的Web调试工具之一,它能记录所有客户端和服务器的http和https请求,允许你监视,设置断点,甚至修改输入输出数据,Fiddler包含了一个强大的基于 ...

  6. uniapp 消息推送

    1.前言 作为一个非原生App的开发者,对于手机系统的推送机制了解是是非有限的,只有了解清楚这些机制,后期的开发才会少踩很多坑,本文将对推送机制逻辑进行一个简单的梳理与记录 2.推送流程 推送流程1. ...

  7. LR语法分析算法

    LR语法分析器 组成:一个输入,一个输出,状态栈,驱动程序,语法分析表 注意:规约后需要寻找新的符号在栈顶状态上的转换 例如: 状态栈   符号栈       输入 0 5        $id    ...

  8. Jetpack Compose 的原理性文章

    正在写一篇关于UI的思考,接触到 Android 的 Jetpack Compose: 从第一原则撰写 | 可理解的胡言乱语

  9. JVM简介—2.垃圾回收器和内存分配策略

    大纲 1.垃圾回收概述 2.如何判断对象存活 3.各种引用介绍 4.垃圾收集的算法 5.垃圾收集器的设计 6.垃圾回收器列表 7.各种垃圾回收器详情 8.Stop The World现象 9.内存分配 ...

  10. Android7以上https抓包

    1. 问题描述 1.1 运行环境 1.2 问题描述 virtualXposed 不一定支持Android模拟器 无法抓包 https 请求 1.3 问题原因 Android7 以后,系统分了系统证书和 ...