SpringSecurity6从入门到实战之登录后操作

2024-06-20 11:28

本文主要是介绍SpringSecurity6从入门到实战之登录后操作,希望对大家解决编程问题提供一定的参考价值,需要的开发者们随着小编来一起学习吧!

SpringSecurity6从入门到实战之登录后操作

上次已经了解了如何进行自定义登录页面,这次主要是详细讲解登录成功,登录之后的跳转以及包括退出登录等一系列操作.让我们来看看SpringSecurity需要如何进行配置

登录之后的跳转

定义 Spring Security 配置类

@Configuration
@EnableWebSecurity
public class MySecurityConfig {// 自定义表单认证@Beanpublic SecurityFilterChain securityFilterChain(HttpSecurity http) throws Exception {http.authorizeHttpRequests().requestMatchers("/test").permitAll() // 放行该资源.requestMatchers("/login.html").permitAll() // 放行该资源.anyRequest().authenticated() // 其它请求 必须先认证通过后 才能访问.and().formLogin() // 开启表单认证.loginPage("/login.html")  // 默认登录页.loginProcessingUrl("/doLogin")  // 处理登录请求的url.usernameParameter("uname") // 用户名文件框的名称.passwordParameter("upass") // 密码框的名称// 登录成功 跳转.successForwardUrl("/test") 	 //forward转发  跳转  不会跳转到之前请求路径//.defaultSuccessUrl("/test")   //redirect 重定向 如果之前有请求路径,会优先跳转之前请求的路径.and().csrf().disable();  // 关闭 CSRF;return http.build();}
}

这里就不一一进行测试展示了

成功后的跳转有两个方法 successForwardUrl 、defaultSuccessUrl

  • successForwardUrl forward 跳转 (注意:不会跳转到之前请求路径)
  • defaultSuccessUrl redirect 跳转 (注意:如果之前请求路径,会有优先跳转之前请求路径,可以通过第二个参数进行修改)
    .defaultSuccessUrl(“/test”, true) // redirect 跳转,且直接跳到 /test

登录成功之后返回JSON

在前后端分离开发中成功之后不需要跳转到页面,只需要给返回一个 JSON 通知登录成功还是失败即可。这个时候可以通过自定义 AuthenticationSucccessHandler 实现

自定义 AuthenticationSuccessHandler 的实现类

创建MyAuthenticationSuccessHandler实现AuthenticationSuccessHandler

public class MyAuthenticationSuccessHandler implements AuthenticationSuccessHandler {@Overridepublic void onAuthenticationSuccess(HttpServletRequest request, HttpServletResponse response, Authentication authentication) throws IOException, ServletException {Map<String, Object> result = new HashMap<String, Object>();result.put("msg", "登录成功");result.put("status", 200);response.setContentType("application/json;charset=UTF-8");String s = new ObjectMapper().writeValueAsString(result);response.getWriter().println(s);}
}

定义 Spring Security 配置类

@Configuration
@EnableWebSecurity
public class MySecurityConfig {// 自定义表单认证@Beanpublic SecurityFilterChain securityFilterChain(HttpSecurity http) throws Exception {http.authorizeHttpRequests()// .....and().formLogin() // 开启表单认证// ....// 登录成功 JSON处理(将我们自定义 AuthenticationSuccessHandler 的实现类作为参数传入successHandler()即可).successHandler(new MyAuthenticationSuccessHandler()).and().csrf().disable();  //关闭 CSRF;return http.build();}
}

image.png

登录失败后的跳转

定义 Spring Security 配置类

@Configuration
@EnableWebSecurity
public class MySecurityConfig {// 自定义表单认证@Beanpublic SecurityFilterChain securityFilterChain(HttpSecurity http) throws Exception {http.authorizeHttpRequests()// .....and().formLogin() // 开启表单认证// ....// 登录失败 跳转.failureForwardUrl("/login.html") // 登录失败 forward跳转//.failureUrl("/login.html") // 登录失败 redirect跳转.and().csrf().disable();  // 关闭 CSRF;return http.build();}
}
# failureForwardUrl、failureUrl 方法类似于登录成功跳转时的 successForwardUrl 、defaultSuccessUrl 方法:- failureForwardUrl 登录失败后的 forward 跳转- failureUrl 登录失败后的 redirect 跳转

登录失败之后返回JSON

自定义 AuthenticationFailureHandler的实现类(这里与成功实现的类不一样注意!)

public class MyAuthenticationFailureHandler implements AuthenticationFailureHandler {@Overridepublic void onAuthenticationFailure(HttpServletRequest request, HttpServletResponse response, AuthenticationException exception) throws IOException, ServletException {HashMap<String, Object> result = new HashMap<>();result.put("msg", "登录失败!" + exception.getMessage());result.put("status", 500);response.setContentType("application/json; charset=UTF-8");String s = new ObjectMapper().writeValueAsString(result);response.getWriter().println(s);}
}

定义 Spring Security 配置类

@Configuration
@EnableWebSecurity
public class MySecurityConfig {// 自定义表单认证@Beanpublic SecurityFilterChain securityFilterChain(HttpSecurity http) throws Exception {http.authorizeHttpRequests()// .....and().formLogin() // 开启表单认证// ....// 登录失败 JSON处理.failureHandler(new MyAuthenticationFailureHandler()).and().csrf().disable();  // 关闭 CSRF;return http.build();}
}

退出登录之后的跳转

这里还是和上面的登录成功失败一样的流程只需要进行配置即可

定义 Spring Security 配置类

@Configuration
@EnableWebSecurity
public class MySecurityConfig {// 自定义表单认证@Beanpublic SecurityFilterChain securityFilterChain(HttpSecurity http) throws Exception {http.authorizeHttpRequests()// .....and().formLogin() // 开启表单认证// ....// 退出.and().logout().logoutUrl("/logout") // 默认 /logout.invalidateHttpSession(true) // 默认true 让当前session失效.clearAuthentication(true) // 默认true 清除当前认证标记.logoutSuccessUrl("/login.html") // 退出成功后 跳转到/login.html.and().csrf().disable();;return http.build();}
}

模拟主页,退出登录按钮

<!DOCTYPE html>
<html lang="en">
<head><meta charset="UTF-8"><title>主页</title>
</head>
<body>
<h3>欢迎来到主页</h3>
当前用户:xxx <br/>
<a href="/logout">退出</a>
</body>
</html>

定义主页controller

IndexController

@Controller
public class IndexController {@RequestMapping("/index.html")public String index() {return "index";}
}

退出登录之后返回JSON

自定义 LogoutSuccessHandler 的实现类

也是跟上面一样的流程需要创建一个自定义 LogoutSuccessHandler 的实现类,然后进行配置

public class MyLogoutSuccessHandler implements LogoutSuccessHandler {@Overridepublic void onLogoutSuccess(HttpServletRequest request, HttpServletResponse response, Authentication authentication) throws IOException, ServletException {HashMap<String, Object> result = new HashMap<>();result.put("msg", "退出成功!" + authentication);result.put("status", 200);response.setContentType("application/json; charset=UTF-8");String s = new ObjectMapper().writeValueAsString(result);response.getWriter().println(s);}
}

定义 Spring Security 配置类

@Configuration
@EnableWebSecurity
public class MySecurityConfig {// 自定义表单认证@Beanpublic SecurityFilterChain securityFilterChain(HttpSecurity http) throws Exception {http.authorizeHttpRequests()// .....and().formLogin() // 开启表单认证// ....// 退出.and().logout().logoutUrl("/logout") // 默认 /logout.invalidateHttpSession(true) // 默认true 让当前session失效.clearAuthentication(true) // 默认true 清除当前认证标记.logoutSuccessHandler(new MyLogoutSuccessHandler()).and().csrf().disable();;return http.build();}
}

这篇关于SpringSecurity6从入门到实战之登录后操作的文章就介绍到这儿,希望我们推荐的文章对编程师们有所帮助!



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

相关文章

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

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

Spring Boot + MyBatis Plus 高效开发实战从入门到进阶优化(推荐)

《SpringBoot+MyBatisPlus高效开发实战从入门到进阶优化(推荐)》本文将详细介绍SpringBoot+MyBatisPlus的完整开发流程,并深入剖析分页查询、批量操作、动... 目录Spring Boot + MyBATis Plus 高效开发实战:从入门到进阶优化1. MyBatis

MyBatis 动态 SQL 优化之标签的实战与技巧(常见用法)

《MyBatis动态SQL优化之标签的实战与技巧(常见用法)》本文通过详细的示例和实际应用场景,介绍了如何有效利用这些标签来优化MyBatis配置,提升开发效率,确保SQL的高效执行和安全性,感... 目录动态SQL详解一、动态SQL的核心概念1.1 什么是动态SQL?1.2 动态SQL的优点1.3 动态S

Mysql表的简单操作(基本技能)

《Mysql表的简单操作(基本技能)》在数据库中,表的操作主要包括表的创建、查看、修改、删除等,了解如何操作这些表是数据库管理和开发的基本技能,本文给大家介绍Mysql表的简单操作,感兴趣的朋友一起看... 目录3.1 创建表 3.2 查看表结构3.3 修改表3.4 实践案例:修改表在数据库中,表的操作主要

C# WinForms存储过程操作数据库的实例讲解

《C#WinForms存储过程操作数据库的实例讲解》:本文主要介绍C#WinForms存储过程操作数据库的实例,具有很好的参考价值,希望对大家有所帮助,如有错误或未考虑完全的地方,望不吝赐教... 目录一、存储过程基础二、C# 调用流程1. 数据库连接配置2. 执行存储过程(增删改)3. 查询数据三、事务处

Pandas使用SQLite3实战

《Pandas使用SQLite3实战》本文主要介绍了Pandas使用SQLite3实战,文中通过示例代码介绍的非常详细,对大家的学习或者工作具有一定的参考学习价值,需要的朋友们下面随着小编来一起学习学... 目录1 环境准备2 从 SQLite3VlfrWQzgt 读取数据到 DataFrame基础用法:读

Java使用Curator进行ZooKeeper操作的详细教程

《Java使用Curator进行ZooKeeper操作的详细教程》ApacheCurator是一个基于ZooKeeper的Java客户端库,它极大地简化了使用ZooKeeper的开发工作,在分布式系统... 目录1、简述2、核心功能2.1 CuratorFramework2.2 Recipes3、示例实践3

Java利用JSONPath操作JSON数据的技术指南

《Java利用JSONPath操作JSON数据的技术指南》JSONPath是一种强大的工具,用于查询和操作JSON数据,类似于SQL的语法,它为处理复杂的JSON数据结构提供了简单且高效... 目录1、简述2、什么是 jsONPath?3、Java 示例3.1 基本查询3.2 过滤查询3.3 递归搜索3.4

springboot security验证码的登录实例

《springbootsecurity验证码的登录实例》:本文主要介绍springbootsecurity验证码的登录实例,具有很好的参考价值,希望对大家有所帮助,如有错误或未考虑完全的地方,... 目录前言代码示例引入依赖定义验证码生成器定义获取验证码及认证接口测试获取验证码登录总结前言在spring

Python使用DrissionPage中ChromiumPage进行自动化网页操作

《Python使用DrissionPage中ChromiumPage进行自动化网页操作》DrissionPage作为一款轻量级且功能强大的浏览器自动化库,为开发者提供了丰富的功能支持,本文将使用Dri... 目录前言一、ChromiumPage基础操作1.初始化Drission 和 ChromiumPage