不使用UsernamePasswordAuthenticationToken进行Spring Security JWT验证
创始人
2024-12-29 12:30:37
0

要在Spring Security中实现JWT验证,可以创建一个自定义的过滤器来处理JWT的验证和授权逻辑,而不需要使用UsernamePasswordAuthenticationToken。

以下是一个示例代码,演示如何实现JWT验证:

首先,创建一个名为JwtAuthenticationFilter的过滤器类:

import io.jsonwebtoken.Claims;
import io.jsonwebtoken.Jwts;
import io.jsonwebtoken.SignatureAlgorithm;
import org.springframework.security.authentication.AuthenticationManager;
import org.springframework.security.authentication.UsernamePasswordAuthenticationToken;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.GrantedAuthority;
import org.springframework.security.core.authority.SimpleGrantedAuthority;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.security.web.authentication.www.BasicAuthenticationFilter;

import javax.servlet.FilterChain;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.util.ArrayList;
import java.util.Collection;
import java.util.List;

public class JwtAuthenticationFilter extends BasicAuthenticationFilter {

    public JwtAuthenticationFilter(AuthenticationManager authenticationManager) {
        super(authenticationManager);
    }

    @Override
    protected void doFilterInternal(HttpServletRequest request, HttpServletResponse response, FilterChain chain) throws IOException, ServletException {
        String header = request.getHeader("Authorization");

        if (header == null || !header.startsWith("Bearer ")) {
            chain.doFilter(request, response);
            return;
        }

        Authentication authentication = getAuthentication(request);
        SecurityContextHolder.getContext().setAuthentication(authentication);
        chain.doFilter(request, response);
    }

    private Authentication getAuthentication(HttpServletRequest request) {
        String token = request.getHeader("Authorization");
        if (token != null) {
            // 解析并验证Token
            Claims claims = Jwts.parser()
                    .setSigningKey("your-secret-key")
                    .parseClaimsJws(token.replace("Bearer ", ""))
                    .getBody();

            String username = claims.getSubject();
            List roles = (List) claims.get("roles");

            Collection authorities = new ArrayList<>();
            for (String role : roles) {
                authorities.add(new SimpleGrantedAuthority(role));
            }

            if (username != null) {
                return new UsernamePasswordAuthenticationToken(username, null, authorities);
            }
            return null;
        }
        return null;
    }
}

然后,在你的Spring Security配置类中使用该过滤器:

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.security.authentication.AuthenticationManager;
import org.springframework.security.config.annotation.authentication.builders.AuthenticationManagerBuilder;
import org.springframework.security.config.annotation.method.configuration.EnableGlobalMethodSecurity;
import org.springframework.security.config.annotation.web.builders.HttpSecurity;
import org.springframework.security.config.annotation.web.builders.WebSecurity;
import org.springframework.security.config.annotation.web.configuration.EnableWebSecurity;
import org.springframework.security.config.annotation.web.configuration.WebSecurityConfigurerAdapter;
import org.springframework.security.config.http.SessionCreationPolicy;
import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder;
import org.springframework.security.crypto.password.PasswordEncoder;
import org.springframework.security.web.authentication.UsernamePasswordAuthenticationFilter;

@Configuration
@EnableWebSecurity
@EnableGlobalMethodSecurity(prePostEnabled = true)
public class SecurityConfig extends WebSecurityConfigurerAdapter {

    @Autowired
    private JwtAuthenticationEntryPoint jwtAuthenticationEntryPoint;

    @Autowired
    private JwtAuthenticationFilter jwtAuthenticationFilter;

    @Autowired
    public void configureGlobal(AuthenticationManagerBuilder authenticationManagerBuilder) throws Exception {
        authenticationManagerBuilder
                .userDetailsService(userDetailsService)
                .passwordEncoder(passwordEncoder());
    }

    @Bean
    public PasswordEncoder passwordEncoder() {
        return new BCryptPasswordEncoder();
    }

    @Bean
    @Override
    public AuthenticationManager authenticationManagerBean() throws Exception {
        return super.authenticationManagerBean();
    }

    @Override
    protected void configure(HttpSecurity httpSecurity) throws Exception {
        httpSecurity
                .cors()
                .and()
                .csrf()
                .disable()
                .exceptionHandling()
                .authenticationEntryPoint(jwtAuthenticationEntryPoint)
                .and()
                .sessionManagement()
                .sessionCreationPolicy(SessionCreationPolicy.STATELESS)
                .and()
                .authorizeRequests()
                .antMatchers("/api/auth/**")
                .permitAll()
                .anyRequest()
                .authenticated();

        // 添加JWT过滤器
        httpSecurity.addFilterBefore(jwtAuthenticationFilter, UsernamePasswordAuthenticationFilter.class);
    }

    @Override
    public void configure(WebSecurity web) throws Exception {
        web.ignoring()
                .antMatchers("/h2-console/**");
    }
}

这样,当请求到达时,JwtAuthenticationFilter将会拦截并验证JWT,如果验证通过,将会设置相关的权限信息到SecurityContextHolder中,从而实

相关内容

热门资讯

透视数据!wpk透视插件,wp... 透视数据!wpk透视插件,wpk透视辅助靠谱吗,介绍教程(有挂解说);1、操作简单,无需注册,只需要...
透视玄学!hhpoker有没有... 透视玄学!hhpoker有没有辅助,hhpoker视频巡查真的假的,大神讲解(有挂详情);1、hhp...
透视实锤!wpk透视是真的假的... 透视实锤!wpk透视是真的假的,wpk插件辅助,解密教程(有挂解密)小薇(透视辅助)致您一封信;亲爱...
透视脚本!HH平台挂,hhpo... 透视脚本!HH平台挂,hhpoker为什么一直输,技巧教程(有挂解说)1、金币登录送、破产送、升级送...
透视脚本!wpk透视怎么安装,... 透视脚本!wpk透视怎么安装,wpk透视辅助下载,科技教程(有挂方法)1)wpk透视辅助下载辅助挂:...
透视挂!wpk辅助器是真的吗,... 透视挂!wpk辅助器是真的吗,wpk透视辅助下载,软件教程(有挂细节)wpk辅助器是真的吗是一种具有...
透视好牌!wpk真吗,wpk模... 透视好牌!wpk真吗,wpk模拟器,可靠技巧(有挂方法)1、完成wpk模拟器透视辅助安装,帮助玩家取...
透视ai!hhpoker是内部... 透视ai!hhpoker是内部控制吗,hhpoker有没有辅助,教你攻略(有挂插件)hhpoker是...
透视工具!wpk辅助器是真的吗... 透视工具!wpk辅助器是真的吗,wpk可以作弊吗,新2025版(有挂教程);1、每一步都需要思考,不...
透视好牌!wpk透视怎么安装,... 透视好牌!wpk透视怎么安装,wpk软件是正规的吗,切实教程(有挂详情)一、wpk软件是正规的吗软件...