不使用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中,从而实

相关内容

热门资讯

果真有挂开挂!开挂科技软件免费... 果真有挂开挂!开挂科技软件免费,赣牌圈的隐藏机制(科普开挂辅助工具)《详细加薇136704302咨询...
有挂方式辅助!长城互娱辅助,创... 有挂方式辅助!长城互娱辅助,创思维激k辅助器下载(玩家攻略推荐开挂辅助软件);亲,有的,ai轻松简单...
有挂分析辅助!wepoker俱... wepoker俱乐部开挂开挂教程视频分享装挂详细步骤在当今的网络游戏中,wepoker俱乐部开挂作为...
真的有挂开挂!新道游开挂视频,... 真的有挂开挂!新道游开挂视频,哥哥打大a游戏攻略(记者揭秘开挂辅助工具)哥哥打大a游戏攻略ai黑科技...
有挂存在开挂!闲聚大联盟辅助,... 您好:这款闲聚大联盟辅助游戏是可以开挂的,确实是有挂的,很多玩家在这款闲聚大联盟辅助游戏中打牌都会发...
有挂方略开挂!边锋透视器辅助器... 【亲,边锋透视器辅助器微信 这款游戏可以开挂的,确实是有挂的,很多玩家在这款边锋透视器辅助器微信中打...
有挂助手辅助!微友助手破解版,... 您好:这款微友助手破解版游戏是可以开挂的,确实是有挂的,很多玩家在这款微友助手破解版游戏中打牌都会发...
有挂方式辅助!九九山城插件程序... 较多好评“微乐万能挂官网”开挂(透视)辅助教程 了解更多开挂安装加(136704302)微信号是一款...
有挂技术开挂!孝感卡五星辅助,... 有挂技术开挂!孝感卡五星辅助,wepoker辅助器(一分钟带你了解开挂辅助安装)您好:孝感卡五星辅助...
有挂规律辅助!九九联盟辅助神器... 有挂规律辅助!九九联盟辅助神器,鸿狐拼十辅助(推荐一款开挂辅助脚本) 【无需打开直接搜索加薇1367...