Java17 --- SpringSecurity之授权

2024-06-16 18:36

本文主要是介绍Java17 --- SpringSecurity之授权,希望对大家解决编程问题提供一定的参考价值,需要的开发者们随着小编来一起学习吧!

目录

一、授权

1.1、基于request的授权

1.2、请求未授权处理 

1.3、角色分配 

1.4、基于方法授权 


一、授权

1.1、基于request的授权

 @Beanpublic SecurityFilterChain securityFilterChain(HttpSecurity httpSecurity) throws Exception {httpSecurity.sessionManagement(session ->session.maximumSessions(1).expiredSessionStrategy(new MySessionInformationExpiredStrategy()));//会话并发处理httpSecurity.cors(Customizer.withDefaults());//跨域处理httpSecurity.authorizeRequests(authorize -> authorize.requestMatchers("/getListUser").hasAuthority("USER_LIST").requestMatchers("/addUser").hasAuthority("USER_ADD").anyRequest() //对所有请求开启授权保护.authenticated() //已认证的请求会自动授权);httpSecurity.formLogin(//Customizer.withDefaults()//使用表单授权方式//.httpBasic(Customizer.withDefaults());//使用基本授权方式form -> form.loginPage("/login").permitAll()//无需授权就能访问.usernameParameter("name").passwordParameter("pass").successHandler(new MyAuthenticationSuccessHandler())//认证成功的处理.failureHandler(new MyAuthenticationFailureHandler())//认证失败的处理);httpSecurity.logout(logout ->logout.logoutSuccessHandler(new MyLogoutSuccessHandler())//用户注销成功处理);httpSecurity.exceptionHandling(exception ->exception.authenticationEntryPoint(new MyAuthenticationEntryPoint()));//请求未认证处理httpSecurity.csrf(csrf -> csrf.disable());//关闭csrf功能return httpSecurity.build();}
 @Overridepublic UserDetails loadUserByUsername(String username) throws UsernameNotFoundException {QueryWrapper<User> userQueryWrapper = new QueryWrapper<>();userQueryWrapper.eq("name",username);User user = userMapper.selectOne(userQueryWrapper);if (user == null) {throw new UsernameNotFoundException(username);}else {Collection<GrantedAuthority> collection = new ArrayList<>();collection.add(()->"USER_LIST");collection.add(()->"USER_ADD");return new org.springframework.security.core.userdetails.User(user.getName(),user.getPassword(),user.getEnabled(),true,//用户账号是否过期true, //用户凭证是否过期true, //用户是否被锁定collection //权限列表);}}

1.2、请求未授权处理 

public class MyAccessDeniedHandler  implements AccessDeniedHandler{@Overridepublic void handle(HttpServletRequest request, HttpServletResponse response, AccessDeniedException accessDeniedException) throws IOException, ServletException {HashMap map = new HashMap<>();map.put("code",400);map.put("message","没有权限");//将信息json化String jsonString = JSON.toJSONString(map);//返回json数据到前端response.setContentType("application/json;charset=UTF-8");response.getWriter().println(jsonString);}
}
 httpSecurity.exceptionHandling(exception ->exception.authenticationEntryPoint(new MyAuthenticationEntryPoint())//请求未认证处理.accessDeniedHandler(new MyAccessDeniedHandler())//);

1.3、角色分配 

@Overridepublic UserDetails loadUserByUsername(String username) throws UsernameNotFoundException {QueryWrapper<User> userQueryWrapper = new QueryWrapper<>();userQueryWrapper.eq("name",username);User user = userMapper.selectOne(userQueryWrapper);if (user == null) {throw new UsernameNotFoundException(username);}else {return org.springframework.security.core.userdetails.User.withUsername(user.getName()).password(user.getPassword()).disabled(!user.getEnabled()).credentialsExpired(false).accountLocked(false).roles("ADMIN").build();}}
httpSecurity.authorizeRequests(authorize -> authorize
//                        .requestMatchers("/getListUser").hasAuthority("USER_LIST")
//                        .requestMatchers("/addUser").hasAuthority("USER_ADD").requestMatchers("/user/**").hasRole("ADMIN").anyRequest() //对所有请求开启授权保护.authenticated() //已认证的请求会自动授权);

1.4、基于方法授权 

在配置类中开启

@EnableMethodSecurity //开启基于方法的授权
public class MySecurityConfig {}

在方法再次控制 

 @GetMapping("/getListUser")@PreAuthorize("hasRole('ADMIN')")public List<User> getListUser(){return userService.list();}@PostMapping("/addUser")@PreAuthorize("hasRole('TOM')")public void addUser(@RequestBody User user){userService.saveUser(user);System.out.println("添加一次");}

 

 

 

 

 

 

这篇关于Java17 --- SpringSecurity之授权的文章就介绍到这儿,希望我们推荐的文章对编程师们有所帮助!


原文地址:
本文来自互联网用户投稿,该文观点仅代表作者本人,不代表本站立场。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如若转载,请注明出处:http://www.chinasem.cn/article/1067226

相关文章

Spring Boot项目部署命令java -jar的各种参数及作用详解

《SpringBoot项目部署命令java-jar的各种参数及作用详解》:本文主要介绍SpringBoot项目部署命令java-jar的各种参数及作用的相关资料,包括设置内存大小、垃圾回收... 目录前言一、基础命令结构二、常见的 Java 命令参数1. 设置内存大小2. 配置垃圾回收器3. 配置线程栈大小

SpringBoot实现微信小程序支付功能

《SpringBoot实现微信小程序支付功能》小程序支付功能已成为众多应用的核心需求之一,本文主要介绍了SpringBoot实现微信小程序支付功能,文中通过示例代码介绍的非常详细,对大家的学习或者工作... 目录一、引言二、准备工作(一)微信支付商户平台配置(二)Spring Boot项目搭建(三)配置文件

解决SpringBoot启动报错:Failed to load property source from location 'classpath:/application.yml'

《解决SpringBoot启动报错:Failedtoloadpropertysourcefromlocationclasspath:/application.yml问题》这篇文章主要介绍... 目录在启动SpringBoot项目时报如下错误原因可能是1.yml中语法错误2.yml文件格式是GBK总结在启动S

Spring中配置ContextLoaderListener方式

《Spring中配置ContextLoaderListener方式》:本文主要介绍Spring中配置ContextLoaderListener方式,具有很好的参考价值,希望对大家有所帮助,如有错误... 目录Spring中配置ContextLoaderLishttp://www.chinasem.cntene

java实现延迟/超时/定时问题

《java实现延迟/超时/定时问题》:本文主要介绍java实现延迟/超时/定时问题,具有很好的参考价值,希望对大家有所帮助,如有错误或未考虑完全的地方,望不吝赐教... 目录Java实现延迟/超时/定时java 每间隔5秒执行一次,一共执行5次然后结束scheduleAtFixedRate 和 schedu

Java Optional避免空指针异常的实现

《JavaOptional避免空指针异常的实现》空指针异常一直是困扰开发者的常见问题之一,本文主要介绍了JavaOptional避免空指针异常的实现,帮助开发者编写更健壮、可读性更高的代码,减少因... 目录一、Optional 概述二、Optional 的创建三、Optional 的常用方法四、Optio

Spring Boot项目中结合MyBatis实现MySQL的自动主从切换功能

《SpringBoot项目中结合MyBatis实现MySQL的自动主从切换功能》:本文主要介绍SpringBoot项目中结合MyBatis实现MySQL的自动主从切换功能,本文分步骤给大家介绍的... 目录原理解析1. mysql主从复制(Master-Slave Replication)2. 读写分离3.

idea maven编译报错Java heap space的解决方法

《ideamaven编译报错Javaheapspace的解决方法》这篇文章主要为大家详细介绍了ideamaven编译报错Javaheapspace的相关解决方法,文中的示例代码讲解详细,感兴趣的... 目录1.增加 Maven 编译的堆内存2. 增加 IntelliJ IDEA 的堆内存3. 优化 Mave

Java String字符串的常用使用方法

《JavaString字符串的常用使用方法》String是JDK提供的一个类,是引用类型,并不是基本的数据类型,String用于字符串操作,在之前学习c语言的时候,对于一些字符串,会初始化字符数组表... 目录一、什么是String二、如何定义一个String1. 用双引号定义2. 通过构造函数定义三、St

springboot filter实现请求响应全链路拦截

《springbootfilter实现请求响应全链路拦截》这篇文章主要为大家详细介绍了SpringBoot如何结合Filter同时拦截请求和响应,从而实现​​日志采集自动化,感兴趣的小伙伴可以跟随小... 目录一、为什么你需要这个过滤器?​​​二、核心实现:一个Filter搞定双向数据流​​​​三、完整代码