Java 如何使用jwt为用户名和密码配置Web安全性?

Java 如何使用jwt为用户名和密码配置Web安全性?,java,spring,spring-boot,spring-security,Java,Spring,Spring Boot,Spring Security,我想使用JWT配置服务器,以便使用用户名和密码进行身份验证。我只允许公开注册端点,其他需要登录的端点。但显然,注册端点仍然进入JWTAuthenticationFilter并返回200,而不执行任何操作。 对于其余的端点,它返回403,而我期望的是401。 以下是httpSecurity配置: private static final String SIGN_UP_URL = "/users/sign-up"; @Override protected void configur

我想使用JWT配置服务器,以便使用用户名和密码进行身份验证。我只允许公开注册端点,其他需要登录的端点。但显然,注册端点仍然进入JWTAuthenticationFilter并返回200,而不执行任何操作。 对于其余的端点,它返回403,而我期望的是401。 以下是httpSecurity配置:

private static final String SIGN_UP_URL = "/users/sign-up";

    @Override
    protected void configure(HttpSecurity http) throws Exception {
        http.cors().and().csrf().disable().authorizeRequests()
                .antMatchers(HttpMethod.POST, SIGN_UP_URL).permitAll()
                .anyRequest().authenticated()
                .and()
                .addFilter(new JWTAuthenticationFilter(authenticationManager()))
                .addFilter(new JWTAuthorizationFilter(authenticationManager()))
                .sessionManagement().sessionCreationPolicy(SessionCreationPolicy.STATELESS);
    }
JWTAuthenticationFilter扩展了UsernamePasswordAuthenticationFilter
JWTAuthorizationFilter扩展了基本身份验证筛选器

编辑:这是我的post请求的样子:

@PostMapping("/sign-up")
    public ResponseEntity<AddUserResult> signUp(@RequestBody AddUserCommand command) {
        return new ResponseEntity<>(bus.executeCommand(command), HttpStatus.CREATED);
    }
@PostMapping(“/注册”)
公共响应注册(@RequestBody AddUserCommand){
返回新的响应属性(bus.executeCommand(命令),HttpStatus.CREATED);
}

您可以尝试以下操作,只需提及您希望在没有身份验证的情况下加载的注册或登录URL即可。在这种情况下,您将能够访问URL而无需任何身份验证

同样在Controller方法中,若您不提及@PreAuthorize注释,那个就好了

    @Override
    protected void configure(HttpSecurity http) throws Exception {

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

        http.csrf().disable();

        http.sessionManagement().sessionCreationPolicy(SessionCreationPolicy.STATELESS);

        http.addFilterBefore(new JwtTokenFilter(userDetailsService), UsernamePasswordAuthenticationFilter.class);

    }

加载时注册URL是否为get请求?是否为post请求您是否尝试了我后来决定使用基本身份验证和https的解决方案,因此我不再使用JWTs。

    @PostMapping(value = "/signup")
    public User signup(@RequestBody @Valid SignUpRequest signUpRequest) {
        return userService.signup(signUpRequest)
                .orElseThrow(() -> new HttpServerErrorException(HttpStatus.BAD_REQUEST, "User Already Exists"));
    }