spring security 多认证方式的配置,自定义认证方式

本文介绍了在Spring Security框架下,如何在已有账号密码登录基础上,新增JWT(JSON Web Token)认证方式来实现单点登录。通过实现JWTAuthenticationProcessingFilter、JWTAuthenticationProvider和JWTAuthenticationToken三个类,并配置到Spring Security中,成功实现了点击链接直接登录的功能。同时,文章解释了Spring Security的验证工作流程,包括Filter、AuthenticationManager和AuthenticationProvider的角色。后续计划通过获取Header中的JWT串,进一步完善登录逻辑。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

背景: 项目中已经有了登录界面,通过账号密码登录的方式登录系统,之前别人搞的, 

新需求: 需要与其他系统集成,相当于单点登录,也不需要去认证服务器验证,默认认为他们传过来的就是正确的(话说这样真的挺危险的), 经过讨论,加一点加密措施,使用了 JWT进行加密传输, 所以需要在保留现有登录界面登录方式的基础上, 添加新的登录方式,点击链接直接登录(链接中带上加密后的JWT串)

过程: 接到了需求后,就去网上搜了一遍, 毕竟面向百度编程时代, 看了看怎么集成, 帖子也不少,写的比较好的如下

https://blog.csdn.net/qq_36521507/article/details/103365805

https://blog.csdn.net/qq_36521507/article/details/103370070

照着上面的文章,抄了一下,写了三个类

JWTAuthenticationProcessingFilter
JWTAuthenticationProvider
JWTAuthenticationToken

import org.springframework.security.authentication.AuthenticationServiceException;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.AuthenticationException;
import org.springframework.security.web.authentication.AbstractAuthenticationProcessingFilter;
import org.springframework.security.web.util.matcher.AntPathRequestMatcher;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;

public class JWTAuthenticationProcessingFilter extends AbstractAuthenticationProcessingFilter {


    public static final String SPRING_SECURITY_FORM_USERNAME_KEY = "username";
    public static final String SPRING_SECURITY_FORM_PASSWORD_KEY = "password";

    private String usernameParameter = SPRING_SECURITY_FORM_USERNAME_KEY;
    private String passwordParameter = SPRING_SECURITY_FORM_PASSWORD_KEY;
    private boolean postOnly = false;


    public JWTAuthenticationProcessingFilter() {
         super(new AntPathRequestMatcher("/jwtLogin", "GET"));
     }

    @Override
    public Authentication attemptAuthentication(HttpServletRequest request, HttpServletResponse response)
        throws AuthenticationException, IOException, ServletException {
        if (postOnly && !request.getMethod().equals("POST")) {
            throw new AuthenticationServiceException(
                    "Authentication method not supported111: " + request.getMethod());
        }

//        String username = obtainUsername(request);
//        Stri
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值