1.自定义Realm
public class CustomRealm extends AuthorizingRealm {
@Autowired
private UserService userService;
@Override
protected AuthorizationInfo doGetAuthorizationInfo ( PrincipalCollection principals) {
System . out. println ( "授权开始.......doGetAuthorizationInfo" ) ;
User user = ( User ) principals. getPrimaryPrincipal ( ) ;
User userInfo = userService. findAllUserInfoByUsername ( user. getUsername ( ) ) ;
Set < String > roleList = new HashSet < > ( ) ;
Set < String > stringPermission = new HashSet < > ( ) ;
userInfo. getRoleList ( ) . forEach ( role -> {
roleList. add ( role. getName ( ) ) ;
if ( role. getPermissionList ( ) != null ) {
stringPermission. addAll ( role. getPermissionList ( ) . stream ( ) . map ( Permission :: getName ) . collect ( Collectors . toList ( ) ) ) ;
}
} ) ;
SimpleAuthorizationInfo authorizationInfo = new SimpleAuthorizationInfo ( ) ;
authorizationInfo. setRoles ( roleList) ;
authorizationInfo. setStringPermissions ( stringPermission) ;
return authorizationInfo;
}
@Override
protected AuthenticationInfo doGetAuthenticationInfo ( AuthenticationToken token) throws AuthenticationException {
System . out. println ( "认证开始........doGetAuthenticationInfo" ) ;
String username = ( String ) token. getPrincipal ( ) ;
User user = userService. findSimpleUserInfoByUsername ( username) ;
String pwd = user. getPassword ( ) ;
if ( pwd== null || "" . equals ( pwd) ) {
return null ;
}
return new SimpleAuthenticationInfo ( user, pwd, this . getClass ( ) . getName ( ) ) ;
}
}
2.自定义角色权限CustomRolesOrAuthorizationFilter
public class CustomRolesOrAuthorizationFilter extends AuthorizationFilter {
@Override
protected boolean isAccessAllowed ( ServletRequest request, ServletResponse response, Object mappedValue) throws Exception {
Subject subject = getSubject ( request, response) ;
String [ ] rolesArray = ( String [ ] ) mappedValue;
if ( rolesArray == null || rolesArray. length == 0 ) {
return true ;
}
Set < String > roles = CollectionUtils . asSet ( rolesArray) ;
for ( String role : roles) {
if ( subject. hasRole ( role) ) {
return true ;
}
}
return false ;
}
}
3.自定义SessionId生成
public class CustomSessionIdGenerator implements SessionIdGenerator {
@Override
public Serializable generateId ( Session session) {
return "xxx" + UUID . randomUUID ( ) . toString ( ) . replace ( "-" , "" ) ;
}
}
4.自定义会话管理器CustomSessionManager
public class CustomSessionManager extends DefaultWebSessionManager {
private static final String AUTHORIZATION = "token" ;
public CustomSessionManager ( ) {
super ( ) ;
}
@Override
protected Serializable getSessionId ( ServletRequest request, ServletResponse response) {
String sessionId = WebUtils . toHttp ( request) . getHeader ( AUTHORIZATION ) ;
if ( sessionId != null ) {
request. setAttribute ( ShiroHttpServletRequest . REFERENCED_SESSION_ID_SOURCE ,
ShiroHttpServletRequest . COOKIE_SESSION_ID_SOURCE ) ;
request. setAttribute ( ShiroHttpServletRequest . REFERENCED_SESSION_ID , sessionId) ;
request. setAttribute ( ShiroHttpServletRequest . REFERENCED_SESSION_ID_IS_VALID , Boolean . TRUE ) ;
return sessionId;
} else {
return super . getSessionId ( request, response) ;
}
}
}
5.shiro过滤器配置
@Configuration
public class ShiroConfig {
@Bean
public ShiroFilterFactoryBean shiroFilter ( SecurityManager securityManager) {
System . out. println ( "执行... ShiroFilterFactoryBean" ) ;
ShiroFilterFactoryBean shiroFilterFactoryBean = new ShiroFilterFactoryBean ( ) ;
shiroFilterFactoryBean. setSecurityManager ( securityManager) ;
shiroFilterFactoryBean. setLoginUrl ( "/pub/need_login" ) ;
shiroFilterFactoryBean. setSuccessUrl ( "/" ) ;
shiroFilterFactoryBean. setUnauthorizedUrl ( "/pub/not_permit" ) ;
Map < String , Filter > filterChainMap = new HashMap < > ( ) ;
filterChainMap. put ( "roleOrAuth" , new CustomRolesOrAuthorizationFilter ( ) ) ;
shiroFilterFactoryBean. setFilters ( filterChainMap) ;
Map < String , String > filterChainDefinitionMap = new LinkedHashMap < > ( ) ;
filterChainDefinitionMap. put ( "/logout" , DefaultFilter . logout. name ( ) ) ;
filterChainDefinitionMap. put ( "/pub/**" , DefaultFilter . anon. name ( ) ) ;
filterChainDefinitionMap. put ( "/authc/**" , DefaultFilter . authc. name ( ) ) ;
filterChainDefinitionMap. put ( "/admin/**" , "roleOrAuth[admin,root]" ) ;
filterChainDefinitionMap. put ( "/order/**" , "perms[order_update]" ) ;
filterChainDefinitionMap. put ( "/**" , "authc" ) ;
shiroFilterFactoryBean. setFilterChainDefinitionMap ( filterChainDefinitionMap) ;
return shiroFilterFactoryBean;
}
@Bean
public SecurityManager securityManager ( ) {
DefaultWebSecurityManager securityManager = new DefaultWebSecurityManager ( ) ;
securityManager. setSessionManager ( customSessionManager ( ) ) ;
securityManager. setCacheManager ( cacheManager ( ) ) ;
securityManager. setRealm ( customRealm ( ) ) ;
return securityManager;
}
@Bean
public CustomRealm customRealm ( ) {
CustomRealm customRealm = new CustomRealm ( ) ;
customRealm. setCredentialsMatcher ( hashedCredentialsMatcher ( ) ) ;
return customRealm;
}
@Bean
public HashedCredentialsMatcher hashedCredentialsMatcher ( ) {
HashedCredentialsMatcher credentialsMatcher = new HashedCredentialsMatcher ( ) ;
credentialsMatcher. setHashAlgorithmName ( "md5" ) ;
credentialsMatcher. setHashIterations ( 2 ) ;
return credentialsMatcher;
}
@Bean
public CustomSessionManager customSessionManager ( ) {
CustomSessionManager customSessionManager = new CustomSessionManager ( ) ;
customSessionManager. setGlobalSessionTimeout ( 200000 ) ;
customSessionManager. setSessionDAO ( redisSessionDAO ( ) ) ;
return customSessionManager;
}
@Bean
public RedisManager getRedisManager ( ) {
RedisManager redisManager = new RedisManager ( ) ;
redisManager. setHost ( "localhost" ) ;
redisManager. setPort ( 6379 ) ;
return redisManager;
}
@Bean
public CacheManager cacheManager ( ) {
RedisCacheManager redisCacheManager = new RedisCacheManager ( ) ;
redisCacheManager. setRedisManager ( getRedisManager ( ) ) ;
redisCacheManager. setExpire ( 20 ) ;
return redisCacheManager;
}
@Bean
public RedisSessionDAO redisSessionDAO ( ) {
RedisSessionDAO redisSessionDAO = new RedisSessionDAO ( ) ;
redisSessionDAO. setRedisManager ( getRedisManager ( ) ) ;
redisSessionDAO. setSessionIdGenerator ( new CustomSessionIdGenerator ( ) ) ;
return redisSessionDAO;
}
@Bean
public LifecycleBeanPostProcessor lifecycleBeanPostProcessor ( ) {
return new LifecycleBeanPostProcessor ( ) ;
}
@Bean
public AuthorizationAttributeSourceAdvisor authorizationAttributeSourceAdvisor ( )
{
AuthorizationAttributeSourceAdvisor authorizationAttributeSourceAdvisor = new
AuthorizationAttributeSourceAdvisor ( ) ;
authorizationAttributeSourceAdvisor. setSecurityManager ( securityManager ( ) ) ;
return authorizationAttributeSourceAdvisor;
}
@Bean
@DependsOn ( "lifecycleBeanPostProcessor" )
public DefaultAdvisorAutoProxyCreator getDefaultAdvisorAutoProxyCreator ( ) {
DefaultAdvisorAutoProxyCreator defaultAdvisorAutoProxyCreator= new
DefaultAdvisorAutoProxyCreator ( ) ;
defaultAdvisorAutoProxyCreator. setUsePrefix ( true ) ;
return defaultAdvisorAutoProxyCreator;
}
}