本文主要是介绍Spring Security 弃用 WebSecurityConfigurerAdapter 重写登录接口 前后端分离 返回json数据格式,希望对大家解决编程问题提供一定的参考价值,需要的开发者们随着小编来一起学习吧!
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.0.0 版本的写法
这篇关于Spring Security 弃用 WebSecurityConfigurerAdapter 重写登录接口 前后端分离 返回json数据格式的文章就介绍到这儿,希望我们推荐的文章对编程师们有所帮助!