Preface
shiro is a permission framework. For specific use, you can check its official website http://shiro.apache.org/. It provides very convenient permission authentication and login functions.
As an open source framework, springboot must provide functions that integrate with shiro!
Shiro has been used in project authentication before. It is used more frequently in Spring MVC, and it is configured with XML. It is relatively simple and mature to use Shiro for permission control. Moreover, I have always put Shiro's session in mongodb. This is more in line with the original design intention of mongodb. In distributed projects, mongodb is also used as an intermediate layer, which is used to easily solve the problem of session synchronization in distributed environments.
Since SpringBoot was released, my project can basically use SpringBoot, and it is also very convenient to use MAVEN for unified centralized management. Although SpringBoot also provides a set of permission security framework Spring Security, it is relatively not very useful, so it is still more convenient to use Shiro. SpringBoot integration with Shiro is much simpler than Spring MVC, at least without a bunch of XML configurations, which looks more refreshing, so we will start integrating next.
The method is as follows:
The first step must be to add Shiro and mongo dependencies in MAVEN first. The Shiro version I use is
<shiro.version>1.2.3</shiro.version>
Add dependencies:
<dependency> <groupId>org.apache.shiro</groupId> <artifactId>shiro-core</artifactId> <version>${shiro.version}</version></dependency><dependency> <groupId>org.apache.shiro</groupId> <artifactId>shiro-web</artifactId> <version>${shiro.version}</version></dependency><dependency> <groupId>org.apache.shiro</groupId> <artifactId>shiro-spring</artifactId> <version>${shiro.version}</version></dependency><dependency> <groupId>org.apache.shiro</groupId> <artifactId>shiro-spring</artifactId> <version>${shiro.version}</version></dependency><dependency> <groupId>org.mongodb</groupId> <artifactId>mongo-java-driver</artifactId> <version>3.0.0</version></dependency> <dependency> <groupId>org.springframework.data</groupId> <artifactId>spring-data-mongodb</artifactId> <version>1.7.0.RELEASE</version></dependency>Then configure mongodb in application.xml or yml
spring.data.mongodb.host=127.0.0.1spring.data.mongodb.port=27017spring.data.mongodb.database=SHIRO_INFO
After the configuration is completed, we start to officially write Shiro authentication code, first customize an authentication realm, inherit from AuthorizingRealm
public class ShiroDbRealm extends AuthorizingRealm { /** * User Information Operation*/ private SystemUserService systemUserService; public ShiroDbRealm() {} public ShiroDbRealm(SystemUserService systemUserService) { this.systemUserService = systemUserService; } /** * Authorization Information*/ @Override protected AuthorizationInfo doGetAuthorizationInfo(PrincipalCollection principals) { SimpleAuthorizationInfo info = (SimpleAuthorizationInfo) ShiroKit.getShiroSessionAttr("perms"); if (null != info && !CollectionUtils.isEmpty(info.getRoles()) && !CollectionUtils.isEmpty(info.getStringPermissions())) { return info; } return null; } /** * Authentication Information*/ protected AuthenticationInfo doGetAuthenticationInfo(AuthenticationToken authcToken) throws AuthenticationException { UsernamePasswordToken token = (UsernamePasswordToken) authcToken; String userName = token.getUsername(); if (userName != null && !"".equals(userName)) { SystemUser key = new SystemUser(); key.setLoginName(token.getUsername()); key.setPassword(String.valueOf(token.getPassword())); SystemUser user = systemUserService.login(key); if (user != null) { Subject userTemp = SecurityUtils.getSubject(); userTemp.getSession().setAttribute("userId", user.getId()); userTemp.getSession().setAttribute("userName", user.getUserName()); return new SimpleAuthenticationInfo(user.getLoginName(), user.getPassword(), getName()); } } return null; }}Store session into mongodb's Repository and implementation:
public interface ShiroSessionRepository { /** * * @param session */ void saveSession(Session session); ......}MongoDBSessionRepository.java
public class MongoDBSessionRepository implements ShiroSessionRepository { private MongoTemplate mongoTemplate; public MongoDBSessionRepository() {} public MongoDBSessionRepository(MongoTemplate mongoTemplate) { this.mongoTemplate = mongoTemplate; } @Override public void saveSession(Session session) { if (session == null || session.getId() == null) { return; } SessionBean bean = new SessionBean(); bean.setKey(getSessionKey(session.getId())); bean.setValue(SerializeUtil.serialize(session)); bean.setPrincipal(null); bean.setHost(session.getHost()); bean.setStartTimestamp(session.getStartTimestamp()); bean.setLastAccessTime(session.getLastAccessTime()); bean.setTimeoutTime(getTimeoutTime(session.getStartTimestamp(), session.getTimeout())); mongoTemplate.insert(bean); } ......}ShiroSessionDAO.java
public class ShiroSessionDAO extends AbstractSessionDAO { /** * Logger*/ private static final Logger log = LoggerFactory.getLogger(ShiroSessionDAO.class); /** * Database storage*/ private ShiroSessionRepository shiroSessionRepository; /** * @return */ public ShiroSessionRepository getShiroSessionRepository() { return shiroSessionRepository; } /** * * @param shiroSessionRepository */ public void setShiroSessionRepository(ShiroSessionRepository shiroSessionRepository) { this.shiroSessionRepository = shiroSessionRepository; } @Override public void update(Session session) throws UnknownSessionException { getShiroSessionRepository().updateSession(session); } @Override public void delete(Session session) { if (session == null) { log.error("session can not be null,delete failed"); return; } Serializable id = session.getId(); if (id != null) { getShiroSessionRepository().deleteSession(id); } } @Override public Collection<Session> getActiveSessions() { return getShiroSessionRepository().getAllSessions(); } @Override protected Serializable doCreate(Session session) { Serializable sessionId = this.generateSessionId(session); this.assignSessionId(session, sessionId); getShiroSessionRepository().saveSession(session); return sessionId; } @Override protected Session doReadSession(Serializable sessionId) { return getShiroSessionRepository().getSession(sessionId); }}OK! All basic classes have been completed, and finally write a config to initialize and configure Shiro
@Configurationpublic class ShiroConfig { @Resource private MongoTemplate mongoTemplate; @Resource private SystemUserService systemUserService;// This is the service used to determine the user name and password @Bean public ShiroFilterFactoryBean shiroFilter(DefaultWebSecurityManager securityManager) { ShiroFilterFactoryBean shiroFilterFactoryBean = new ShiroFilterFactoryBean(); shiroFilterFactoryBean.setSecurityManager(securityManager); shiroFilterFactoryBean.setLoginUrl("/login"); shiroFilterFactoryBean.setSuccessUrl("/index"); shiroFilterFactoryBean.setUnauthorizedUrl("/403"); // Interceptor. Map<String, String> filterChainDefinitionMap = new LinkedHashMap<String, String>(); filterChainDefinitionMap.put("/static/**", "anon"); filterChainDefinitionMap.put("/ajaxLogin", "anon"); filterChainDefinitionMap.put("/libs/**", "anon"); filterChainDefinitionMap.put("/images/**", "anon"); filterChainDefinitionMap.put("/logout", "logout"); filterChainDefinitionMap.put("/**", "authc"); shiroFilterFactoryBean.setFilterChainDefinitionMap(filterChainDefinitionMap); return shiroFilterFactoryBean; } public AuthorizationAttributeSourceAdvisor authorizationAttributeSourceAdvisor( DefaultWebSessionManager securityManager) { AuthorizationAttributeSourceAdvisor adv = new AuthorizationAttributeSourceAdvisor(); adv.setSecurityManager(securityManager); return adv; } @Bean public DefaultWebSecurityManager securityManager(DefaultWebSessionManager sessionManager, ShiroDbRealm myShiroRealm) { DefaultWebSecurityManager securityManager = new DefaultWebSecurityManager(); // Set realm. securityManager.setRealm(myShiroRealm); securityManager.setSessionManager(sessionManager); return securityManager; } /** * Authentication realm; (Here pass systemUserService to custom ShiroDbRealm initialization) * * @return */ @Bean public ShiroDbRealm myShiroRealm() { ShiroDbRealm myShiroRealm = new ShiroDbRealm(systemUserService); return myShiroRealm; } @Bean public DefaultWebSessionManager sessionManager(ShiroSessionDAO shiroSessionDao) { DefaultWebSessionManager sessionManager = new DefaultWebSessionManager(); sessionManager.setGlobalSessionTimeout(1800000l); sessionManager.setDeleteInvalidSessions(true); sessionManager.setSessionValidationSchedulerEnabled(true); sessionManager.setSessionDAO(shiroSessionDao); sessionManager.setSessionIdCookieEnabled(true); SimpleCookie cookie = new SimpleCookie(ShiroHttpSession.DEFAULT_SESSION_ID_NAME); cookie.setHttpOnly(true); cookie.setMaxAge(1800000); sessionManager.setSessionIdCookie(cookie); return sessionManager; } @Bean public ShiroSessionDAO shiroSessionDao(MongoDBSessionRepository shiroSessionRepository) { ShiroSessionDAO dao = new ShiroSessionDAO(); dao.setShiroSessionRepository(shiroSessionRepository); return dao; } @Bean MongoDBSessionRepository shiroSessionRepository() { MongoDBSessionRepository resp = new MongoDBSessionRepository(mongoTemplate); return resp; }}The task is done. This is just a simple configuration. The code has been excerpted and modified from the project. As for how to use it in the controller and how to authenticate with different permissions, it is enough to implement it in your own code.
Summarize
The above is the entire content of this article. I hope that the content of this article has certain reference value for everyone's study or work. If you have any questions, you can leave a message to communicate. Thank you for your support to Wulin.com.