springsecurity:权限与异常处理
权限即不同用户可以使用不同功能
实现前置:
在上一次登录与校验中,我们将authentication存入到SecurityContextHolder中,后续我们需要从FilterSecurityInterceptor取出并进行验证
基于注解实现
开启相关配置(放在config里)
@EnableGlobalMethodSecurity(prePostEnabled = true) //适用于springboot2
@EnableMethodSecurity(prePostEnabled = true) //适用于springboot3
对应主要注解
@PreAuthorize("hasAuthority('ROLE_USER')")
需要修改的有两部分:
1.在我们自定义的UserDetailService中我们重写了loadUserByUsername:返回的LoginUser还包括了权限。在上一次,我们仅仅向里封装了一个User信息。除此以外,我们还需要一个权限信息,因此基于上次的User信息,我们对LoginUser增加了成员变量
@Data
@NoArgsConstructor
public class LoginUser implements UserDetails {
private User user;
private List<String> permissions;
// 这里不进行序列化/反序列化的原因是SimpleGrantedAuthority没实现序列化,而且我们已经有permissions,可直接通过get方法获取authorities
// 其实他可以不做成员变量,但是这样可以节省系统开销:不必多次创建authorities
@JSONField(serialize = false)
private List<SimpleGrantedAuthority> authorities;
public LoginUser(User user, List<String> permissions) {
this.user = user;
this.permissions = permissions;
}
@Override
public Collection<? extends GrantedAuthority> getAuthorities() {
if(this.authorities!=null){
return this.authorities;
}
//如何选定的simplegrantedauthority:
// 通过查看grantedAuhority源码,通过ctrl+alt点击这个接口,我们发现他有三个实现类,我们从中选择其一
// 本方法即把string转换为相关的权限类型以便于preAuthorize(hasAuthority(''))使用
this.authorities=this.permissions.stream().map(SimpleGrantedAuthority::new).collect(Collectors.toList());
return this.authorities;
}
@Override
public String getPassword() {
return user.getPassword();
}
@Override
public String getUsername() {
return user.getUserName();
}
@Override
public boolean isAccountNonExpired() {
return true;
}
@Override
public boolean isAccountNonLocked() {
return true;
}
@Override
public boolean isCredentialsNonExpired() {
return true;
}
@Override
public boolean isEnabled() {
return true;
}
}
2.在拦截器中写入对应的权限信息
SecurityContextHolder.getContext().
setAuthentication(new UsernamePasswordAuthenticationToken(loginUser,null,loginUser.getAuthorities()));
异常:异常一般有两种:登录不上去,权限不够
1.登录失败(身份入口)新增异常处理
@Component
public class AuthenticationEntryPointImpl implements AuthenticationEntryPoint {
@Override
public void commence(HttpServletRequest request, HttpServletResponse response, AuthenticationException authException) throws IOException, ServletException {
ResponseResult result = new ResponseResult(HttpStatus.UNAUTHORIZED.value(),"用户认证失败!请重新登录");
String json= JSON.toJSONString(result);
WebUtil.renderString(response, json);
}
}
2.权限不足新增异常处理
@Component
public class AccessDeniedHandlerImpl implements AccessDeniedHandler {
@Override
public void handle(HttpServletRequest request, HttpServletResponse response, AccessDeniedException accessDeniedException) throws IOException, ServletException {
ResponseResult result = new ResponseResult(HttpStatus.FORBIDDEN.value(),"用户权限不足!");
String json= JSON.toJSONString(result);
WebUtil.renderString(response, json);
}
}
WebUtil
public class WebUtil {
/**
* 将字符串渲染到客户端
*
* @param response 渲染对象
* @param string 待渲染的字符串
* @return null
*/
public static String renderString(HttpServletResponse response, String string) {
try {
response.setStatus(200);
response.setContentType("application/json");
response.setCharacterEncoding("utf-8");
response.getWriter().print(string);
} catch (IOException e) {
e.printStackTrace();
}
return null;
}
}
修改securityConfig
// 添加异常处理器
http
.exceptionHandling()
.authenticationEntryPoint(authenticationEntryPoint)
.accessDeniedHandler(accessDeniedHandler);
springsecurity:权限与异常处理的更多相关文章
- SpringSecurity权限管理系统实战—二、日志、接口文档等实现
系列目录 SpringSecurity权限管理系统实战-一.项目简介和开发环境准备 SpringSecurity权限管理系统实战-二.日志.接口文档等实现 SpringSecurity权限管理系统实战 ...
- SpringSecurity权限管理系统实战—七、处理一些问题
目录 SpringSecurity权限管理系统实战-一.项目简介和开发环境准备 SpringSecurity权限管理系统实战-二.日志.接口文档等实现 SpringSecurity权限管理系统实战-三 ...
- SpringSecurity权限管理系统实战—一、项目简介和开发环境准备
目录 SpringSecurity权限管理系统实战-一.项目简介和开发环境准备 SpringSecurity权限管理系统实战-二.日志.接口文档等实现 SpringSecurity权限管理系统实战-三 ...
- SpringSecurity权限管理系统实战—四、整合SpringSecurity(上)
目录 SpringSecurity权限管理系统实战-一.项目简介和开发环境准备 SpringSecurity权限管理系统实战-二.日志.接口文档等实现 SpringSecurity权限管理系统实战-三 ...
- SpringSecurity权限管理系统实战—六、SpringSecurity整合jwt
目录 SpringSecurity权限管理系统实战-一.项目简介和开发环境准备 SpringSecurity权限管理系统实战-二.日志.接口文档等实现 SpringSecurity权限管理系统实战-三 ...
- SpringSecurity权限管理系统实战—八、AOP 记录用户、异常日志
目录 SpringSecurity权限管理系统实战-一.项目简介和开发环境准备 SpringSecurity权限管理系统实战-二.日志.接口文档等实现 SpringSecurity权限管理系统实战-三 ...
- SpringSecurity权限管理系统实战—九、数据权限的配置
目录 SpringSecurity权限管理系统实战-一.项目简介和开发环境准备 SpringSecurity权限管理系统实战-二.日志.接口文档等实现 SpringSecurity权限管理系统实战-三 ...
- spring-security权限控制详解
在本例中,主要讲解spring-boot与spring-security的集成,实现方式为: 将用户.权限.资源(url)采用数据库存储 自定义过滤器,代替原有的 FilterSecurityInte ...
- SpringSecurity权限管理系统实战—五、整合SpringSecurity(下)
系列目录 前言 上篇文章SpringSecurity整合了一半,这次把另一半整完,所以本篇的序号接着上一篇. 七.自定义用户信息 前面我们登录都是用的指定的用户名和密码或者是springsecurit ...
- sonar + jacoco + mockMvc 模拟session 用户登录 配合SpringSecurity 权限 快速测试代码覆盖率.
遇到mock 测试简直就是神器,特别是要做代码覆盖率,直接测试controller就好了,缺点,虽然可以回滚事务,但是依赖数据库数据,解决,根据SpringBoot ,再建立一个专门跑单元测试的数据库 ...
随机推荐
- Android 12(S) MultiMedia Learning(十)ACodec & OMX
这一节的学习分为三块内容,omx hidl service用法.OMX架构.ACodec中的buffer分配. 1.omx hidl service system可以借助vndbinder来访问ven ...
- linux中磁盘清理方法(简单好用)
文章目录1.命令2.df参数说明3.find参数说明4.清理日志文件1.命令先来看解决办法 df -h --显示当前磁盘使用情况cd / --cd到要清理文件的路径下面find . -type f - ...
- NaN数值类型
<!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8 ...
- ajax传参
// ajax传参 // ajax传参特点: // 1,不需要跳转 // 2,ajax传参,都是异步程序 // ...
- CF1900D - Small GCD 题解
1900D - Small GCD 给定序列 \(A\),定义 \(f(a, b, c)\) 为 \(a, b, c\) 中最小的次小的数的 \(\gcd\),求: \[\sum_{i = 1}^n ...
- rsync备份
备份工具rsync 备份是太常见.且太重要的一个日常工作了. 备份源码.文档.数据库.等等. 类似cp命令拷贝,但是支持服务器之间的网络拷贝,且保证安全性. 学习背景 超哥游戏公司要每天都要对代码备份 ...
- 【踩坑】.NET 8.0 自定义IExceptionHandler不生效
中间件实现异常处理 在ASP.NET Core里,我们可以使用中间件(Middleware)实现全局的异常处理. 如内置的异常处理中间件 UseExceptionHandler app.UseExce ...
- WPF/C#:数据绑定到方法
在WPF Samples中有一个关于数据绑定到方法的Demo,该Demo结构如下: 运行效果如下所示: 来看看是如何实现的. 先来看下MainWindow.xaml中的内容: <Window.R ...
- TI AM62x工业开发板规格书(单/双/四核ARM Cortex-A53 + 单核ARM Cortex-M4F,主频1.4GHz)
1 评估板简介 创龙科技TL62x-EVM是一款基于TI Sitara系列AM62x单/双/四核ARM Cortex-A53 + 单核ARM Cortex-M4F多核处理器设计的高性能低功耗工业评估板 ...
- QT 使用相对路径读取.txt文件
QT可以使用QFile来读取.txt文件,具体代码实现如下: 1 #include <QCoreApplication> 2 #include <QString> 3 #inc ...