這個demo是基於springboot項目的。html
名詞介紹:前端
Shiro
Shiro 主要分爲 安全認證 和 接口受權 兩個部分,其中的核心組件爲 Subject、 SecurityManager、 Realms,公共部分 Shiro 都已經爲咱們封裝好了,咱們只須要按照必定的規則去編寫響應的代碼便可…java
Subject 即表示主體,將用戶的概念理解爲當前操做的主體,由於它便可以是一個經過瀏覽器請求的用戶,也多是一個運行的程序,外部應用與 Subject 進行交互,記錄當前操做用戶。Subject 表明了當前用戶的安全操做,SecurityManager 則管理全部用戶的安全操做。web
SecurityManager 即安全管理器,對全部的 Subject 進行安全管理,並經過它來提供安全管理的各類服務(認證、受權等)ajax
Realm 充當了應用與數據安全間的 橋樑 或 鏈接器。當對用戶執行認證(登陸)和受權(訪問控制)驗證時,Shiro 會從應用配置的 Realm 中查找用戶及其權限信息。
redis
<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管理。
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; } }
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; } }
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; } }
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); } } }
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 須要認證,只要登陸成功後就容許你操做spring
@RequiresPermissions 須要特定的權限,沒有則拋出 AuthorizationException數據庫
@RequiresRoles 須要特定的橘色,沒有則拋出 AuthorizationExceptionapache
①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");//帳號 String obj = 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; }
輸入正確的帳號密碼時,返回信息以下:
故意輸錯密碼時,返回信息以下:
鑑權時,若是該用戶沒有角色: