Spring boot integrates shiro configuration

Keywords: Session Shiro Druid Redis

1. Configure lifecycle bean postprocessor to manage lifecycle
2. Configure ShiroFilterFactoryBean to set which paths require authentication and which do not
3. Enable shiro Aop annotation to support AuthorizationAttributeSourceAdvisor
4. Configure SecurityManager to manage custom realms, session s, and caches
Realm realizes login authentication and authorization
Session set timeout, session Dao (session cache can use shiro or radis), session monitoring
Cache can be set to shiro custom or radis
shiroConfig
/**
* Created by lenovo on 2019/4/2.
*/
@Configuration
public class shiroConfig {
//1. Configure lifecycle bean postprocessor to manage lifecycle
//2. Configure ShiroFilterFactoryBean to set which paths require authentication and which do not
//3. Enable shiro Aop annotation to support AuthorizationAttributeSourceAdvisor
//4. Configure SecurityManager to manage custom realms, session s, and caches
//Realm realizes login authentication and authorization
//Session set timeout, session Dao (session cache can use shiro or radis), session monitoring
//Cache can be set to shiro custom or radis

    //session timeout
    @Value("${server.session-timeout}")
    private int tomcatTimeout;

    //The best configuration for managing shiro bean life cycle
    @Bean
    public static LifecycleBeanPostProcessor getLifecycleBeanPostProcessor() {
        return new LifecycleBeanPostProcessor();
    }

    @Bean("shiroFilter")
    ShiroFilterFactoryBean shiroFilterFactoryBean(SecurityManager securityManager) {
        ShiroFilterFactoryBean shiroFilterFactoryBean = new ShiroFilterFactoryBean();
        shiroFilterFactoryBean.setSecurityManager(securityManager);
        shiroFilterFactoryBean.setLoginUrl("/login");
        shiroFilterFactoryBean.setSuccessUrl("/index");
        shiroFilterFactoryBean.setUnauthorizedUrl("/403");
        LinkedHashMap<String, String> filterChainDefinitionMap = new LinkedHashMap<>();
        filterChainDefinitionMap.put("/login","anon");
        filterChainDefinitionMap.put("/css/**", "anon");
        filterChainDefinitionMap.put("/js/**", "anon");
        filterChainDefinitionMap.put("/fonts/**", "anon");
        filterChainDefinitionMap.put("/img/**", "anon");
        filterChainDefinitionMap.put("/docs/**", "anon");
        filterChainDefinitionMap.put("/druid/**", "anon");
        filterChainDefinitionMap.put("/upload/**", "anon");
        filterChainDefinitionMap.put("/files/**", "anon");/*
        filterChainDefinitionMap.put("/logout", "logout");*/
        filterChainDefinitionMap.put("/", "anon");
        filterChainDefinitionMap.put("/login", "anon");
        filterChainDefinitionMap.put("/blog/open/**", "anon");
        filterChainDefinitionMap.put("/**", "authc");
        shiroFilterFactoryBean.setFilterChainDefinitionMap(filterChainDefinitionMap);
        return shiroFilterFactoryBean;
    }

    /**
     * Enable shiro aop annotation support
     * Use agent mode, so you need to turn on code support;
     *
     * @param securityManager
     * @return
     */
    @Bean
    public AuthorizationAttributeSourceAdvisor authorizationAttributeSourceAdvisor(SecurityManager securityManager) {
        AuthorizationAttributeSourceAdvisor authorizationAttributeSourceAdvisor = new AuthorizationAttributeSourceAdvisor();
        authorizationAttributeSourceAdvisor.setSecurityManager(securityManager);
        return authorizationAttributeSourceAdvisor;
    }


    @Bean
    public SecurityManager securityManager() {
        DefaultWebSecurityManager securityManager = new DefaultWebSecurityManager();
        //Set realm.
        securityManager.setRealm(userRealm());
        // Using redis for custom cache implementation
        securityManager.setCacheManager(ehCacheManager());
        securityManager.setSessionManager(sessionManager());
        return securityManager;
    }
    //Custom implementation Realm
    @Bean
    UserRealm userRealm() {
        UserRealm userRealm = new UserRealm();
        return userRealm;
    }
    //Use the buffer of shiro
    @Bean
    public SessionDAO sessionDAO() {
        return new MemorySessionDAO();
    }

    /**
     * shiro session Management
     */
    @Bean
    public DefaultWebSessionManager sessionManager() {
        DefaultWebSessionManager sessionManager = new DefaultWebSessionManager();
        //session timeout
        sessionManager.setGlobalSessionTimeout(tomcatTimeout * 1000);
        sessionManager.setSessionDAO(sessionDAO());
        Collection<SessionListener> listeners = new ArrayList<SessionListener>();
        sessionManager.setSessionListeners(listeners);
        return sessionManager;
    }
    //ehCahe cache uses its own defined
    @Bean
    public EhCacheManager ehCacheManager() {
        EhCacheManager em = new EhCacheManager();
        em.setCacheManager(cacheManager());
        return em;
    }

    @Bean("cacheManager2")
    CacheManager cacheManager(){
        return CacheManager.create();
    }


}

UserRealm

public class UserRealm extends AuthorizingRealm {
/*	@Autowired
	UserDao userMapper;
	@Autowired
	MenuService menuService;*/

	@Override
protected AuthorizationInfo doGetAuthorizationInfo(PrincipalCollection arg0) {
	 UserDO usrDo = (UserDO)SecurityUtils.getSubject().getPrincipal();
	MenuService menuService = ApplicationContextRegister.getBean(MenuService.class);
	Set<String> perms = menuService.listPerms(usrDo.getUserId());
	SimpleAuthorizationInfo info = new SimpleAuthorizationInfo();
	info.setStringPermissions(perms);
	return info;
}

@Override
protected AuthenticationInfo doGetAuthenticationInfo(AuthenticationToken token) throws AuthenticationException {
	String username = (String) token.getPrincipal();
	Map<String, Object> map = new HashMap<>(16);
	map.put("username", username);
	String password = new String((char[]) token.getCredentials());

	UserDao userMapper = ApplicationContextRegister.getBean(UserDao.class);
	// Query user information
	UserDO user = userMapper.list(map).get(0);

	// Account does not exist
	if (user == null) {
		throw new UnknownAccountException("Incorrect account or password");
	}

	// Password error
	if (!password.equals(user.getPassword())) {
		throw new IncorrectCredentialsException("Incorrect account or password");
	}

	// account lockout
	if (user.getStatus() == 0) {
		throw new LockedAccountException("Account locked,Please contact the administrator");
	}
	SimpleAuthenticationInfo info = new SimpleAuthenticationInfo(user, password, getName());
	return info;
}

}

Posted by Wintergreen on Wed, 04 Dec 2019 20:33:14 -0800