shiro,基於springboot,基於前後端分離,從登入認證到鑑權,從入門到放棄
這個demo是基於springboot專案的。
名詞介紹:
Shiro
Shiro 主要分為 安全認證 和 介面授權 兩個部分,其中的核心元件為 Subject、 SecurityManager、 Realms,公共部分 Shiro 都已經為我們封裝好了,我們只需要按照一定的規則去編寫響應的程式碼即可…
Subject 即表示主體,將使用者的概念理解為當前操作的主體,因為它即可以是一個通過瀏覽器請求的使用者,也可能是一個執行的程式,外部應用與 Subject 進行互動,記錄當前操作使用者。Subject 代表了當前使用者的安全操作,SecurityManager 則管理所有使用者的安全操作。
SecurityManager 即安全管理器,對所有的 Subject 進行安全管理,並通過它來提供安全管理的各種服務(認證、授權等)
Realm 充當了應用與資料安全間的 橋樑 或 聯結器。當對使用者執行認證(登入)和授權(訪問控制)驗證時,Shiro 會從應用配置的 Realm 中查詢使用者及其許可權資訊。
1.匯入shiro依賴
<dependency> <groupId>org.apache.shiro</groupId> <artifactId>shiro-spring</artifactId> <version>1.4.0</version> </dependency> <dependency> <groupId>org.crazycake</groupId> <artifactId>shiro-redis</artifactId> <version>2.8.24</version> </dependency>
shiro-redis為什麼要匯入這個包呢?將使用者資訊交給redis管理。
2.shiro配置類
package com.test.cbd.shiro; import org.apache.shiro.authc.credential.HashedCredentialsMatcher; import org.apache.shiro.mgt.SecurityManager; import org.apache.shiro.session.mgt.SessionManager; import org.apache.shiro.spring.security.interceptor.AuthorizationAttributeSourceAdvisor; import org.apache.shiro.spring.web.ShiroFilterFactoryBean; import org.apache.shiro.web.mgt.DefaultWebSecurityManager; import org.crazycake.shiro.RedisCacheManager; import org.crazycake.shiro.RedisManager; import org.crazycake.shiro.RedisSessionDAO; import org.springframework.aop.framework.autoproxy.DefaultAdvisorAutoProxyCreator; import org.springframework.beans.factory.annotation.Value; import org.springframework.context.annotation.Bean; import org.springframework.context.annotation.Configuration; import org.springframework.web.servlet.HandlerExceptionResolver; import java.util.LinkedHashMap; import java.util.Map; @Configuration public class ShiroConfig { @Value("${spring.redis.shiro.host}") private String host; @Value("${spring.redis.shiro.port}") private int port; @Value("${spring.redis.shiro.timeout}") private int timeout; @Value("${spring.redis.shiro.password}") private String password; @Bean public ShiroFilterFactoryBean shirFilter(SecurityManager securityManager) { System.out.println("ShiroConfiguration.shirFilter()"); ShiroFilterFactoryBean shiroFilterFactoryBean = new ShiroFilterFactoryBean(); shiroFilterFactoryBean.setSecurityManager(securityManager); Map<String, String> filterChainDefinitionMap = new LinkedHashMap<String, String>(); //注意過濾器配置順序 不能顛倒 //配置退出 過濾器,其中的具體的退出程式碼Shiro已經替我們實現了,登出後跳轉配置的loginUrl filterChainDefinitionMap.put("/logout", "logout"); // 配置不會被攔截的連結 順序判斷,在 ShiroConfiguration 中的 shiroFilter 處配置了 /ajaxLogin=anon,意味著可以不需要認證也可以訪問 filterChainDefinitionMap.put("/static/**", "anon"); filterChainDefinitionMap.put("/*.html", "anon"); filterChainDefinitionMap.put("/ajaxLogin", "anon"); filterChainDefinitionMap.put("/login", "anon"); filterChainDefinitionMap.put("/**", "authc"); //配置shiro預設登入介面地址,前後端分離中登入介面跳轉應由前端路由控制,後臺僅返回json資料 shiroFilterFactoryBean.setLoginUrl("/unauth"); // 登入成功後要跳轉的連結 //shiroFilterFactoryBean.setSuccessUrl("/index"); //未授權介面; //shiroFilterFactoryBean.setUnauthorizedUrl("/403"); shiroFilterFactoryBean.setFilterChainDefinitionMap(filterChainDefinitionMap); return shiroFilterFactoryBean; } /** * 憑證匹配器 * (由於我們的密碼校驗交給Shiro的SimpleAuthenticationInfo進行處理了 * ) * * @return */ @Bean public HashedCredentialsMatcher hashedCredentialsMatcher() { HashedCredentialsMatcher hashedCredentialsMatcher = new HashedCredentialsMatcher(); hashedCredentialsMatcher.setHashAlgorithmName("md5");//雜湊演算法:這裡使用MD5演算法; hashedCredentialsMatcher.setHashIterations(1024);//雜湊的次數,比如雜湊兩次,相當於 md5(md5("")); return hashedCredentialsMatcher; } @Bean public MyShiroRealm myShiroRealm() { MyShiroRealm myShiroRealm = new MyShiroRealm(); myShiroRealm.setCredentialsMatcher(hashedCredentialsMatcher()); return myShiroRealm; } @Bean public SecurityManager securityManager() { DefaultWebSecurityManager securityManager = new DefaultWebSecurityManager(); securityManager.setRealm(myShiroRealm()); // 自定義session管理 使用redis securityManager.setSessionManager(sessionManager()); // 自定義快取實現 使用redis securityManager.setCacheManager(cacheManager()); return securityManager; } //自定義sessionManager @Bean public SessionManager sessionManager() { MySessionManager mySessionManager = new MySessionManager(); mySessionManager.setSessionDAO(redisSessionDAO()); return mySessionManager; } /** * 配置shiro redisManager * <p> * 使用的是shiro-redis開源外掛 * * @return */ public RedisManager redisManager() { RedisManager redisManager = new RedisManager(); redisManager.setHost(host); redisManager.setPort(port); redisManager.setExpire(1800);// 配置快取過期時間 redisManager.setTimeout(timeout); redisManager.setPassword(password); return redisManager; } /** * cacheManager 快取 redis實現 * <p> * 使用的是shiro-redis開源外掛 * * @return */ @Bean public RedisCacheManager cacheManager() { RedisCacheManager redisCacheManager = new RedisCacheManager(); redisCacheManager.setRedisManager(redisManager()); return redisCacheManager; } /** * RedisSessionDAO shiro sessionDao層的實現 通過redis * <p> * 使用的是shiro-redis開源外掛 */ @Bean public RedisSessionDAO redisSessionDAO() { RedisSessionDAO redisSessionDAO = new RedisSessionDAO(); redisSessionDAO.setRedisManager(redisManager()); return redisSessionDAO; } /** * 開啟shiro aop註解支援. * 使用代理方式;所以需要開啟程式碼支援; * * @param securityManager * @return */ @Bean public AuthorizationAttributeSourceAdvisor authorizationAttributeSourceAdvisor(SecurityManager securityManager) { AuthorizationAttributeSourceAdvisor authorizationAttributeSourceAdvisor = new AuthorizationAttributeSourceAdvisor(); authorizationAttributeSourceAdvisor.setSecurityManager(securityManager); return authorizationAttributeSourceAdvisor; } /** * 註冊全域性異常處理 * @return */ @Bean(name = "exceptionHandler") public HandlerExceptionResolver handlerExceptionResolver() { return new MyExceptionHandler(); } //自動建立代理,沒有這個鑑權可能會出錯 @Bean public DefaultAdvisorAutoProxyCreator getDefaultAdvisorAutoProxyCreator() { DefaultAdvisorAutoProxyCreator autoProxyCreator = new DefaultAdvisorAutoProxyCreator(); autoProxyCreator.setProxyTargetClass(true); return autoProxyCreator; } }
3.安全認證和許可權驗證的核心,自定義Realm
package com.test.cbd.shiro; import com.google.gson.JsonObject; import com.test.cbd.service.UserService; import com.test.cbd.vo.SysPermission; import com.test.cbd.vo.SysRole; import com.test.cbd.vo.UserInfo; import org.apache.commons.beanutils.BeanUtils; 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.session.Session; import org.apache.shiro.subject.PrincipalCollection; import org.apache.shiro.subject.Subject; import org.apache.shiro.util.ByteSource; import springfox.documentation.spring.web.json.Json; import javax.annotation.Resource; import java.util.HashSet; import java.util.Set; public class MyShiroRealm extends AuthorizingRealm { @Resource private UserService userInfoService; @Override protected AuthorizationInfo doGetAuthorizationInfo(PrincipalCollection principals){ //// 許可權資訊物件info,用來存放查出的使用者的所有的角色(role)及許可權(permission) SimpleAuthorizationInfo authorizationInfo = new SimpleAuthorizationInfo(); Session session = SecurityUtils.getSubject().getSession(); UserInfo user = (UserInfo) session.getAttribute("USER_SESSION"); // 使用者的角色集合 Set<String> roles = new HashSet<>(); roles.add(user.getRoleList().get(0).getRole()); authorizationInfo.setRoles(roles); return authorizationInfo; } /*主要是用來進行身份認證的,也就是說驗證使用者輸入的賬號和密碼是否正確。*/ @Override protected AuthenticationInfo doGetAuthenticationInfo(AuthenticationToken token) throws AuthenticationException { //System.out.println("MyShiroRealm.doGetAuthenticationInfo()"); //獲取使用者的輸入的賬號. String username = (String) token.getPrincipal(); //System.out.println(token.getCredentials()); //通過username從資料庫中查詢 User物件,如果找到,沒找到. //實際專案中,這裡可以根據實際情況做快取,如果不做,Shiro自己也是有時間間隔機制,2分鐘內不會重複執行該方法 UserInfo userInfo = userInfoService.findByUsername(username); // Subject subject = SecurityUtils.getSubject(); //Session session = subject.getSession(); //session.setAttribute("role",userInfo.getRoleList()); //System.out.println("----->>userInfo="+userInfo); if (userInfo == null) { return null; } if (userInfo.getState() == 1) { //賬戶凍結 throw new LockedAccountException(); } String credentials = userInfo.getPassword(); System.out.println("credentials="+credentials); ByteSource credentialsSalt = ByteSource.Util.bytes(username); SimpleAuthenticationInfo authenticationInfo = new SimpleAuthenticationInfo( userInfo.getUserName(), //使用者名稱 credentials, //密碼 credentialsSalt, getName()//realm name ); Session session = SecurityUtils.getSubject().getSession(); session.setAttribute("USER_SESSION", userInfo); return authenticationInfo; } }
4.全域性異常處理器
package com.test.cbd.shiro; import com.alibaba.fastjson.support.spring.FastJsonJsonView; import org.apache.shiro.authz.UnauthenticatedException; import org.apache.shiro.authz.UnauthorizedException; import org.springframework.web.servlet.HandlerExceptionResolver; import org.springframework.web.servlet.ModelAndView; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; import java.util.HashMap; import java.util.Map; /** * Created by Administrator on 2017/12/11. * 全域性異常處理 */ public class MyExceptionHandler implements HandlerExceptionResolver { public ModelAndView resolveException(HttpServletRequest httpServletRequest, HttpServletResponse httpServletResponse, Object o, Exception ex) { ModelAndView mv = new ModelAndView(); FastJsonJsonView view = new FastJsonJsonView(); Map<String, Object> attributes = new HashMap<String, Object>(); if (ex instanceof UnauthenticatedException) { attributes.put("code", "1000001"); attributes.put("msg", "token錯誤"); } else if (ex instanceof UnauthorizedException) { attributes.put("code", "1000002"); attributes.put("msg", "使用者無許可權"); } else { attributes.put("code", "1000003"); attributes.put("msg", ex.getMessage()); } view.setAttributesMap(attributes); mv.setView(view); return mv; } }
5.因為現在的專案大多都是前後端分離的,所以我們需要實現自己的session管理
package com.test.cbd.shiro; import org.apache.shiro.web.servlet.ShiroHttpServletRequest; import org.apache.shiro.web.session.mgt.DefaultWebSessionManager; import org.apache.shiro.web.util.WebUtils; import org.springframework.util.StringUtils; import javax.servlet.ServletRequest; import javax.servlet.ServletResponse; import java.io.Serializable; public class MySessionManager extends DefaultWebSessionManager { private static final String TOKEN = "token"; private static final String REFERENCED_SESSION_ID_SOURCE = "Stateless request"; public MySessionManager() { super(); } @Override protected Serializable getSessionId(ServletRequest request, ServletResponse response) { String id = WebUtils.toHttp(request).getHeader(TOKEN); //如果請求頭中有 token 則其值為sessionId if (!StringUtils.isEmpty(id)) { request.setAttribute(ShiroHttpServletRequest.REFERENCED_SESSION_ID_SOURCE, REFERENCED_SESSION_ID_SOURCE); request.setAttribute(ShiroHttpServletRequest.REFERENCED_SESSION_ID, id); request.setAttribute(ShiroHttpServletRequest.REFERENCED_SESSION_ID_IS_VALID, Boolean.TRUE); return id; } else { //否則按預設規則從cookie取sessionId return super.getSessionId(request, response); } } }
6.控制器
package com.test.cbd.shiro; import com.alibaba.fastjson.JSONObject; import com.test.cbd.vo.UserInfo; import io.swagger.annotations.Api; import lombok.extern.slf4j.Slf4j; import org.apache.shiro.SecurityUtils; import org.apache.shiro.authc.AuthenticationException; import org.apache.shiro.authc.IncorrectCredentialsException; import org.apache.shiro.authc.LockedAccountException; import org.apache.shiro.authc.UsernamePasswordToken; import org.apache.shiro.authz.annotation.RequiresRoles; import org.apache.shiro.crypto.hash.SimpleHash; import org.apache.shiro.session.Session; import org.apache.shiro.subject.Subject; import org.apache.shiro.util.ByteSource; import org.springframework.web.bind.annotation.*; import javax.servlet.http.HttpServletRequest; import java.net.InetAddress; @Slf4j @Api(value="shiro測試",description="shiro測試") @RestController @RequestMapping("/") public class ShiroLoginController { /** * 登入測試 * @param userInfo * @return */ @RequestMapping(value = "/ajaxLogin", method = RequestMethod.POST) @ResponseBody public String ajaxLogin(UserInfo userInfo) { JSONObject jsonObject = new JSONObject(); UsernamePasswordToken token = new UsernamePasswordToken(userInfo.getUserName(), userInfo.getPassword()); Subject subject = SecurityUtils.getSubject(); try { subject.login(token); jsonObject.put("token", subject.getSession().getId()); jsonObject.put("msg", "登入成功"); } catch (IncorrectCredentialsException e) { jsonObject.put("msg", "密碼錯誤"); } catch (LockedAccountException e) { jsonObject.put("msg", "登入失敗,該使用者已被凍結"); } catch (AuthenticationException e) { jsonObject.put("msg", "該使用者不存在"); } catch (Exception e) { e.printStackTrace(); } return jsonObject.toString(); } /** * 鑑權測試 * @param userInfo * @return */ @RequestMapping(value = "/check", method = RequestMethod.GET) @ResponseBody @RequiresRoles("guest") public String check() { JSONObject jsonObject = new JSONObject(); jsonObject.put("msg", "鑑權測試"); return jsonObject.toString(); } }
常用註解
@RequiresGuest 代表無需認證即可訪問,同理的就是 /path=anon
@RequiresAuthentication 需要認證,只要登入成功後就允許你操作
@RequiresPermissions 需要特定的許可權,沒有則丟擲 AuthorizationException
@RequiresRoles 需要特定的橘色,沒有則丟擲 AuthorizationException
7.以上就是shiro登陸和鑑權的主要配置和類,下面補充一下其他資訊。
①application.properties中shiro-redis相關配置:
spring.redis.shiro.host=127.0.0.1 spring.redis.shiro.port=6379 spring.redis.shiro.timeout=5000 spring.redis.shiro.password=123456
②因為資料是模擬的,所以在登陸認證的時候,並沒有通過資料庫查使用者資訊,可以通過以下方式模擬加密後的密碼:
/** * 生成測試用的md5加密的密碼 * @param args */ public static void main(String[] args) { String hashAlgorithmName = "md5"; String credentials = "123456";//密碼 int hashIterations = 1024; ByteSource credentialsSalt = ByteSource.Util.bytes("root");//賬號 Stringobj = new SimpleHash(hashAlgorithmName, credentials, credentialsSalt, hashIterations).toHex(); System.out.println(obj); }
上面obj的結果是b1ba853525d0f30afe59d2d005aad96c
③登陸認證的findByUsername方法,模擬到資料庫查詢使用者資訊,實際是自己構造的資料,偷偷懶。
public UserInfo findByUsername(String userName){ SysRole admin = SysRole.builder().role("admin").build(); List<SysPermission> list=new ArrayList<SysPermission>(); SysPermission sysPermission=new SysPermission("read"); SysPermission sysPermission1=new SysPermission("write"); list.add(sysPermission); list.add(sysPermission1); admin.setPermissions(list); UserInfo root = UserInfo.builder().userName("root").password("b1ba853525d0f30afe59d2d005aad96c").credentialsSalt("123").state(0).build(); List<SysRole> roleList=new ArrayList<SysRole>(); roleList.add(admin); root.setRoleList(roleList); return root; }
8.結果演示
輸入正確的賬號密碼時,返回資訊如下:
故意輸錯密碼時,返回資訊如下:
鑑權時,如果該使用者沒有角色: