身份验证过滤器上的 403 禁止错误

403 forbidden error on authentication filter

我正在使用 mysql 作为数据库进行基本 spring 启动 api 我为注册用户(“/ users”)创建了一个端点,它是 bcrypt 密码 登录时我创建了一个身份验证过滤器,它在响应的 header 中添加了 jwt 令牌 但是在访问端点(“/登录”)时我收到 403 错误, 我已经为名为“/login”的请求配置了蚂蚁匹配

**网络安全配置**

package com.mukul.app.mobileappws.security;

import com.mukul.app.mobileappws.security.FIlter.AuthenticationFilter;
import com.mukul.app.mobileappws.services.UserService;

import org.springframework.context.annotation.Configuration;
import org.springframework.http.HttpMethod;

import org.springframework.security.config.annotation.authentication.builders.AuthenticationManagerBuilder;
import org.springframework.security.config.annotation.web.builders.HttpSecurity;
import org.springframework.security.config.annotation.web.configuration.EnableWebSecurity;
import org.springframework.security.config.annotation.web.configuration.WebSecurityConfigurerAdapter;
import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder;

@Configuration
@EnableWebSecurity
public class ConfigurationSecurity extends WebSecurityConfigurerAdapter {
    UserService userService;
    BCryptPasswordEncoder bcrypt;

    ConfigurationSecurity(UserService u, BCryptPasswordEncoder b) {
        this.userService = u;
        this.bcrypt = b;
    }

    @Override
    protected void configure(HttpSecurity http) throws Exception {
        // http.authorizeRequests().antMatchers(HttpMethod.POST,
        // "/users").permitAll().anyRequest()
        // .authenticated();
        //
        AuthenticationFilter af = new AuthenticationFilter(authenticationManager());
       
        http.csrf().disable();
        http.authorizeRequests().antMatchers(HttpMethod.POST,
                "/users").permitAll();

        http.authorizeRequests().antMatchers("/login").permitAll();
        http.authorizeRequests().anyRequest()
                .authenticated();
        http.addFilter(af);

    }

    @Override
    protected void configure(AuthenticationManagerBuilder auth) throws Exception {
        auth.userDetailsService(userService).passwordEncoder(bcrypt);
    }

}

身份验证过滤器

package com.mukul.app.mobileappws.security.FIlter;

import java.io.IOException;
import java.util.Date;

import javax.servlet.FilterChain;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import com.mukul.app.mobileappws.security.SecurityConstants;

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.userdetails.User;
import org.springframework.security.web.authentication.UsernamePasswordAuthenticationFilter;

import io.jsonwebtoken.Jwts;
import io.jsonwebtoken.SignatureAlgorithm;

public class AuthenticationFilter extends UsernamePasswordAuthenticationFilter {
    private AuthenticationManager authManager;

    public AuthenticationFilter(AuthenticationManager am) {
        this.authManager = am;
    }

    @Override
    public Authentication attemptAuthentication(HttpServletRequest request, HttpServletResponse response)
            throws AuthenticationException {
        final String email = request.getParameter("email");
        final String password = request.getParameter("password");

        return authManager.authenticate(new UsernamePasswordAuthenticationToken(email, password));
    }

    @Override
    protected void successfulAuthentication(HttpServletRequest request, HttpServletResponse response, FilterChain chain,
            Authentication auth) throws IOException, ServletException {

        // generate token
        User u = (User) auth.getPrincipal();
        String email = u.getUsername();
        String token = Jwts.builder()
                .setSubject(email)
                .setExpiration(new Date(System.currentTimeMillis() + SecurityConstants.EXPIRE))
                .signWith(SignatureAlgorithm.HS512, SecurityConstants.SECRET)
                .compact();
        response.addHeader(SecurityConstants.HEADER, SecurityConstants.PREFIX + token);

        super.successfulAuthentication(request, response, chain, auth);
    }

}

enter image description here

我觉得你的配置没问题。

http.addFilter(authFilter) 将通过检查过滤器类型将过滤器放在适当的位置。

在你的情况下,我怀疑问题是没有正确触发登录请求。根据给定 repo 中的内容,我 运行 项目并使用嵌入式 H2 而不是完整的数据库。

如果您正在阅读 request.getParameter(parameterName),这就是您需要触发请求的方式。请注意,我收到了 404 错误,因为 Spring 试图将我重定向到不存在的“/”post 成功登录。 :)

使用 Spring 安全性 我在登录时总是遇到 CSRF 问题,因为该页面没有 CSRF 令牌,没有它就不允许 POST,请尝试检查它。