Spring Security 弃用 WebSecurityConfigurerAdapter 重写登录接口

本文主要是介绍Spring Security 弃用 WebSecurityConfigurerAdapter 重写登录接口,希望对大家解决编程问题提供一定的参考价值,需要的开发者们随着小编来一起学习吧!

springboot 版本高于 2.7 之后 弃用了 WebSecurityConfigurerAdapter  推荐使用组件化配置安全组件。

原版本的2.7版本的登录接口  

功能: 通过/api/doLogin 进行登录 

package cn.devops.config;import cn.devops.model.User;
import cn.devops.response.RespBean;
import cn.devops.service.DevopsService;
import cn.devops.service.UserService;
import com.fasterxml.jackson.databind.ObjectMapper;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.security.authentication.*;
import org.springframework.security.config.annotation.authentication.builders.AuthenticationManagerBuilder;
import org.springframework.security.config.annotation.web.builders.HttpSecurity;
import org.springframework.security.config.annotation.web.builders.WebSecurity;
import org.springframework.security.config.annotation.web.configuration.WebSecurityConfigurerAdapter;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.AuthenticationException;
import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder;
import org.springframework.security.crypto.password.PasswordEncoder;
import org.springframework.security.web.authentication.AuthenticationFailureHandler;
import org.springframework.security.web.authentication.AuthenticationSuccessHandler;
import org.springframework.security.web.authentication.logout.LogoutSuccessHandler;import javax.annotation.Resource;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.PrintWriter;/*** @author morey* 用户登录模块*/
@Configuration
public class SecurityConfig_bak extends WebSecurityConfigurerAdapter {@ResourceUserService userService;@ResourceDevopsService devopsService;/*** 带salt的加密*/@Beanpublic PasswordEncoder passwordEncoder() {return new BCryptPasswordEncoder(5);}/*** 全局身份认证器*/@Overrideprotected void configure(AuthenticationManagerBuilder auth) throws Exception {auth.userDetailsService(userService);}/*** 配置需要忽略的url*/@Overridepublic void configure(WebSecurity web) throws Exception {web.ignoring().antMatchers("/fonts/**", "/js/**", "/css/**", "index.html", "favicon.ico", "/static/**", "/sys/**", "/user/**", "/actuator/**","/api/hello/admin");}/*** 配置具体的控制权限 http请求的安全处理* 配合拦截规则,表单登录,登录成功与失败的响应等*/@Overrideprotected void configure(HttpSecurity http) throws Exception {http.authorizeRequests()//.antMatchers("/","index.html").permitAll().anyRequest().authenticated().and().formLogin().usernameParameter("username").passwordParameter("password").loginProcessingUrl("/api/doLogin")//.loginPage("/index.html").successHandler(new AuthenticationSuccessHandler() {@Overridepublic void onAuthenticationSuccess(HttpServletRequest req, HttpServletResponse resp, Authentication auth)throws IOException, ServletException {resp.setContentType("application/json;charset=utf-8");//创建输出流,得到request文件流PrintWriter out = resp.getWriter();//Principal是一个包含用户标识和用户角色的对象User user = (User) auth.getPrincipal();//返回json时忽略password字段给前端 安全考虑user.setPassword(null);RespBean ok = RespBean.ok("登录成功", user);//将java对象转换成json字符串String s = new ObjectMapper().writeValueAsString(ok);//将request文件流写入json中out.write(s);out.flush();out.close();}}).failureHandler(new AuthenticationFailureHandler() {@Overridepublic void onAuthenticationFailure(HttpServletRequest req, HttpServletResponse resp, AuthenticationException exception) throws IOException, ServletException {resp.setContentType("application/json;charset=utf-8");//获取响应流PrintWriter out = resp.getWriter();RespBean respBean = RespBean.error("登录失败");if (exception instanceof LockedException) {respBean.setMsg("账号锁定,请联系管理员");} else if (exception instanceof CredentialsExpiredException) {respBean.setMsg("密码过期,请联系管理员");} else if (exception instanceof AccountExpiredException) {respBean.setMsg("账号过期,请联系管理员");} else if (exception instanceof DisabledException) {respBean.setMsg("账号被禁用,请联系管理员");} else if (exception instanceof BadCredentialsException) {respBean.setMsg("用户名或密码错误,请重新输入");}out.write(new ObjectMapper().writeValueAsString(respBean));out.flush();out.close();}}).permitAll().and().logout().logoutSuccessHandler(new LogoutSuccessHandler() {@Overridepublic void onLogoutSuccess(HttpServletRequest req, HttpServletResponse resp, Authentication authentication) throws IOException, ServletException {resp.setContentType("application/json;charset=utf-8");PrintWriter out = resp.getWriter();out.write(new ObjectMapper().writeValueAsString(RespBean.ok("注销成功")));out.flush();out.close();}}).permitAll().and().csrf().disable();}
}

spring-boot-starter Security  3.2.2版本的写法

这篇关于Spring Security 弃用 WebSecurityConfigurerAdapter 重写登录接口的文章就介绍到这儿,希望我们推荐的文章对编程师们有所帮助!



http://www.chinasem.cn/article/705137

相关文章

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搞定双向数据流​​​​三、完整代码

SpringBoot利用@Validated注解优雅实现参数校验

《SpringBoot利用@Validated注解优雅实现参数校验》在开发Web应用时,用户输入的合法性校验是保障系统稳定性的基础,​SpringBoot的@Validated注解提供了一种更优雅的解... 目录​一、为什么需要参数校验二、Validated 的核心用法​1. 基础校验2. php分组校验3

Java Predicate接口定义详解

《JavaPredicate接口定义详解》Predicate是Java中的一个函数式接口,它代表一个判断逻辑,接收一个输入参数,返回一个布尔值,:本文主要介绍JavaPredicate接口的定义... 目录Java Predicate接口Java lamda表达式 Predicate<T>、BiFuncti

Spring Security基于数据库的ABAC属性权限模型实战开发教程

《SpringSecurity基于数据库的ABAC属性权限模型实战开发教程》:本文主要介绍SpringSecurity基于数据库的ABAC属性权限模型实战开发教程,本文给大家介绍的非常详细,对大... 目录1. 前言2. 权限决策依据RBACABAC综合对比3. 数据库表结构说明4. 实战开始5. MyBA

Spring Security方法级安全控制@PreAuthorize注解的灵活运用小结

《SpringSecurity方法级安全控制@PreAuthorize注解的灵活运用小结》本文将带着大家讲解@PreAuthorize注解的核心原理、SpEL表达式机制,并通过的示例代码演示如... 目录1. 前言2. @PreAuthorize 注解简介3. @PreAuthorize 核心原理解析拦截与

一文详解JavaScript中的fetch方法

《一文详解JavaScript中的fetch方法》fetch函数是一个用于在JavaScript中执行HTTP请求的现代API,它提供了一种更简洁、更强大的方式来处理网络请求,:本文主要介绍Jav... 目录前言什么是 fetch 方法基本语法简单的 GET 请求示例代码解释发送 POST 请求示例代码解释

Java图片压缩三种高效压缩方案详细解析

《Java图片压缩三种高效压缩方案详细解析》图片压缩通常涉及减少图片的尺寸缩放、调整图片的质量(针对JPEG、PNG等)、使用特定的算法来减少图片的数据量等,:本文主要介绍Java图片压缩三种高效... 目录一、基于OpenCV的智能尺寸压缩技术亮点:适用场景:二、JPEG质量参数压缩关键技术:压缩效果对比

Java调用C++动态库超详细步骤讲解(附源码)

《Java调用C++动态库超详细步骤讲解(附源码)》C语言因其高效和接近硬件的特性,时常会被用在性能要求较高或者需要直接操作硬件的场合,:本文主要介绍Java调用C++动态库的相关资料,文中通过代... 目录一、直接调用C++库第一步:动态库生成(vs2017+qt5.12.10)第二步:Java调用C++