springboot專案,thymeleaf整合shiro
阿新 • • 發佈:2018-11-07
github地址:https://github.com/theborakompanioni/thymeleaf-extras-shiro
ps:此文章需要相應的shiro基礎,內容很精簡
1.pom.xml
<properties> <project.build.sourceEncoding>UTF-8</project.build.sourceEncoding> <project.reporting.outputEncoding>UTF-8</project.reporting.outputEncoding><java.version>1.8</java.version> <thymeleaf.version>3.0.3.RELEASE</thymeleaf.version> <thymeleaf-layout-dialect.version>2.2.1</thymeleaf-layout-dialect.version> </properties>
<!--shiro相關--> <dependency> <groupId>org.apache.shiro</groupId>2.shiro 相關配置<artifactId>shiro-spring</artifactId> <version>1.2.5</version> </dependency> <dependency> <groupId>org.apache.shiro</groupId> <artifactId>shiro-ehcache</artifactId> <version>1.2.5</version> </dependency> <!--加入thymeleaf--><dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-thymeleaf</artifactId> </dependency> <dependency> <groupId>nz.net.ultraq.thymeleaf</groupId> <artifactId>thymeleaf-layout-dialect</artifactId> </dependency> <!--thymeleaf使用shiro--> <dependency> <groupId>com.github.theborakompanioni</groupId> <artifactId>thymeleaf-extras-shiro</artifactId> <version>2.0.0</version> </dependency>
2.1
package com.example.competition.shiro; import at.pollux.thymeleaf.shiro.dialect.ShiroDialect; import org.apache.shiro.authc.credential.HashedCredentialsMatcher; import org.apache.shiro.spring.LifecycleBeanPostProcessor; import org.apache.shiro.spring.security.interceptor.AuthorizationAttributeSourceAdvisor; import org.apache.shiro.spring.web.ShiroFilterFactoryBean; import org.apache.shiro.web.filter.authc.LogoutFilter; import org.apache.shiro.web.mgt.DefaultWebSecurityManager; import org.springframework.aop.framework.autoproxy.DefaultAdvisorAutoProxyCreator; import org.springframework.boot.autoconfigure.condition.ConditionalOnMissingBean; import org.springframework.context.annotation.Bean; import org.springframework.context.annotation.Configuration; import org.springframework.context.annotation.DependsOn; import javax.servlet.Filter; import java.util.LinkedHashMap; import java.util.Map; /** * shiro配置類 * Created by cdyoue on 2016/10/21. */ @Configuration public class ShiroConfiguration { /** * LifecycleBeanPostProcessor,這是個DestructionAwareBeanPostProcessor的子類, * 負責org.apache.shiro.util.Initializable型別bean的生命週期的,初始化和銷燬。 * 主要是AuthorizingRealm類的子類,以及EhCacheManager類。 */ @Bean(name = "lifecycleBeanPostProcessor") public LifecycleBeanPostProcessor lifecycleBeanPostProcessor() { return new LifecycleBeanPostProcessor(); } /** * HashedCredentialsMatcher,這個類是為了對密碼進行編碼的, * 防止密碼在資料庫裡明碼儲存,當然在登陸認證的時候, * 這個類也負責對form裡輸入的密碼進行編碼。 */ @Bean(name = "hashedCredentialsMatcher") public HashedCredentialsMatcher hashedCredentialsMatcher() { HashedCredentialsMatcher credentialsMatcher = new HashedCredentialsMatcher(); credentialsMatcher.setHashAlgorithmName("MD5"); credentialsMatcher.setHashIterations(2); credentialsMatcher.setStoredCredentialsHexEncoded(true); return credentialsMatcher; } /** * ShiroRealm, ,繼承自AuthorizingRealm, * 負責使用者的認證和許可權的處理,可以參考JdbcRealm的實現。 */ @Bean(name = "shiroRealm") @DependsOn("lifecycleBeanPostProcessor") public ShiroRealm shiroRealm() { ShiroRealm realm = new ShiroRealm(); // realm.setCredentialsMatcher(hashedCredentialsMatcher()); return realm; } // /** // * EhCacheManager,快取管理,使用者登陸成功後,把使用者資訊和許可權資訊快取起來, // * 然後每次使用者請求時,放入使用者的session中,如果不設定這個bean,每個請求都會查詢一次資料庫。 // */ // @Bean(name = "ehCacheManager") // @DependsOn("lifecycleBeanPostProcessor") // public EhCacheManager ehCacheManager() { // return new EhCacheManager(); // } /** * SecurityManager,許可權管理,這個類組合了登陸,登出,許可權,session的處理,是個比較重要的類。 * // */ @Bean(name = "securityManager") public DefaultWebSecurityManager securityManager() { DefaultWebSecurityManager securityManager = new DefaultWebSecurityManager(); securityManager.setRealm(shiroRealm()); // securityManager.setCacheManager(ehCacheManager()); return securityManager; } /** * ShiroFilterFactoryBean,是個factorybean,為了生成ShiroFilter。 * 它主要保持了三項資料,securityManager,filters,filterChainDefinitionManager。 */ @Bean(name = "shiroFilter") public ShiroFilterFactoryBean shiroFilterFactoryBean() { ShiroFilterFactoryBean shiroFilterFactoryBean = new ShiroFilterFactoryBean(); shiroFilterFactoryBean.setSecurityManager(securityManager()); Map<String, Filter> filters = new LinkedHashMap<String, Filter>(); LogoutFilter logoutFilter = new LogoutFilter(); logoutFilter.setRedirectUrl("/login"); // filters.put("logout",null); shiroFilterFactoryBean.setFilters(filters); Map<String, String> filterChainDefinitionManager = new LinkedHashMap<String, String>(); filterChainDefinitionManager.put("/logout", "logout"); filterChainDefinitionManager.put("/user/**", "authc,roles[ROLE_USER]"); filterChainDefinitionManager.put("/events/**", "authc,roles[ROLE_ADMIN]"); // filterChainDefinitionManager.put("/user/edit/**", "authc,perms[user:edit]");// 這裡為了測試,固定寫死的值,也可以從資料庫或其他配置中讀取 filterChainDefinitionManager.put("/**", "anon"); shiroFilterFactoryBean.setFilterChainDefinitionMap(filterChainDefinitionManager); shiroFilterFactoryBean.setSuccessUrl("/"); shiroFilterFactoryBean.setUnauthorizedUrl("/403"); return shiroFilterFactoryBean; } /** * DefaultAdvisorAutoProxyCreator,Spring的一個bean,由Advisor決定對哪些類的方法進行AOP代理。 */ @Bean @ConditionalOnMissingBean public DefaultAdvisorAutoProxyCreator defaultAdvisorAutoProxyCreator() { DefaultAdvisorAutoProxyCreator defaultAAP = new DefaultAdvisorAutoProxyCreator(); defaultAAP.setProxyTargetClass(true); return defaultAAP; } /** * AuthorizationAttributeSourceAdvisor,shiro裡實現的Advisor類, * 內部使用AopAllianceAnnotationsAuthorizingMethodInterceptor來攔截用以下註解的方法。 */ @Bean public AuthorizationAttributeSourceAdvisor authorizationAttributeSourceAdvisor() { AuthorizationAttributeSourceAdvisor aASA = new AuthorizationAttributeSourceAdvisor(); aASA.setSecurityManager(securityManager()); return aASA; } @Bean public ShiroDialect shiroDialect() { return new ShiroDialect(); } }2.2此類根據自己資料庫修改
package com.example.competition.shiro; import com.example.competition.dao.dto.UserRoleDTO; import com.example.competition.dao.mapper.PermissionMapper; import com.example.competition.dao.mapper.UserMapper; import com.example.competition.dao.model.Permission; import com.example.competition.dao.model.Role; import lombok.extern.slf4j.Slf4j; import org.apache.shiro.SecurityUtils; import org.apache.shiro.authc.*; import org.apache.shiro.authz.AuthorizationInfo; import org.apache.shiro.authz.SimpleAuthorizationInfo; import org.apache.shiro.realm.AuthorizingRealm; import org.apache.shiro.subject.PrincipalCollection; import org.springframework.beans.factory.annotation.Autowired; import java.util.HashMap; import java.util.Map; /** * Created by cdyoue on 2016/10/21. */ @Slf4j public class ShiroRealm extends AuthorizingRealm { @Autowired private UserMapper userMapper; @Autowired private PermissionMapper permissionMapper; /** 授權訪問控制 */ @Override protected AuthorizationInfo doGetAuthorizationInfo(PrincipalCollection principalCollection) { log.info("doGetAuthorizationInfo:"+principalCollection.toString()); Map<String,Object> map=new HashMap<>(); map.put("username",principalCollection.getPrimaryPrincipal()); UserRoleDTO userRoleDTO = userMapper.selectUserAndRole(map); //把principals放session中 key=userId value=principals SecurityUtils.getSubject().getSession().setAttribute(String.valueOf(userRoleDTO.getUserId()),SecurityUtils.getSubject().getPrincipals()); SimpleAuthorizationInfo simpleAuthorizationInfo = new SimpleAuthorizationInfo(); //賦予角色 for(Role userRole:userRoleDTO.getRoles()){ simpleAuthorizationInfo.addRole(userRole.getRoleName()); } //賦予許可權 for(Permission permission:permissionMapper.selectPermissionByUserId(userRoleDTO.getUserId())){ // if(StringUtils.isNotBlank(permission.getPermCode())) simpleAuthorizationInfo.addStringPermission(permission.getpName()); } //設定登入次數、時間 // userService.updateUserLogin(user); return simpleAuthorizationInfo; } /** 驗證使用者身份 */ @Override protected AuthenticationInfo doGetAuthenticationInfo(AuthenticationToken authenticationToken) throws AuthenticationException { log.info("doGetAuthenticationInfo:" + authenticationToken.toString()); UsernamePasswordToken token = (UsernamePasswordToken) authenticationToken; String userName=token.getUsername(); log.info(userName+token.getPassword()); Map<String,Object> map=new HashMap<>(); map.put("username",token.getUsername()); UserRoleDTO userRoleDTO = userMapper.selectUserAndRole(map); if (userRoleDTO != null) { // byte[] salt = Encodes.decodeHex(user.getSalt()); // ShiroUser shiroUser=new ShiroUser(user.getId(), user.getLoginName(), user.getName()); //設定使用者session SecurityUtils.getSubject().getSession().setAttribute("user", userRoleDTO); return new SimpleAuthenticationInfo(userName,userRoleDTO.getPassword(),getName()); } else { return null; } // return null; } }3.頁面
<!DOCTYPE html> <html xmlns:shiro="http://www.pollix.at/thymeleaf/shiro"> <head> <title>thymeleaf-extras-shiro</title> </head> <body> <p shiro:guest="">Please <a href="login.html">login</a></p> <p shiro:authenticated=""> Hello, <span shiro:principal=""></span>, how are you today? </p> </body> </html>