经验首页 前端设计 程序设计 Java相关 移动开发 数据库/运维 软件/图像 大数据/云计算 其他经验
当前位置:技术经验 » Java相关 » Java » 查看文章
shiro,基于springboot,基于前后端分离,从登录认证到鉴权,从入门到放弃
来源:cnblogs  作者:撸码识途  时间:2018/11/8 9:56:33  对本文有异议

这个demo是基于springboot项目的。

名词介绍:

Shiro
Shiro 主要分为 安全认证 和 接口授权 两个部分,其中的核心组件为 Subject、 SecurityManager、 Realms,公共部分 Shiro 都已经为我们封装好了,我们只需要按照一定的规则去编写响应的代码即可…

Subject 即表示主体,将用户的概念理解为当前操作的主体,因为它即可以是一个通过浏览器请求的用户,也可能是一个运行的程序,外部应用与 Subject 进行交互,记录当前操作用户。Subject 代表了当前用户的安全操作,SecurityManager 则管理所有用户的安全操作。

SecurityManager 即安全管理器,对所有的 Subject 进行安全管理,并通过它来提供安全管理的各种服务(认证、授权等)

Realm 充当了应用与数据安全间的 桥梁 或 连接器。当对用户执行认证(登录)和授权(访问控制)验证时,Shiro 会从应用配置的 Realm 中查找用户及其权限信息。

1.导入shiro依赖

  1. <dependency>
  2. <groupId>org.apache.shiro</groupId>
  3. <artifactId>shiro-spring</artifactId>
  4. <version>1.4.0</version>
  5. </dependency>
  6.     
  7. <dependency>
  8. <groupId>org.crazycake</groupId>
  9. <artifactId>shiro-redis</artifactId>
  10. <version>2.8.24</version>
  11. </dependency>
  1. shiro-redis为什么要导入这个包呢?将用户信息交给redis管理。

2.shiro配置类

  1. package com.test.cbd.shiro;
  2. import org.apache.shiro.authc.credential.HashedCredentialsMatcher;
  3. import org.apache.shiro.mgt.SecurityManager;
  4. import org.apache.shiro.session.mgt.SessionManager;
  5. import org.apache.shiro.spring.security.interceptor.AuthorizationAttributeSourceAdvisor;
  6. import org.apache.shiro.spring.web.ShiroFilterFactoryBean;
  7. import org.apache.shiro.web.mgt.DefaultWebSecurityManager;
  8. import org.crazycake.shiro.RedisCacheManager;
  9. import org.crazycake.shiro.RedisManager;
  10. import org.crazycake.shiro.RedisSessionDAO;
  11. import org.springframework.aop.framework.autoproxy.DefaultAdvisorAutoProxyCreator;
  12. import org.springframework.beans.factory.annotation.Value;
  13. import org.springframework.context.annotation.Bean;
  14. import org.springframework.context.annotation.Configuration;
  15. import org.springframework.web.servlet.HandlerExceptionResolver;
  16. import java.util.LinkedHashMap;
  17. import java.util.Map;
  18. @Configuration
  19. public class ShiroConfig {
  20. @Value("${spring.redis.shiro.host}")
  21. private String host;
  22. @Value("${spring.redis.shiro.port}")
  23. private int port;
  24. @Value("${spring.redis.shiro.timeout}")
  25. private int timeout;
  26. @Value("${spring.redis.shiro.password}")
  27. private String password;
  28. @Bean
  29. public ShiroFilterFactoryBean shirFilter(SecurityManager securityManager) {
  30. System.out.println("ShiroConfiguration.shirFilter()");
  31. ShiroFilterFactoryBean shiroFilterFactoryBean = new ShiroFilterFactoryBean();
  32. shiroFilterFactoryBean.setSecurityManager(securityManager);
  33. Map<String, String> filterChainDefinitionMap = new LinkedHashMap<String, String>();
  34. //注意过滤器配置顺序 不能颠倒
  35. //配置退出 过滤器,其中的具体的退出代码Shiro已经替我们实现了,登出后跳转配置的loginUrl
  36. filterChainDefinitionMap.put("/logout", "logout");
  37. // 配置不会被拦截的链接 顺序判断,在 ShiroConfiguration 中的 shiroFilter 处配置了 /ajaxLogin=anon,意味着可以不需要认证也可以访问
  38. filterChainDefinitionMap.put("/static/**", "anon");
  39. filterChainDefinitionMap.put("/*.html", "anon");
  40. filterChainDefinitionMap.put("/ajaxLogin", "anon");
  41. filterChainDefinitionMap.put("/login", "anon");
  42. filterChainDefinitionMap.put("/**", "authc");
  43. //配置shiro默认登录界面地址,前后端分离中登录界面跳转应由前端路由控制,后台仅返回json数据
  44. shiroFilterFactoryBean.setLoginUrl("/unauth");
  45. // 登录成功后要跳转的链接
  46. // shiroFilterFactoryBean.setSuccessUrl("/index");
  47. //未授权界面;
  48. // shiroFilterFactoryBean.setUnauthorizedUrl("/403");
  49. shiroFilterFactoryBean.setFilterChainDefinitionMap(filterChainDefinitionMap);
  50. return shiroFilterFactoryBean;
  51. }
  52. /**
  53. * 凭证匹配器
  54. * (由于我们的密码校验交给Shiro的SimpleAuthenticationInfo进行处理了
  55. * )
  56. *
  57. * @return
  58. */
  59. @Bean
  60. public HashedCredentialsMatcher hashedCredentialsMatcher() {
  61. HashedCredentialsMatcher hashedCredentialsMatcher = new HashedCredentialsMatcher();
  62. hashedCredentialsMatcher.setHashAlgorithmName("md5");//散列算法:这里使用MD5算法;
  63. hashedCredentialsMatcher.setHashIterations(1024);//散列的次数,比如散列两次,相当于 md5(md5(""));
  64. return hashedCredentialsMatcher;
  65. }
  66. @Bean
  67. public MyShiroRealm myShiroRealm() {
  68. MyShiroRealm myShiroRealm = new MyShiroRealm();
  69. myShiroRealm.setCredentialsMatcher(hashedCredentialsMatcher());
  70. return myShiroRealm;
  71. }
  72. @Bean
  73. public SecurityManager securityManager() {
  74. DefaultWebSecurityManager securityManager = new DefaultWebSecurityManager();
  75. securityManager.setRealm(myShiroRealm());
  76. // 自定义session管理 使用redis
  77. securityManager.setSessionManager(sessionManager());
  78. // 自定义缓存实现 使用redis
  79. securityManager.setCacheManager(cacheManager());
  80. return securityManager;
  81. }
  82. //自定义sessionManager
  83. @Bean
  84. public SessionManager sessionManager() {
  85. MySessionManager mySessionManager = new MySessionManager();
  86. mySessionManager.setSessionDAO(redisSessionDAO());
  87. return mySessionManager;
  88. }
  89. /**
  90. * 配置shiro redisManager
  91. * <p>
  92. * 使用的是shiro-redis开源插件
  93. *
  94. * @return
  95. */
  96. public RedisManager redisManager() {
  97. RedisManager redisManager = new RedisManager();
  98. redisManager.setHost(host);
  99. redisManager.setPort(port);
  100. redisManager.setExpire(1800);// 配置缓存过期时间
  101. redisManager.setTimeout(timeout);
  102. redisManager.setPassword(password);
  103. return redisManager;
  104. }
  105. /**
  106. * cacheManager 缓存 redis实现
  107. * <p>
  108. * 使用的是shiro-redis开源插件
  109. *
  110. * @return
  111. */
  112. @Bean
  113. public RedisCacheManager cacheManager() {
  114. RedisCacheManager redisCacheManager = new RedisCacheManager();
  115. redisCacheManager.setRedisManager(redisManager());
  116. return redisCacheManager;
  117. }
  118. /**
  119. * RedisSessionDAO shiro sessionDao层的实现 通过redis
  120. * <p>
  121. * 使用的是shiro-redis开源插件
  122. */
  123. @Bean
  124. public RedisSessionDAO redisSessionDAO() {
  125. RedisSessionDAO redisSessionDAO = new RedisSessionDAO();
  126. redisSessionDAO.setRedisManager(redisManager());
  127. return redisSessionDAO;
  128. }
  129. /**
  130. * 开启shiro aop注解支持.
  131. * 使用代理方式;所以需要开启代码支持;
  132. *
  133. * @param securityManager
  134. * @return
  135. */
  136. @Bean
  137. public AuthorizationAttributeSourceAdvisor authorizationAttributeSourceAdvisor(SecurityManager securityManager) {
  138. AuthorizationAttributeSourceAdvisor authorizationAttributeSourceAdvisor = new AuthorizationAttributeSourceAdvisor();
  139. authorizationAttributeSourceAdvisor.setSecurityManager(securityManager);
  140. return authorizationAttributeSourceAdvisor;
  141. }
  142. /**
  143. * 注册全局异常处理
  144. * @return
  145. */
  146. @Bean(name = "exceptionHandler")
  147. public HandlerExceptionResolver handlerExceptionResolver() {
  148. return new MyExceptionHandler();
  149. }
  150. //自动创建代理,没有这个鉴权可能会出错
  151. @Bean
  152. public DefaultAdvisorAutoProxyCreator getDefaultAdvisorAutoProxyCreator() {
  153. DefaultAdvisorAutoProxyCreator autoProxyCreator = new DefaultAdvisorAutoProxyCreator();
  154. autoProxyCreator.setProxyTargetClass(true);
  155. return autoProxyCreator;
  156. }
  157. }

3.安全认证和权限验证的核心,自定义Realm 

  1. package com.test.cbd.shiro;
  2. import com.google.gson.JsonObject;
  3. import com.test.cbd.service.UserService;
  4. import com.test.cbd.vo.SysPermission;
  5. import com.test.cbd.vo.SysRole;
  6. import com.test.cbd.vo.UserInfo;
  7. import org.apache.commons.beanutils.BeanUtils;
  8. import org.apache.shiro.SecurityUtils;
  9. import org.apache.shiro.authc.*;
  10. import org.apache.shiro.authz.AuthorizationInfo;
  11. import org.apache.shiro.authz.SimpleAuthorizationInfo;
  12. import org.apache.shiro.realm.AuthorizingRealm;
  13. import org.apache.shiro.session.Session;
  14. import org.apache.shiro.subject.PrincipalCollection;
  15. import org.apache.shiro.subject.Subject;
  16. import org.apache.shiro.util.ByteSource;
  17. import springfox.documentation.spring.web.json.Json;
  18. import javax.annotation.Resource;
  19. import java.util.HashSet;
  20. import java.util.Set;
  21.  
  22. public class MyShiroRealm extends AuthorizingRealm {
  23. @Resource
  24. private UserService userInfoService;
  25. @Override
  26. protected AuthorizationInfo doGetAuthorizationInfo(PrincipalCollection principals){
  27. // // 权限信息对象info,用来存放查出的用户的所有的角色(role)及权限(permission)
  28. SimpleAuthorizationInfo authorizationInfo = new SimpleAuthorizationInfo();
  29. Session session = SecurityUtils.getSubject().getSession();
  30. UserInfo user = (UserInfo) session.getAttribute("USER_SESSION");
  31. // 用户的角色集合
  32. Set<String> roles = new HashSet<>();
  33. roles.add(user.getRoleList().get(0).getRole());
  34. authorizationInfo.setRoles(roles);
  35. return authorizationInfo;
  36. }
  37. /*主要是用来进行身份认证的,也就是说验证用户输入的账号和密码是否正确。*/
  38. @Override
  39. protected AuthenticationInfo doGetAuthenticationInfo(AuthenticationToken token)
  40. throws AuthenticationException {
  41. // System.out.println("MyShiroRealm.doGetAuthenticationInfo()");
  42. //获取用户的输入的账号.
  43. String username = (String) token.getPrincipal();
  44. // System.out.println(token.getCredentials());
  45. //通过username从数据库中查找 User对象,如果找到,没找到.
  46. //实际项目中,这里可以根据实际情况做缓存,如果不做,Shiro自己也是有时间间隔机制,2分钟内不会重复执行该方法
  47. UserInfo userInfo = userInfoService.findByUsername(username);
  48. // Subject subject = SecurityUtils.getSubject();
  49. //Session session = subject.getSession();
  50. //session.setAttribute("role",userInfo.getRoleList());
  51. // System.out.println("----->>userInfo="+userInfo);
  52. if (userInfo == null) {
  53. return null;
  54. }
  55. if (userInfo.getState() == 1) { //账户冻结
  56. throw new LockedAccountException();
  57. }
  58. String credentials = userInfo.getPassword();
  59. System.out.println("credentials="+credentials);
  60. ByteSource credentialsSalt = ByteSource.Util.bytes(username);
  61. SimpleAuthenticationInfo authenticationInfo = new SimpleAuthenticationInfo(
  62. userInfo.getUserName(), //用户名
  63. credentials, //密码
  64. credentialsSalt,
  65. getName() //realm name
  66. );
  67. Session session = SecurityUtils.getSubject().getSession();
  68. session.setAttribute("USER_SESSION", userInfo);
  69. return authenticationInfo;
  70. }
  71. }

4.全局异常处理器

  1. package com.test.cbd.shiro;
  2. import com.alibaba.fastjson.support.spring.FastJsonJsonView;
  3. import org.apache.shiro.authz.UnauthenticatedException;
  4. import org.apache.shiro.authz.UnauthorizedException;
  5. import org.springframework.web.servlet.HandlerExceptionResolver;
  6. import org.springframework.web.servlet.ModelAndView;
  7. import javax.servlet.http.HttpServletRequest;
  8. import javax.servlet.http.HttpServletResponse;
  9. import java.util.HashMap;
  10. import java.util.Map;
  11. /**
  12. * Created by Administrator on 2017/12/11.
  13. * 全局异常处理
  14. */
  15. public class MyExceptionHandler implements HandlerExceptionResolver {
  16. public ModelAndView resolveException(HttpServletRequest httpServletRequest,
                HttpServletResponse httpServletResponse, Object o, Exception ex) {
  17. ModelAndView mv = new ModelAndView();
  18. FastJsonJsonView view = new FastJsonJsonView();
  19. Map<String, Object> attributes = new HashMap<String, Object>();
  20. if (ex instanceof UnauthenticatedException) {
  21. attributes.put("code", "1000001");
  22. attributes.put("msg", "token错误");
  23. } else if (ex instanceof UnauthorizedException) {
  24. attributes.put("code", "1000002");
  25. attributes.put("msg", "用户无权限");
  26. } else {
  27. attributes.put("code", "1000003");
  28. attributes.put("msg", ex.getMessage());
  29. }
  30. view.setAttributesMap(attributes);
  31. mv.setView(view);
  32. return mv;
  33. }
  34. }

5.因为现在的项目大多都是前后端分离的,所以我们需要实现自己的session管理

  1. package com.test.cbd.shiro;
  2. import org.apache.shiro.web.servlet.ShiroHttpServletRequest;
  3. import org.apache.shiro.web.session.mgt.DefaultWebSessionManager;
  4. import org.apache.shiro.web.util.WebUtils;
  5. import org.springframework.util.StringUtils;
  6. import javax.servlet.ServletRequest;
  7. import javax.servlet.ServletResponse;
  8. import java.io.Serializable;
  9.  
  10. public class MySessionManager extends DefaultWebSessionManager {
  11. private static final String TOKEN = "token";
  12. private static final String REFERENCED_SESSION_ID_SOURCE = "Stateless request";
  13. public MySessionManager() {
  14. super();
  15. }
  16. @Override
  17. protected Serializable getSessionId(ServletRequest request, ServletResponse response) {
  18. String id = WebUtils.toHttp(request).getHeader(TOKEN);
  19. //如果请求头中有 token 则其值为sessionId
  20. if (!StringUtils.isEmpty(id)) {
  21. request.setAttribute(ShiroHttpServletRequest.REFERENCED_SESSION_ID_SOURCE, REFERENCED_SESSION_ID_SOURCE);
  22. request.setAttribute(ShiroHttpServletRequest.REFERENCED_SESSION_ID, id);
  23. request.setAttribute(ShiroHttpServletRequest.REFERENCED_SESSION_ID_IS_VALID, Boolean.TRUE);
  24. return id;
  25. } else {
  26. //否则按默认规则从cookie取sessionId
  27. return super.getSessionId(request, response);
  28. }
  29. }
  30. }

6.控制器

  1. package com.test.cbd.shiro;
  2. import com.alibaba.fastjson.JSONObject;
  3. import com.test.cbd.vo.UserInfo;
  4. import io.swagger.annotations.Api;
  5. import lombok.extern.slf4j.Slf4j;
  6. import org.apache.shiro.SecurityUtils;
  7. import org.apache.shiro.authc.AuthenticationException;
  8. import org.apache.shiro.authc.IncorrectCredentialsException;
  9. import org.apache.shiro.authc.LockedAccountException;
  10. import org.apache.shiro.authc.UsernamePasswordToken;
  11. import org.apache.shiro.authz.annotation.RequiresRoles;
  12. import org.apache.shiro.crypto.hash.SimpleHash;
  13. import org.apache.shiro.session.Session;
  14. import org.apache.shiro.subject.Subject;
  15. import org.apache.shiro.util.ByteSource;
  16. import org.springframework.web.bind.annotation.*;
  17. import javax.servlet.http.HttpServletRequest;
  18. import java.net.InetAddress;
  19. @Slf4j
  20. @Api(value="shiro测试",description="shiro测试")
  21. @RestController
  22. @RequestMapping("/")
  23. public class ShiroLoginController {
  24. /**
  25. * 登录测试
  26. * @param userInfo
  27. * @return
  28. */
  29. @RequestMapping(value = "/ajaxLogin", method = RequestMethod.POST)
  30. @ResponseBody
  31. public String ajaxLogin(UserInfo userInfo) {
  32. JSONObject jsonObject = new JSONObject();
  33. UsernamePasswordToken token = new UsernamePasswordToken(userInfo.getUserName(), userInfo.getPassword());
  34. Subject subject = SecurityUtils.getSubject();
  35. try {
  36. subject.login(token);
  37. jsonObject.put("token", subject.getSession().getId());
  38. jsonObject.put("msg", "登录成功");
  39. } catch (IncorrectCredentialsException e) {
  40. jsonObject.put("msg", "密码错误");
  41. } catch (LockedAccountException e) {
  42. jsonObject.put("msg", "登录失败,该用户已被冻结");
  43. } catch (AuthenticationException e) {
  44. jsonObject.put("msg", "该用户不存在");
  45. } catch (Exception e) {
  46. e.printStackTrace();
  47. }
  48. return jsonObject.toString();
  49. }
  50. /**
  51. * 鉴权测试
  52. * @param userInfo
  53. * @return
  54. */
  55. @RequestMapping(value = "/check", method = RequestMethod.GET)
  56. @ResponseBody
  57. @RequiresRoles("guest")
  58. public String check() {
  59. JSONObject jsonObject = new JSONObject();
  60. jsonObject.put("msg", "鉴权测试");
  61. return jsonObject.toString();
  62. }
  63. }

常用注解
@RequiresGuest 代表无需认证即可访问,同理的就是 /path=anon

@RequiresAuthentication 需要认证,只要登录成功后就允许你操作

@RequiresPermissions 需要特定的权限,没有则抛出 AuthorizationException

@RequiresRoles 需要特定的橘色,没有则抛出 AuthorizationException


7.以上就是shiro登陆和鉴权的主要配置和类,下面补充一下其他信息。

①application.properties中shiro-redis相关配置:

  1. spring.redis.shiro.host=127.0.0.1
  2. spring.redis.shiro.port=6379
  3. spring.redis.shiro.timeout=5000
  4. spring.redis.shiro.password=123456

②因为数据是模拟的,所以在登陆认证的时候,并没有通过数据库查用户信息,可以通过以下方式模拟加密后的密码:

  1. /**
  2. * 生成测试用的md5加密的密码
  3. * @param args
  4. */
  5. public static void main(String[] args) {
  6. String hashAlgorithmName = "md5";
  7. String credentials = "123456";//密码
  8. int hashIterations = 1024;
  9. ByteSource credentialsSalt = ByteSource.Util.bytes("root");//账号
  10. String obj = new SimpleHash(hashAlgorithmName, credentials, credentialsSalt, hashIterations).toHex();
  11. System.out.println(obj);
  12. }

上面obj的结果是b1ba853525d0f30afe59d2d005aad96c

③登陆认证的findByUsername方法,模拟到数据库查询用户信息,实际是自己构造的数据,偷偷懒。

  1. public UserInfo findByUsername(String userName){
  2. SysRole admin = SysRole.builder().role("admin").build();
  3. List<SysPermission> list=new ArrayList<SysPermission>();
  4. SysPermission sysPermission=new SysPermission("read");
  5. SysPermission sysPermission1=new SysPermission("write");
  6. list.add(sysPermission);
  7. list.add(sysPermission1);
  8. admin.setPermissions(list);
  9. UserInfo root = UserInfo.builder().userName("root").password("b1ba853525d0f30afe59d2d005aad96c").credentialsSalt("123").state(0).build();
  10. List<SysRole> roleList=new ArrayList<SysRole>();
  11. roleList.add(admin);
  12. root.setRoleList(roleList);
  13. return root;
  14. }

8.结果演示

输入正确的账号密码时,返回信息如下:

 

 故意输错密码时,返回信息如下:

 

鉴权时,如果该用户没有角色:

完!

 友情链接:直通硅谷  点职佳  北美留学生论坛

本站QQ群:前端 618073944 | Java 606181507 | Python 626812652 | C/C++ 612253063 | 微信 634508462 | 苹果 692586424 | C#/.net 182808419 | PHP 305140648 | 运维 608723728

W3xue 的所有内容仅供测试,对任何法律问题及风险不承担任何责任。通过使用本站内容随之而来的风险与本站无关。
关于我们  |  意见建议  |  捐助我们  |  报错有奖  |  广告合作、友情链接(目前9元/月)请联系QQ:27243702 沸活量
皖ICP备17017327号-2 皖公网安备34020702000426号