Spring Security自定义登录接口处理JSON请求体

server/2024/10/17 19:45:31/

Spring Security自定义登录接口处理JSON请求体

  • 一、Spring Security自定义登录接口处理JSON请求体
    • 1. 创建自定义登录控制器
    • 2. 创建LoginRequest类
    • 3. 配置Spring Security


一、Spring Security自定义登录接口处理JSON请求体

在Spring Security中,默认情况下,表单登录是通过/login路径处理的,并且默认的登录表单会通过POST方法提交到/login路径。然而,你的前端将用户名和密码放到请求体中,而不是表单数据中。因此,你需要自定义一个登录接口来处理这种情况。

1. 创建自定义登录控制器

首先,你需要创建一个自定义的登录控制器来处理JSON请求体。以下是一个示例:

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.ResponseEntity;
import org.springframework.security.authentication.AuthenticationManager;
import org.springframework.security.authentication.UsernamePasswordAuthenticationToken;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.AuthenticationException;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RestController;@RestController
public class CustomLoginController {@Autowiredprivate AuthenticationManager authenticationManager;@Autowiredprivate UserDetailsService userDetailsService;@PostMapping("/system/user/login")public ResponseEntity<?> login(@RequestBody LoginRequest loginRequest) {try {// 创建一个基于用户名和密码的认证令牌Authentication authentication = authenticationManager.authenticate(new UsernamePasswordAuthenticationToken(loginRequest.getUsername(), loginRequest.getPassword()));// 将认证信息存储到安全上下文中SecurityContextHolder.getContext().setAuthentication(authentication);// 获取认证后的用户信息UserDetails userDetails = userDetailsService.loadUserByUsername(loginRequest.getUsername());// 这里可以生成 JWT 或其他形式的令牌,并返回给前端// 例如:String token = jwtTokenUtil.generateToken(userDetails);// 返回成功响应return ResponseEntity.ok("登录成功");} catch (AuthenticationException e) {// 返回登录失败响应return ResponseEntity.status(401).body("登录失败: " + e.getMessage());}}
}

2. 创建LoginRequest类

接下来,你需要创建一个LoginRequest类来接收请求体中的JSON数据:

public class LoginRequest {private String username;private String password;// Getters and Setters
}

3. 配置Spring Security

最后,你需要配置Spring Security以允许自定义登录接口。在你的configure(HttpSecurity http)方法中,确保你已经配置了自定义的登录接口,并且禁用了默认的表单登录:

@Override
protected void configure(HttpSecurity http) throws Exception {// 禁用框架的 X-Frame-Options 响应头,以允许页面在 iframe 中显示http.headers().frameOptions().disable();// 配置异常处理器http.exceptionHandling().accessDeniedHandler(customerRestAccessDeniedHandler) // 访问被拒绝时的处理类.authenticationEntryPoint(customerAuthenticationEntryPoint); // 未认证时的处理类// 添加 JWT 过滤器http.addFilterBefore(customerJwtAuthenticationTokenFilter, UsernamePasswordAuthenticationFilter.class);// 配置请求授权http.authorizeRequests().withObjectPostProcessor(new ObjectPostProcessor<FilterSecurityInterceptor>() {@Overridepublic <O extends FilterSecurityInterceptor> O postProcess(O o) {o.setAccessDecisionManager(accessDecisionManager); // 设置访问决策管理器o.setSecurityMetadataSource(securityMetadataSource); // 设置安全元数据源return o;}}).antMatchers("/ignore/**", "/system/user/login").permitAll() // 这些路径不需要权限校验.anyRequest().authenticated() // 其他请求需要认证.and().sessionManagement().sessionCreationPolicy(SessionCreationPolicy.STATELESS) // 使用无状态的会话管理.and().logout() // 配置登出.logoutUrl("/system/user/logout").logoutSuccessHandler(customerLogoutSuccessHandler) // 登出成功处理器.permitAll() // 登出放行.and().csrf().disable(); // 禁用 CSRF 保护(在使用 JWT 时通常可以禁用)// 禁用默认的表单登录http.formLogin().disable();
}

通过以上步骤,你可以自定义一个处理JSON请求体的登录接口,并确保Spring Security能够正确处理这种类型的登录请求。


http://www.ppmy.cn/server/132564.html

相关文章

Vue3+TypeScript+AntVX6实现Web组态(从技术层面与实现层面进行分析)内含实际案例教学

摘要 用Vue3TypeScriptAntVX6实现Web组态&#xff08;从技术层面与实现层面进行分析&#xff09;&#xff0c;包含画布创建、节点设计、拖拽实现&#xff08;实际案例&#xff09;、节点连线、交互功能&#xff0c;后续文章持续更新。 注&#xff1a;本文章可以根据目录进行导…

Golang Slice扩容机制及注意事项

Golang Slice扩容机制及注意事项&#xff1a; 在 Go语言中&#xff0c;Slice&#xff08;切片&#xff09;是一种非常灵活且强大的数据结构&#xff0c;它是对数组的抽象&#xff0c;提供了动态数组的功能。Slice 的扩容机制是自动的&#xff0c;但了解其背后的原理对于编写高…

Qt-系统QThread多线程介绍使用(62)

目录 描述 相关函数 使用 准备工作 重写run 发送信号 创建一个线程 启动线程 计时器运行流程 多线程运用场景 描述 qt多线程和Linux多线程类似 Linux有自己的一套多线程 API&#xff0c;Qt 也有着自己封装的多线程 API QT多线程参考了JAVA中的设计方式 QThread创建…

云服务器磁盘满了,清理docker无用缓存、容器等清理

docker system prune 命令用于清理 Docker 系统中的各种未使用资源。根据你提供的警告信息&#xff0c;这条命令将会移除以下内容&#xff1a; 所有已停止的容器&#xff08;all stopped containers&#xff09; 所有未被至少一个容器使用的网络&#xff08;all networks no…

AI赋能安全运营 | 赛宁网安深度参与四川省网络安全沙龙

为促进四川省、市网络安全公共服务领域的经验交流与深入探讨&#xff0c;打通网络安全供需上下游&#xff0c;加速汇聚省、市优质网络安全设备和服务资源&#xff0c;提升巴中市乃至四川省网络安全防护水平&#xff0c;共同推动四川省网络安全事业的蓬勃发展。 2024年10月15日…

Java【代码 19】含有换行符\r\n的字符串匹配(源码分享)处理Word文档里的Excel表格数据

含有换行符的字符串匹配 1.问题说明2.问题分析3.问题解决 1.问题说明 Java 后台读取包含 Excel 表格的 Word 文档&#xff0c;此时正文数据字符串包含 \r\n也就是换行符&#xff0c;想要通过 yaml 配置文件匹配 Excel 表格的表头&#xff0c;但是无论如何都是匹配不上&#xf…

CSS @规则(At-rules)系列详解___@font-face规则使用方法

CSS 规则(At-rules)系列详解 ___font-face规则使用方法 本文目录&#xff1a; 零、时光宝盒 一、CSSfont-face规则定义和用法 二、font-face语法 三、font-face使用方法例子 3.1、指定一种字体 3.2、font-face 里添加文本的描述符 3.3、设置多个 font-face 规则。 3.4…

第十五届蓝桥杯C/C++学B组(解)

1.握手问题 解题思路一 数学方法 50个人互相握手 &#xff08;491&#xff09;*49/2 &#xff0c;减去7个人没有互相握手&#xff08;61&#xff09;*6/2 答案&#xff1a;1024 解题思路二 思路&#xff1a; 模拟 将50个人从1到50标号&#xff0c;对于每两个人之间只握一…