基于spring security实现登录注销功能过程解析
作者:炫舞风中 发布时间:2023-11-29 06:09:05
标签:spring,security,登录,功能
这篇文章主要介绍了基于spring security实现登录注销功能过程解析,文中通过示例代码介绍的非常详细,对大家的学习或者工作具有一定的参考学习价值,需要的朋友可以参考下
1、引入maven依赖
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-security</artifactId>
</dependency>
2、Security 配置类 说明登录方式、登录页面、哪个url需要认证、注入登录失败/成功过滤器
@Configuration
public class BrowserSecurityConfig extends WebSecurityConfigurerAdapter {
/**
* 注入 Security 属性类配置
*/
@Autowired
private SecurityProperties securityProperties;
/**
* 注入 自定义的 登录成功处理类
*/
@Autowired
private MyAuthenticationSuccessHandler mySuccessHandler;
/**
* 注入 自定义的 登录失败处理类
*/
@Autowired
private MyAuthenticationFailHandler myFailHandler;
/**
* 重写PasswordEncoder 接口中的方法,实例化加密策略
* @return 返回 BCrypt 加密策略
*/
@Bean
public PasswordEncoder passwordEncoder(){
return new BCryptPasswordEncoder();
}
@Override
protected void configure(HttpSecurity http) throws Exception {
//登录成功的页面地址
String redirectUrl = securityProperties.getLoginPage();
//basic 登录方式
// http.httpBasic()
//表单登录 方式
http.formLogin()
.loginPage("/authentication/require")
//登录需要经过的url请求
.loginProcessingUrl("/authentication/form")
.successHandler(mySuccessHandler)
.failureHandler(myFailHandler)
.and()
//请求授权
.authorizeRequests()
//不需要权限认证的url
.antMatchers("/authentication/*",redirectUrl).permitAll()
//任何请求
.anyRequest()
//需要身份认证
.authenticated()
.and()
//关闭跨站请求防护
.csrf().disable();
//默认注销地址:/logout
http.logout().
//注销之后 跳转的页面
logoutSuccessUrl("/authentication/require");
}
3、自定义登录成功和失败的处理器
(1)、登录成功
@Component
@Slf4j
public class MyAuthenticationSuccessHandler extends SavedRequestAwareAuthenticationSuccessHandler {
@Override
public void onAuthenticationSuccess(HttpServletRequest httpServletRequest, HttpServletResponse httpServletResponse, Authentication authentication) throws IOException, ServletException {
logger.info("登录成功");
//将 authention 信息打包成json格式返回
httpServletResponse.setContentType("application/json;charset=UTF-8");
httpServletResponse.getWriter().write("登录成功");
} }
(2)、登录失败
@Component
@Slf4j
public class MyAuthenticationFailHandler extends SimpleUrlAuthenticationFailureHandler {
@Override
public void onAuthenticationFailure(HttpServletRequest httpServletRequest, HttpServletResponse httpServletResponse, AuthenticationException e) throws IOException, ServletException {
logger.info("登录失败");
//设置状态码
httpServletResponse.setStatus(500);
//将 登录失败 信息打包成json格式返回
httpServletResponse.setContentType("application/json;charset=UTF-8");
httpServletResponse.getWriter().write("登录失败:"+e.getMessage());
} }
4、UserDetail 类 加载用户数据 , 返回UserDetail 实例 (里面包含用户信息)
@Component
@Slf4j
public class MyUserDetailsService implements UserDetailsService {
@Autowired
private PasswordEncoder passwordEncoder;
/**
* 根据进行登录
* @param username
* @return
* @throws UsernameNotFoundException
*/
@Override
public UserDetails loadUserByUsername(String username) throws UsernameNotFoundException {
log.info("登录用户名:"+username);
String password = passwordEncoder.encode("123456");
//User三个参数 (用户名+密码+权限)
//根据查找到的用户信息判断用户是否被冻结
log.info("数据库密码:"+password);
return new User(username,password, AuthorityUtils.commaSeparatedStringToAuthorityList("admin"));
}
}
5、登录路径请求类,.loginPage("/authentication/require")
@RestController
@Slf4j
@ResponseStatus(code = HttpStatus.UNAUTHORIZED)
public class BrowerSecurityController {
/**
* 把当前的请求缓存到 session 里去
*/
private RequestCache requestCache = new HttpSessionRequestCache();
/**
* 重定向 策略
*/
private RedirectStrategy redirectStrategy = new DefaultRedirectStrategy();
/**
* 注入 Security 属性类配置
*/
@Autowired
private SecurityProperties securityProperties;
/**
* 当需要身份认证时 跳转到这里
*/
@RequestMapping("/authentication/require")
public SimpleResponse requireAuthentication(HttpServletRequest request, HttpServletResponse response) throws IOException {
//拿到请求对象
SavedRequest savedRequest = requestCache.getRequest(request, response);
if (savedRequest != null){
//获取 跳转url
String targetUrl = savedRequest.getRedirectUrl();
log.info("引发跳转的请求是:"+targetUrl);
//判断 targetUrl 是不是 .html结尾, 如果是:跳转到登录页(返回view)
if (StringUtils.endsWithIgnoreCase(targetUrl,".html")){
String redirectUrl = securityProperties.getLoginPage();
redirectStrategy.sendRedirect(request,response,redirectUrl);
}
}
//如果不是,返回一个json 字符串
return new SimpleResponse("访问的服务需要身份认证,请引导用户到登录页");
}
6、postman请求测试
(1)未登录请求
(2)、登录
(3)、再次访问
(4)、注销
来源:https://www.cnblogs.com/cq-yangzhou/p/12157078.html


猜你喜欢
- 前导:发过程中经常会使用java将office系列文档转换为PDF, 一般都使用微软提供的openoffice+jodconverter 实
- 背景Java是一种流行的编程语言,验证码是一种常用的网络安全技术。Java发展至今,网上也出现了各种各样的验证码,本人初学Java,下面是我
- 基本概念Java中创建对象时,一旦程序终止,创建的对象可能就不存在.要想使得对象能够在程序不运行的状态下依然能够保存对象的信息,这时就需要用
- 概述在本文章中,我们对如何在 Java 中对 Array 和 List 进行转换进行一些说明和示例。这些示例通过使用 Core Java 和
- 在Java中如果一个类同时继承接口A与B,并且这两个接口中具有同名方法,会怎么样?动手做实验:interface A{ void
- 前章知识: 点此跳转HTML简介:超文本是一种组织信息的方式,它通过超级链接方法将文本中的文字、图表与其他信息媒体相关联。这些相互关联的信息
- 迷宫项目实现设计文档项目介绍:一个网格迷宫由n行m列的单元格组成,每个大院个要么是空地(用0表示),要么是障碍物(用1表示)。你的任务是找一
- Tomcat启动报异常java.lang.ClassNotFoundExceptionTomcat启动报异常:java.lang.Class
- 简介线段树是一种二叉搜索树,是用来维护区间信息的数据结构。可以在O(logN)的时间复杂度内实现单点修改、区间修改、区间查询(区间求和,求区
- java的接口解耦方式我只想把抽象的东西说的具体,或者说,听起来简单些,明白些。。。学过java的人都知道,java是单继承的,也就是说一个
- 首先,通过一张最新(2021.11)的编程语言排名图来了解常见的编程语言:从图中可以看出,C++的排名相对于Python、Java、C来说并
- 1. 查找系统中坏味道的异常处理代码在上篇文章杂谈异常处理try-catch-finally中主要详细介绍了C#异常处理的概念,
- 本文主要汇总了在开发过程中,使用List和Dictionary常用的方法,例如增、删、改、查、排序等等各种常用操作。在平时的开发过程中,Li
- 本文借由并发环境下使用线程不安全的SimpleDateFormat优化案例,帮助大家理解ThreadLocal.最近整理公司项目,发现不少写
- 在平时的开发中,我们会经常遇到这样一个需求,要在页面通过一个『导出』按钮把查询出的数据导出到 Excel 表格中。本文即为实现上述需求的一个
- 详解java 中Spring jsonp 跨域请求的实例jsonp介绍  
- 本文实例讲述了C#常用目录文件操作类。分享给大家供大家参考。具体分析如下:这个c#类封装了常用的目录操作,包括列出目录下的文件、检测目录是否
- 一、AtomicReference 基本使用我们这里再聊起老生常谈的账户问题,通过个人银行账户问题,来逐渐引入 AtomicReferenc
- 今天遇到pom中添加dependency时相关的jar会自动下载,但是左边的External Libraries中一直获取不到添加的jar问
- 目录一、事出有因二、解决方案困境三、柳暗花明,终级解决方案第一种实现方案第二种实现方案第三种实现方案四、引发的思考一、事出有因最近有一个场景