2017.11.20
SpringBoot之Shiro配置
(1)pom文件的dependency
<dependency> <groupId>org.apache.shiro</groupId> <artifactId>shiro-spring</artifactId> <version>1.3.2</version> <exclusions> <exclusion> <artifactId>slf4j-api</artifactId> <groupId>org.slf4j</groupId> </exclusion> </exclusions> </dependency>(2)在使用的Shiro的过程中,Shiro主要通过Subject的login方法将token传入自定义的Realm中,而springboot中shiro主要通过shiroFilter来过滤地址,同时在实现的ShiroFactoryBean中配置SecurityManager(安全管理器),安全管理主要讲用户的自定义的Realm装配至其中以实现安全管理,需要注意的是securityManager、shiroRealm都需要装配成bean,核心代码如下:
shiroFilter类
@Bean public ShiroFilterFactoryBean shirFilter(DefaultWebSecurityManager securityManager) { System.out.println("ShiroConfiguration.shirFilter()"); ShiroFilterFactoryBean shiroFilterFactoryBean = new ShiroFilterFactoryBean(); shiroFilterFactoryBean.setSecurityManager(securityManager); shiroFilterFactoryBean.setLoginUrl("/login"); //默认的登陆访问url shiroFilterFactoryBean.setSuccessUrl("/main"); //登陆成功后跳转的url shiroFilterFactoryBean.setUnauthorizedUrl("/403"); //没有权限跳转的url Map<String, String> hashMap = new LinkedHashMap<String, String>(); hashMap.put("logout","anon"); hashMap.put("/**","authc"); shiroFilterFactoryBean.setFilterChainDefinitionMap(hashMap); return shiroFilterFactoryBean; }
securityManager类
@Bean public DefaultWebSecurityManager securityManager(){ DefaultWebSecurityManager securityManager = new DefaultWebSecurityManager(); securityManager.setRealm(myShiroRealm()); return securityManager; }
shiroRealm的bean
@Bean public MyShiroRealm myShiroRealm(){ MyShiroRealm myShiroRealm = new MyShiroRealm(); return myShiroRealm; }该bean中的myShiroRealm类是获取token的关键,在该类中可以通过token中的数据判断是否通过验证,并且在shiro装配完之后执行subject.login(token)方法也会直接进入该类的doauthenticationInfo的方法,在这个方法中返回由对象、密码、盐、realm名组成的AuthenticationInfo,用于在controller中进行下一步判断:
@Override protected AuthenticationInfo doGetAuthenticationInfo(AuthenticationToken authenticationToken) throws AuthenticationException { try { UsernamePasswordToken token = (UsernamePasswordToken) authenticationToken; UserService userService = SpringContextUtil.getBean("userService"); UserModel user = userService.queryUserByName(token.getUsername()); if(null==user){ throw new UnknownAccountException(); } String password = user.getPassword(); // 密码加盐处理 String source = user.getSalt(); ByteSource credentialsSalt = new Md5Hash(source); SimpleAuthenticationInfo simpleAuthenticationInfo = new SimpleAuthenticationInfo( user, password, credentialsSalt, super.getName()); return simpleAuthenticationInfo; } catch (UnknownAccountException ua) { throw new UnknownAccountException(ua); } catch (Exception e){ throw new BusinessException("Error"); } }至此Shiro就配置完成了,虽然比较复杂,但是shiro强大的过滤和认证授权功能能够方便的使用,且能维护系统的安全,值得使用