【问题标题】:JWT Interceptor SpringbootJWT 拦截器 Springboot
【发布时间】:2021-06-01 14:22:50
【问题描述】:

我想让持有 JWT 的人可以访问所有 API,但现在只能通过 EXCLUDE PATH 访问。我应该为此设置什么?

这是我的 WebConfig。

private static final String[] EXCLUDE_PATHS = {
            "/api/user/**"
    };
    

public void addInterceptors(InterceptorRegistry registry){
        registry.addInterceptor(jwtInterceptor)
                .addPathPatterns("/**")
                .excludePathPatterns(EXCLUDE_PATHS);

这是我的拦截器。

public class JwtInterceptor implements HandlerInterceptor {

    private static final String HEADER_AUTH = "Authorization";

    private final JwtTokenProvider jwtTokenProvider;

    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {

        final String token = request.getHeader(HEADER_AUTH);

        if(token !=null && jwtTokenProvider.validateToken(token)){
            return true;
        }else{
            throw new UnauthorizedException();
        }

这是我的 validateToken fn

public boolean validateToken(String jwtToken) {
        try {
            Jws<Claims> claims = Jwts.parser().setSigningKey(secretKey).parseClaimsJws(jwtToken);
            return !claims.getBody().getExpiration().before(new Date());
        } catch (Exception e) {
            return false;
        }
    }

这是我的过滤器

public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain) throws IOException, ServletException {

        String token = jwtTokenProvider.resolveToken((HttpServletRequest) request);

        if (token != null && jwtTokenProvider.validateToken(token)) {

            Authentication authentication = jwtTokenProvider.getAuthentication(token);

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

这是我的安全配置。

protected void configure(HttpSecurity http) throws Exception {


        http
                .httpBasic().disable()
                .csrf()
                .ignoringAntMatchers("/h2-console/**")
                .disable()
                .sessionManagement().sessionCreationPolicy(SessionCreationPolicy.STATELESS)
                .and()
                .authorizeRequests()
                .antMatchers("/admin/**").hasRole("ADMIN")
                .antMatchers("/h2-console/**").permitAll()
                .antMatchers("/user/**").hasRole("USER")
                .anyRequest().permitAll()
                .and()
                .addFilterBefore(new JwtAuthenticationFilter(jwtTokenProvider),
                        UsernamePasswordAuthenticationFilter.class);


    }

我错过了什么吗?我添加了安全配置。

【问题讨论】:

    标签: spring-boot jwt


    【解决方案1】:

    您应该使用 WebSecurity 而不是拦截器。

    类似这样的东西用于配置哪些路径可以访问,哪些不能访问

    @Override
    protected void configure(HttpSecurity http) throws Exception {
        http.cors().and().authorizeRequests()
                .antMatchers(HttpMethod.POST, SIGN_UP_URL).permitAll()
                .anyRequest().authenticated()
                .and()
                .addFilter(new JWTAuthenticationFilter(authenticationManager()))
                .addFilter(new JWTAuthorizationFilter(authenticationManager()))
                // this disables session creation on Spring Security
                .sessionManagement().sessionCreationPolicy(SessionCreationPolicy.STATELESS);
    }
    

    这个link应该能帮到你。

    【讨论】:

    • 嗨。我添加了我的 WebSecurityConfig。有错吗?
    猜你喜欢
    • 1970-01-01
    • 2021-05-17
    • 2017-12-31
    • 2017-12-26
    • 2018-06-12
    • 2023-02-06
    • 1970-01-01
    • 2015-11-22
    • 2014-03-10
    相关资源
    最近更新 更多