SpringSecurity高级用法

SpringSecurity的高级用法,包括自定义loginUrl携带参数,自定义认证校验逻辑,自定义权限校验逻辑。 示例项目 https://github.com/qihaiyan/springcamp/tree/master/spring-advanced-security

一、概述

在项目实际开发过程中,SpringSecurity默认的认证和权限校验逻辑不能实现很高的业务复杂度,这种情况下我们需要自定义这些逻辑,包括自定义loginUrl携带参数,自定义认证校验逻辑,自定义权限校验逻辑。

二、自定义loginUrl携带参数

SpringSecurity在跳转login页面时,虽然可以指定login的url,但是无法让url中携带动态参数,不如跳转到login?param=foo,其中foo需要根据特定条件动态变化,要实现这种效果,我们需要通过exceptionHandling指定自定义LoginUrlAuthenticationEntryPoint。

public class CustomLoginUrlAuthenticationEntryPoint extends LoginUrlAuthenticationEntryPoint {private final RedirectStrategy redirectStrategy = new DefaultRedirectStrategy();public CustomLoginUrlAuthenticationEntryPoint(String loginFormUrl) {super(loginFormUrl);}@Overridepublic void commence(HttpServletRequest request, HttpServletResponse response, AuthenticationException authException)throws IOException, ServletException {if (!super.isUseForward()) {String redirectUrl = this.buildRedirectUrlToLoginPage(request, response, authException);// change login urlredirectUrl = redirectUrl + "?param=test";this.redirectStrategy.sendRedirect(request, response, redirectUrl);} else {String redirectUrl = null;if (super.isForceHttps() && "http".equals(request.getScheme())) {redirectUrl = this.buildHttpsRedirectUrlForRequest(request);}if (redirectUrl != null) {this.redirectStrategy.sendRedirect(request, response, redirectUrl);} else {String loginForm = this.determineUrlToUseForThisRequest(request, response, authException);RequestDispatcher dispatcher = request.getRequestDispatcher(loginForm);dispatcher.forward(request, response);}}}
}

以上代码自定义CustomLoginUrlAuthenticationEntryPoint,在commence方法中我们可以按照业务需要实现自己的跳转逻辑,通过修改redirectUrl实现。

在SpringSecurity配置中通过exceptionHandling引用CustomLoginUrlAuthenticationEntryPoint:

exceptionHandling(customizer ->customizer.authenticationEntryPoint(new CustomLoginUrlAuthenticationEntryPoint("/login")))

三、自定义认证校验逻辑

SpringSecurity默认的认证逻辑是校验用户名密码是否合法,如果想增加其它的校验逻辑,需要实现AuthenticationProvider,然后在authenticationManager中指定我们自己实现的AuthenticationProvider。

public class CustomAuthenticationProvider extends DaoAuthenticationProvider {@Autowiredprivate CustomUserDetailsService customUserDetailsService;@PostConstructpublic void init() {this.setUserDetailsService(customUserDetailsService);}@Overrideprotected void additionalAuthenticationChecks(UserDetails userDetails, UsernamePasswordAuthenticationToken authentication) {super.additionalAuthenticationChecks(userDetails, authentication);HttpServletRequest req = ((ServletRequestAttributes) RequestContextHolder.getRequestAttributes()).getRequest();String username = userDetails.getUsername();// 自定义认证校验逻辑if (username.equals("need approval")) {log.info("invalid request is: {}", req);throw new AuthenticationServiceException("Your account is pending approval for access");}}
}

在上面自定义的CustomAuthenticationProvider中,通过重写additionalAuthenticationChecks方法进行自定义认证逻辑的实现。

然后在authenticationManager中指定CustomAuthenticationProvider:

@Bean
public AuthenticationManager authenticationManager() {return new ProviderManager(customAuthenticationProvider);
}

四、自定义权限校验逻辑

SpringSecurity可以通过在配置中通过requestMatchers指定较为灵活的权限校验策略,但是缺少一些动态特性,比如对 /foo/{param} 这种rest风格的带变量的url就处理不了,
这种情况我们可以通过自定义AuthorizationManager来实现,然后在requestMatchers中通过access方法来指定我们自定义的AuthorizationManager。

public class MyRequestAuthorizationManager implements AuthorizationManager<RequestAuthorizationContext> {private final SecurityExpressionHandler<RequestAuthorizationContext> expressionHandler = new DefaultHttpSecurityExpressionHandler();public MyRequestAuthorizationManager() {}// 自定义授权校验逻辑@Overridepublic AuthorizationDecision check(Supplier<Authentication> authentication, RequestAuthorizationContext context) {EvaluationContext ctx = this.expressionHandler.createEvaluationContext(authentication, context);String checkParam = Optional.ofNullable(ctx.lookupVariable("param")).map(String::valueOf).orElse(null);// the '/public' url doesn't need authenticationif (checkParam != null && (checkParam.equals("public"))) {return new AuthorizationDecision(true);}return new AuthorizationDecision(!ObjectUtils.isEmpty(authentication.get().getCredentials()));}
}

在MyRequestAuthorizationManager中通过重写check方法来实现自定义权限校验,rest风格的带变量的url中的变量,可以通过EvaluationContext的lookupVariable方法获取变量值。

指定自定义AuthorizationManager:

MyRequestAuthorizationManager myRequestAuthorizationManager = new MyRequestAuthorizationManager();
http.authorizeHttpRequests(authorize -> authorize.requestMatchers("/{param}").access(myRequestAuthorizationManager))

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

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

相关文章

(2024|Nature Medicine,生物医学 AI,BiomedGPT)面向多种生物医学任务的通用视觉-语言基础模型

BiomedGPT: A generalist vision–language foundation model for diverse biomedical tasks 目录 1. 摘要 2. 引言 3. 相关研究 3.1 基础模型与通用生物医学 AI 3.2 生物医学 AI 的局限性 3.3 BiomedGPT 的创新点 4. 方法 4.1 架构及表示 4.1.1 模型架构选择 4.1.2 …

使用PyCharm进行Django项目开发环境搭建

如果在PyCharm中创建Django项目 1. 打开PyCharm&#xff0c;选择新建项目 2.左侧选择Django&#xff0c;并设置项目名称 3.查看项目解释器初始配置 4.新建应用程序 执行以下操作之一&#xff1a; 转到工具| 运行manage.py任务或按CtrlAltR 在打开的manage.pystartapp控制台…

AD域控粗略了解

一、前提 转眼大四&#xff0c;目前已入职上饶一公司从事运维工程师&#xff0c;这与我之前干的开发有着很大的差异&#xff0c;也学习到了许多新的知识。今天就写下我对于运维工作中常用的功能——域控的理解。 二、为什么要有域控&#xff0c;即域控的作用 首先我们必须要…

Linux(21)——系统日志

目录 一、系统日志架构&#xff1a; 1、系统日志&#xff1a; 2、日志文件类型&#xff1a; 二、查看 syslog 文件&#xff1a; 1、将事件记录到系统&#xff1a; &#xff08;1&#xff09;syslog 设备&#xff1a; &#xff08;2&#xff09;syslog 优先级&#xff1a…

学习数据结构(6)单链表OJ上

1.移除链表元素 解法一&#xff1a;&#xff08;我的做法&#xff09;在遍历的同时移除&#xff0c;代码写法比较复杂 解法二&#xff1a;创建新的链表&#xff0c;遍历原链表&#xff0c;将非val的节点尾插到新链表&#xff0c;注意&#xff0c;如果原链表结尾是val节点需要将…

第433场周赛:变长子数组求和、最多 K 个元素的子序列的最值之和、粉刷房子 Ⅳ、最多 K 个元素的子数组的最值之和

Q1、变长子数组求和 1、题目描述 给你一个长度为 n 的整数数组 nums 。对于 每个 下标 i&#xff08;0 < i < n&#xff09;&#xff0c;定义对应的子数组 nums[start ... i]&#xff08;start max(0, i - nums[i])&#xff09;。 返回为数组中每个下标定义的子数组中…

CSS 伪类(Pseudo-classes)的详细介绍

CSS 伪类详解与示例 在日常的前端开发中&#xff0c;CSS 伪类可以帮助我们非常精准地选择元素或其特定状态&#xff0c;从而达到丰富页面表现的目的。本文将详细介绍以下伪类的使用&#xff1a; 表单相关伪类 :checked、:disabled、:enabled、:in-range、:invalid、:optional、…

Centos挂载镜像制作本地yum源,并补装图形界面

内网环境centos7.9安装图形页面内网环境制作本地yum源 上传镜像到服务器目录 创建目录并挂载镜像 #创建目录 cd /mnt/ mkdir iso#挂载 mount -o loop ./CentOS-7-x86_64-DVD-2009.iso ./iso #前面镜像所在目录&#xff0c;后面所挂载得目录#检查 [rootlocalhost mnt]# df -h…

大模型推理——MLA实现方案

1.整体流程 先上一张图来整体理解下MLA的计算过程 2.实现代码 import math import torch import torch.nn as nn# rms归一化 class RMSNorm(nn.Module):""""""def __init__(self, hidden_size, eps1e-6):super().__init__()self.weight nn.Pa…

Python截图轻量化工具

一、兼容局限性 这是用Python做的截图工具&#xff0c;不过由于使用了ctypes调用了Windows的API, 同时访问了Windows中"C:/Windows/Cursors/"中的.cur光标样式文件, 这个工具只适用于Windows环境&#xff1b; 如果要提升其跨平台性的话&#xff0c;需要考虑替换cty…

链表(LinkedList) 1

上期内容我们讲述了顺序表&#xff0c;知道了顺序表的底层是一段连续的空间进行存储(数组)&#xff0c;在插入元素或者删除元素需要将顺序表中的元素整体移动&#xff0c;时间复杂度是O(n)&#xff0c;效率比较低。因此&#xff0c;在Java的集合结构中又引入了链表来解决这一问…

SpringAI系列 - 使用LangGPT编写高质量的Prompt

目录 一、LangGPT —— 人人都可编写高质量 Prompt二、快速上手2.1 诗人 三、Role 模板3.1 Role 模板3.2 Role 模板使用步骤3.3 更多例子 四、高级用法4.1 变量4.2 命令4.3 Reminder4.4 条件语句4.5 Json or Yaml 方便程序开发 一、LangGPT —— 人人都可编写高质量 Prompt La…

jupyterLab插件开发

jupyter lab安装、配置&#xff1a; jupyter lab安装、配置教程_容器里装jupyterlab-CSDN博客 『Linux笔记』服务器搭建神器JupyterLab_linux_布衣小张-腾讯云开发者社区 Jupyter Lab | 安装、配置、插件推荐、多用户使用教程-腾讯云开发者社区-腾讯云 jupyterLab插件开发教…

使用LLaMA Factory踩坑记录

前置条件&#xff1a;电脑显卡RTX 4080 问题&#xff1a;LLaMA-Factory在运行的时候&#xff0c;弹出未检测到CUDA的报错信息 结论&#xff1a;出现了以上的报错&#xff0c;主要可以归结于以下两个方面&#xff1a; 1、没有安装GPU版本的pytorch&#xff0c;下载的是CPU版本…

『Apisix进阶篇』结合Consul作服务发现实战演练

文章目录 一、引言二、APISIX与Consul集成2.1 环境准备2.2 配置Consul服务发现2.2.1 修改APISIX配置文件2.2.2 重启APISIX 2.3 在路由中使用Consul服务发现2.3.1 创建路由2.3.2 验证路由 2.4 高级配置2.4.1 服务过滤2.4.2 多数据中心支持 三、总结 &#x1f4e3;读完这篇文章里…

SpringBoot速成(八)登录实战:未登录不能访问 P5-P8

1.登录 package com.itheima.springbootconfigfile.controller;import com.itheima.springbootconfigfile.pojo.Result; import com.itheima.springbootconfigfile.pojo.User; import com.itheima.springbootconfigfile.service.UserService;import com.itheima.springbootco…

对接DeepSeek

其实&#xff0c;整个对接过程很简单&#xff0c;就四步&#xff0c;获取key&#xff0c;找到接口文档&#xff0c;接口测试&#xff0c;代码对接。 获取 KEY https://platform.deepseek.com/transactions 直接付款就是了&#xff08;现在官网暂停充值2025年2月7日&#xff0…

ASP.NET Core JWT

目录 Session的缺点 JWT&#xff08;Json Web Token&#xff09; 优点&#xff1a; 登录流程 JWT的基本使用 生成JWT 解码JWT 用JwtSecurityTokenHandler对JWT解码 注意 Session的缺点 对于分布式集群环境&#xff0c;Session数据保存在服务器内存中就不合适了&#…

【MySQL】深度学习数据库开发技术:使用CC++语言访问数据库

**前言&#xff1a;**本节内容介绍使用C/C访问数据库&#xff0c; 包括对数据库的增删查改操作。 主要是学习一些接口的调用&#xff0c; 废话不多说&#xff0c; 开始我们的学习吧&#xff01; ps:本节内容比较容易&#xff0c; 友友们放心观看哦&#xff01; 目录 准备mysql…

postgreSQL16.6源码安装

1.获取源码 从PostgreSQL: File Browser获取tar.bz2或者tar.gz源码 2.解压 tar xf postgresql-version.tar.bz2 roothwz-VMware-Virtual-Platform:/usr/local# tar xf postgresql-16.6.tar.bz2 roothwz-VMware-Virtual-Platform:/usr/local# ll 总计 24324 drwxr-xr-x 12 ro…