shiro,基于springboot,基于前后端分离,从登录认证到鉴权,从入门到放弃

时间:2021-09-02 06:33:51

这个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");//账号
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;
}

8.结果演示

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

shiro,基于springboot,基于前后端分离,从登录认证到鉴权,从入门到放弃

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

shiro,基于springboot,基于前后端分离,从登录认证到鉴权,从入门到放弃

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

shiro,基于springboot,基于前后端分离,从登录认证到鉴权,从入门到放弃

完!

shiro,基于springboot,基于前后端分离,从登录认证到鉴权,从入门到放弃的更多相关文章

  1. Jeecg-Boot 2&period;0 版本发布,基于Springboot&plus;Vue 前后端分离快速开发平台

    目录 Jeecg-Boot项目简介 源码下载 升级日志 Issues解决 v1.1升级到v2.0不兼容地方 系统截图 Jeecg-Boot项目简介 Jeecg-boot 是一款基于代码生成器的智能开发 ...

  2. (转)也谈基于NodeJS的全栈式开发(基于NodeJS的前后端分离)

    原文链接:http://ued.taobao.org/blog/2014/04/full-stack-development-with-nodejs/ 随着不同终端(pad/mobile/pc)的兴起 ...

  3. 基于 koajs 的前后端分离实践

    一.什么是前后端分离? 前后端分离的概念和优势在这里不再赘述,有兴趣的同学可以看各个前辈们一系列总结和讨论: 系列文章:前后端分离的思考与实践(1-6) slider: 淘宝前后端分离实践 知乎提问: ...

  4. 也谈基于NodeJS的全栈式开发(基于NodeJS的前后端分离)

    前言 为了解决传统Web开发模式带来的各种问题,我们进行了许多尝试,但由于前/后端的物理鸿沟,尝试的方案都大同小异.痛定思痛,今天我们重新思考了“前后端”的定义,引入前端同学都熟悉的NodeJS,试图 ...

  5. 基于NodeJS进行前后端分离

    1.什么是前后端分离 传统的SPA模式:所有用到的展现数据都是后端通过异步接口(AJAX/JSONP)的方式提供的,前端只管展现. 从某种意义上来说,SPA确实做到了前后端分离,但这种方式存在两个问题 ...

  6. &lbrack;转&rsqb; 基于NodeJS的前后端分离的思考与实践(五)多终端适配

    前言 近年来各站点基于 Web 的多终端适配进行得如火如荼,行业间也发展出依赖各种技术的解决方案.有如基于浏览器原生 CSS3 Media Query 的响应式设计.基于云端智能重排的「云适配」方案等 ...

  7. 基于NodeJS的全栈式开发(基于NodeJS的前后端分离)

    也谈基于NodeJS的全栈式开发(基于NodeJS的前后端分离) 前言 为了解决传统Web开发模式带来的各种问题,我们进行了许多尝试,但由于前/后端的物理鸿沟,尝试的方案都大同小异.痛定思痛,今天我们 ...

  8. springboot&plus;apache前后端分离部署https

    目录 1. 引言 2. 了解https.证书.openssl及keytool 2.1 https 2.1.1 什么是https 2.1.2 https解决什么问题 2.2 证书 2.2.1 证书内容 ...

  9. SpringBoot&plus;Vue前后端分离,使用SpringSecurity完美处理权限问题

    原文链接:https://segmentfault.com/a/1190000012879279 当前后端分离时,权限问题的处理也和我们传统的处理方式有一点差异.笔者前几天刚好在负责一个项目的权限管理 ...

随机推荐

  1. 学习vue&period;js 第一天

    最近听到很多人都在用Vue.js ,我也想凑凑热闹,来个入门 啥的 ,要不以后人家说,啥都不知道,多low 看到官网 是这样介绍Vue.js Vue.js(读音 /vjuː/, 类似于 view) 是 ...

  2. JavaScript中getBoundingClientRect&lpar;&rpar;方法详解

    获取浏览器滚动的高度: scrollTop=document.documentElement.scrollTop || document.body.scrollTop getBoundingClien ...

  3. Appium&plus;Robotframework实现Android应用的自动化测试-6:一个简单的例子

    万事具备,只欠编码! 下面看一个简单的示例,这个示例验证Android手机自带的通讯录的添加联系人的操作是否成功.这个例子是Appium官网自带的示例,有兴趣的同学也可以自己下载来研究和学习,下载地址 ...

  4. &lpar;转&rpar;Linux下安装rar fou linux

    在Linux下安装rar fou linux rar for linux 软件下载地址:http://www.rarsoft.com/download.htm 到目前为止最新的版本为4.10 beta ...

  5. not in改写关联无需考虑重复数据

    SQL> select * from a1; ID NAME ---------- ---------- 1 a 1 a 2 a 3 a SQL> select * from a2; ID ...

  6. WPF关于&OpenCurlyDoubleQuote;在&OpenCurlyDoubleQuote;System&period;Windows&period;Markup&period;StaticResourceHolder”上提供值时引发了异常。”问题解决办法

    在WPF中添加样式,在MainWindow.xaml使用自定义按钮FButton时报错,报错信息如下: "System.Windows.Markup.XamlParseException&q ...

  7. Find and run the whalesay image

    Find and run the whalesay image People all over the world create Docker images. You can find these i ...

  8. myeclipse中的类恢复之前的版本方法

    1.右键要恢复的文件,点击如下的选项. 2.界面中出现之前保存的版本,双击要查看的版本,可对比版本之间的不同之处.点击Replace,恢复版本.

  9. python学习&equals;&equals;&equals;从键盘输入一些字符,逐个把它们写到磁盘文件上,直到输入一个 &num; 为止。

    #!/usr/bin/python # -*- coding: UTF-8 -*- if __name__ == '__main__': from sys import stdout filename ...

  10. java SPI机制

    1. SPI是Service Provider Interfaces的简称.根据Java的SPI规范,我们可以定义一个服务接口,具体的实现由对应的实现者去提供,即Service Provider(服务 ...