系列五、Spring Security中的认证 授权(前后端分离)

一、Spring Security中的认证 & 授权(前后端分离)

1.1、MyWebSecurityConfigurerAdapter7002

/*** @Author : 一叶浮萍归大海* @Date: 2024/1/11 21:50* @Description: Spring Security配置类*/
@Configuration
public class MyWebSecurityConfigurerAdapter7002 extends WebSecurityConfigurerAdapter {@Resourceprivate MyAuthenticationSuccessHandler7002 successHandler;@Resourceprivate MyAuthenticationFailureHandler7002 failureHandler;@Resourceprivate MyLogoutSuccessHandler logoutSuccessHandler;@Resourceprivate MyAuthenticationEntryPoint authenticationEntryPoint;/*** 密码加密器* @return*/@BeanPasswordEncoder passwordEncoder() {return NoOpPasswordEncoder.getInstance();}/*** 配置基于内存的用户* @param auth* @throws Exception*/@Overrideprotected void configure(AuthenticationManagerBuilder auth) throws Exception {auth.inMemoryAuthentication().withUser("admin").password("123456").roles("admin").and().withUser("root").password("123456").roles("root");}@Overrideprotected void configure(HttpSecurity http) throws Exception {http.authorizeRequests().antMatchers("/helloWorld").permitAll().anyRequest().authenticated().and()/*** 登录成功 & 登录失败回调*/.formLogin().loginPage("/login").successHandler(successHandler).failureHandler(failureHandler).and()/*** 注销登录回调*/.logout().logoutUrl("/logout").logoutSuccessHandler(logoutSuccessHandler).permitAll().and().csrf().disable()/*** 未认证回调*/.exceptionHandling().authenticationEntryPoint(authenticationEntryPoint);}}

1.2、MyAuthenticationSuccessHandler7002

/*** @Author : 一叶浮萍归大海* @Date: 2024/1/12 09:55* @Description: 认证(登录)成功处理器*/
@Component
public class MyAuthenticationSuccessHandler7002 implements AuthenticationSuccessHandler {@Overridepublic void onAuthenticationSuccess(HttpServletRequest request, HttpServletResponse response, Authentication authentication) throws IOException, ServletException {response.setContentType("application/json;charset=utf-8");PrintWriter out = response.getWriter();R r = R.ok().data(authentication.getPrincipal());out.write(new ObjectMapper().writeValueAsString(r));out.flush();out.close();}
}

1.3、MyAuthenticationFailureHandler7002

/*** @Author : 一叶浮萍归大海* @Date: 2023/1/12 10:05* @Description: 认证(登录)失败处理器*/
@Component
public class MyAuthenticationFailureHandler7002 implements AuthenticationFailureHandler {@Overridepublic void onAuthenticationFailure(HttpServletRequest request, HttpServletResponse response, AuthenticationException exception) throws IOException, ServletException {response.setContentType("application/json;charset=utf-8");PrintWriter out = response.getWriter();R r = R.error();if (exception instanceof LockedException) {r.data(SpringSecurityConstants.LOCKED_ERROR_MESSAGE);} else if (exception instanceof CredentialsExpiredException) {r.data(SpringSecurityConstants.CREDENTIALS_EXPIRED_ERROR_MESSAGE);} else if (exception instanceof AccountExpiredException) {r.data(SpringSecurityConstants.ACCOUNT_EXPIRED_ERROR_MESSAGE);} else if (exception instanceof DisabledException) {r.data(SpringSecurityConstants.DISABLED_ERROR_MESSAGE);} else if (exception instanceof BadCredentialsException) {r.data(SpringSecurityConstants.BAD_CREDENTIALS_ERROR_MESSAGE);} else if (exception instanceof AuthenticationServiceException) {r.data(SpringSecurityConstants.VERIFY_CODE_ERROR_MESSAGE);} else {r.data(SpringSecurityConstants.LOGIN_ERROR_COMMON_MESSAGE);}out.write(new ObjectMapper().writeValueAsString(r));out.flush();out.close();}
}

1.4、MyLogoutSuccessHandler7002

/*** @Author : 一叶浮萍归大海* @Date: 2024/01/12 11:26* @Description: 注销登录处理器*/
@Component
public class MyLogoutSuccessHandler7002 implements LogoutSuccessHandler {@Overridepublic void onLogoutSuccess(HttpServletRequest request, HttpServletResponse response, Authentication authentication) throws IOException, ServletException {response.setContentType("application/json;charset=utf-8");PrintWriter out = response.getWriter();R r = R.ok().data(SpringSecurityConstants.LOGOUT_SUCCESS_MESSAGE);out.write(new ObjectMapper().writeValueAsString(r));out.flush();out.close();}}

1.5、MyAuthenticationEntryPoint7002

/*** @Author : 一叶浮萍归大海* @Date: 2024/01/12 11:27* @Description: 未认证处理方案(用户未登录就访问资源)*/
@Component
public class MyAuthenticationEntryPoint7002 implements AuthenticationEntryPoint {@Overridepublic void commence(HttpServletRequest request, HttpServletResponse response, AuthenticationException authException) throws IOException, ServletException {response.setContentType("application/json;charset=utf-8");PrintWriter out = response.getWriter();R r = R.error(ResponseEnum.HTTP_UNAUTHORIZED_ERROR.getCode(),ResponseEnum.HTTP_UNAUTHORIZED_ERROR.getMessage());out.write(new ObjectMapper().writeValueAsString(r));out.flush();out.close();}}

1.6、SpringSecurityConstants7002

/*** @Author 一叶浮萍归大海* @Description Spring Security认证 & 授权常量类* @Date 2024/01/12 10:06*/
public class SpringSecurityConstants {public static final String LOGOUT_SUCCESS_MESSAGE = "注销成功!";public static final String LOCKED_ERROR_MESSAGE = "账户被锁定,请联系管理员!";public static final String CREDENTIALS_EXPIRED_ERROR_MESSAGE = "密码过期,请联系管理员!";public static final String ACCOUNT_EXPIRED_ERROR_MESSAGE = "账户过期,请联系管理员!";public static final String DISABLED_ERROR_MESSAGE = "账户被禁用,请联系管理员!";public static final String BAD_CREDENTIALS_ERROR_MESSAGE = "用户名或者密码错误,请重新输入!";public static final String VERIFY_CODE_ERROR_MESSAGE = "验证码错误!";public static final String LOGIN_ERROR_COMMON_MESSAGE = "登录失败,请联系管理员!";
}

1.7、R

/*** @Author 一叶浮萍归大海* @Description* @Date 2023/01/12 10:06*/
@Data
public class R<T> {private Integer code;private String message;private T data;/*** 构造函数私有化*/private R(){}/*** 返回成功结果* @return*/public static R ok(){R r = new R();r.setCode(ResponseEnum.SUCCESS.getCode());r.setMessage(ResponseEnum.SUCCESS.getMessage());return r;}/*** 返回失败结果* @return*/public static R error(){R r = new R();r.setCode(ResponseEnum.ERROR.getCode());r.setMessage(ResponseEnum.ERROR.getMessage());return r;}public static R error(int code, String msg) {R r = new R();r.setCode(code);r.setMessage(msg);return r;}/*** 设置特定的结果* @param responseEnum* @return*/public static R setResult(ResponseEnum responseEnum){R r = new R();r.setCode(responseEnum.getCode());r.setMessage(responseEnum.getMessage());return r;}public R data(T entity) {this.setData(entity);return this;}/*** 设置特定的响应消息* @param message* @return*/public R message(String message){this.setMessage(message);return this;}/*** 设置特定的响应码* @param code* @return*/public R code(Integer code){this.setCode(code);return this;}
}

1.8、ResponseEnum

/*** @Author 一叶浮萍归大海* @Description* @Date 2023/5/30 15:55*/
@Getter
@ToString
@AllArgsConstructor
public enum ResponseEnum {/*** 响应状态码 & 响应信息映射*/SUCCESS(200, "成功!"),ERROR(201, "失败!"),SERVER_INTERNAL_ERROR(500, "服务器内部错误,请联系管理员!"),PARAMETER_VALIDATE_FAILED_ERROR(10001, "参数校验失败,请联系管理员!"),BUSINESS_ERROR(10002, "业务异常,请联系管理员"),// =================== Spring Cloud Alibaba Sentinel统一异常处理 ===================SENTINEL_FLOW_EXCEPTION(20001,"接口被限流,请联系管理员!"),SENTINEL_DEGRADE_EXCEPTION(20002,"接口被降级,请联系管理员!"),SENTINEL_PARAM_FLOW_EXCEPTION(20003,"热点参数限流,请联系管理员!"),SENTINEL_SYSTEM_BLOCK_EXCEPTION(20004,"触发系统保护规则,请联系管理员!"),SENTINEL_AUTHORITY_EXCEPTION(20005,"授权规则不通过,请联系管理员!"),// =================== Spring Security统一异常处理 ===================HTTP_UNAUTHORIZED_ERROR(401, "尚未登录,请登录!"),HTTP_FORBIDDEN_ERROR(403, "权限不足,请联系管理员!"),;/*** 响应状态码*/private Integer code;/*** 响应信息*/private String message;}

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

如若内容造成侵权/违法违规/事实不符,请联系多彩编程网进行投诉反馈email:809451989@qq.com,一经查实,立即删除!

相关文章

HTML---CSS-引入样式表和选择器

CSS : Cascading Style Sheet 层叠式样式表 HTML 用于控制网页的结构&#xff0c;CSS则用于控制网页的外观&#xff0c;想要做出美观好看的网页&#xff0c;CSS是必须的 引入外部样式表&#xff1a; 它的属性 rel 和 type是固定的 语法&#xff1a; <link rel"styles…

16 SysTick—系统定时器

文章目录 16.0 前言16.1 SysTick 简介16.2 SysTick 寄存器介绍16.2.1 CTRL 控制及状态寄存器16.2.2 RELOAD 重载数值寄存器16.2.3 Current当前数值寄存器16.2.4 CALRB 校准值寄存器16.3 SysTick 定时实验16.3.1 编程要点16.3.2 代码分析16.3.2.1 SysTick 配置库函数16.3.2.2 配…

音频编辑软件:Studio One 6 中文

Studio One 6是一款功能强大的数字音乐制作软件&#xff0c;为用户提供一站式音乐制作解决方案。它具有直观的界面和强大的音频录制、编辑、混音和制作功能&#xff0c;支持虚拟乐器、效果器和第三方插件&#xff0c;可帮助用户实现高质量的音乐创作和制作。同时&#xff0c;St…

JavaScrip实现一个睡眠函数

说在前面 &#x1f388;在 Java 和 Python 中&#xff0c;有专门用于睡眠的函数&#xff0c;分别是 Thread.sleep() 和 time.sleep()。那么JavaScrip能不能也实现一个呢&#xff1f; 题目描述 请你编写一个异步函数&#xff0c;它接收一个正整数参数 millis &#xff0c;并休眠…

LVS 内置器件

以下是calibre lvs中内置器件的名称 Built_in_typeComponent Name描述NMOSMNCMOS N型晶体管PMOSMPCMOS P型晶体管ENH or ENHANCEMENTMENMOS增强型晶体管DEPL or DEPLETIONMDNMOS耗尽型晶体管MOSMMOS通用晶体管LDDNMOSLDDNCMOS轻掺杂漏极N型晶体管LDDPMOSLDDPCMOS轻掺杂漏极P型…

Java基础之虚拟机

1、前言 本篇基于网络整理&#xff0c;和自己编辑。在不断的完善补充哦。 2、什么是虚拟机&#xff1f; Java 虚拟机&#xff0c;是一个可以执行 Java 字节码的虚拟机进程。Java 源文件被编译成能被 Java 虚拟机执行的字节码文件( .class )。 Java 被设计成允许应用程序可以运…

格密码基础:SIS问题的定义与理解

目录 一. 介绍 二. SIS问题定义 2.1 直观理解 2.2 数学定义 2.3 基本性质 三. SIS与q-ary格 四. SIS问题的推广 五. Hermite标准型 六. 小结 一. 介绍 short interger solution problem短整数解问题&#xff0c;简称SIS问题。 1996年&#xff0c;Ajtai首次提出SIS问…

【数据结构】排序算法

&#x1f984;个人主页:修修修也 &#x1f38f;所属专栏:数据结构 ⚙️操作环境:Visual Studio 2022 目录 &#x1f38f;排序的定义 &#x1f38f;排序的稳定性 &#x1f4cc;稳定性的定义 &#x1f4cc;稳定性的意义 &#x1f38f;内排序与外排序 &#x1f38f;八大内排…

GitHub图床搭建

1 准备Github账号 如果没有Github账号需要先在官网注册一个账号 2 创建仓库 在github上创建一个仓库&#xff0c;随便一个普通的仓库就行&#xff0c;选择公共仓库 3 github token获取 github token创建方式可以参考下面的方式&#xff1a; https://www.xichangyou.com/6…

c/c++中static的用法

概述 static&#xff1a; 作为c/c的关键字之一&#xff0c;具有多种含义和应用&#xff0c;static 关键字可用于声明变量、函数、类数据成员和类函数。默认情况下&#xff0c;在所有块的外部定义的对象或变量具有静态持续时间和外部链接。 静态持续时间意味着&#xff0c;在程…

MT1138-MT1150总结

1. 判断闰年方法 year%40&&year%400&#xff01;0||year%4000 #include<bits/stdc.h> using namespace std;int day(int year,int mouth){if(mouth1||mouth3||mouth5||mouth7||mouth8||mouth10||mouth12){return 31;}else if(mouth4||mouth6||mouth9||mouth11)…

Golang 三数之和 leetcode15 双指针法

三数之和 leetcode15 知识补充&#xff1a; map的key值必须是可以比较运算的类型&#xff0c;不可以是函数、map、slice map记录 失败&#xff01;超出限制 //得到结果后再去重 失败&#xff01; func threeSum(nums []int) [][]int {L : len(nums)var intT stringresult : […

python使用贪心算法求最大整数问题

对于使用贪心算法的一个比较经典的问题&#xff0c;主要是为了解决最大整数的拼接问题&#xff0c;如果给定一个列表&#xff0c;这个列表中所包括的是一些非负整数&#xff0c;如果对这些整数进行组合&#xff0c;怎样才能组合出一个最大的整数&#xff0c;这里要注意一个问题…

1.2MATLAB数据类型和常用函数

MATLAB数据类型 数据类型表示范围整型 无符号整数8位无符号整数00000000~11111111 &#xff08;0~-1&#xff09;16位无符号整数32位无符号整数64位无符号整数带符号整数8位带符号整数10000000~01111111 (~)最左边的1表示符号负号16位带符号整数32位带符号整数64位带符号整数浮…

解决No module named ’torch._six‘问题

如果是 deepspeed &#xff0c;解决方法&#xff1a; deepspeed 安装 Windows deepspeed 安装 Windows-CSDN博客

【C++】内联函数

前言 在C语言中&#xff0c;我们学习过宏的用法。宏通常被用于进行简单的文本替换来执行一系列的操作&#xff0c;比如一些简单的运算。使用宏可以避免函数调用时建立栈帧的开销&#xff0c;提高程序的性能。我们首先来写一个实现加法功能的宏&#xff1a; #define ADD(x, y)…

【我的RUST库】get_local_info 0.2.2发布

0.2.2增加在cargo上的github链接&#xff0c;地址&#xff1a; get_local_info - crates.io: Rust Package Registry

物理学如何推动生成式 AI 的发展

一、说明 许多尖端的生成式 AI 模型都受到物理学概念的启发。在本指南中&#xff0c;我们将从高层次上了解物理学如何推动人工智能的进步。不同的领域经常交叉授粉重要概念&#xff0c;这有助于推动其进步。数学概念为物理学的进步奠定了基础;物理学中的概念经常启发经济学的框…

紫外加速老化试热冲击试验箱

紫外加速老化试热冲击试验箱是用于测试产品在高低温环境下的适应性以及性能表现的实验设备。其功能特点主要包括以下几个方面&#xff1a; 1. 温度控制&#xff1a;冷热冲击试验箱能够提供高温、低温以及常温的测试环境&#xff0c;并且可以快速地实现温度的转换和控制。这使得…

高效办公:如何通过在文件名称右边添加关键字提升工作效率

在繁忙的办公环境中&#xff0c;经常要处理大量的文件和资料。那如何管理和查找这些文件呢&#xff0c;常见的方法有在文件名称右边添加关键字。下面来看云炫文件管理器如何通过在文件名称右边添加关键字来提升工作效率。 在文件名称右边添加关键字前后效果图。 文件名批量添加…