【问题标题】:How to configure webSecurity for username and password with jwt?如何使用 jwt 为用户名和密码配置 webSecurity?
【发布时间】:2020-08-18 23:40:48
【问题描述】:

我想配置服务器以使用 JWT 使用用户名和密码进行身份验证。我想只允许公开允许 sign-up 端点,其他端点需要登录。但显然注册端点仍然进入 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 扩展了 BasicAuthenticationFilter

编辑:这就是我的发布请求的样子:

@PostMapping("/sign-up")
    public ResponseEntity<AddUserResult> signUp(@RequestBody AddUserCommand command) {
        return new ResponseEntity<>(bus.executeCommand(command), HttpStatus.CREATED);
    }

【问题讨论】:

  • 加载时注册 URL 是获取请求吗?
  • 这是一个post请求
  • 你试过我发布的解决方案了吗
  • 最终我决定使用基本身份验证和 https,因此我不再使用 JWT。

标签: java spring spring-boot spring-security


【解决方案1】:

您可以尝试以下方法,只需提及您希望在不进行身份验证的情况下加载的注册或登录 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);

    }

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

【讨论】:

    猜你喜欢
    • 2011-08-14
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2013-09-13
    • 2011-09-25
    • 2012-03-14
    相关资源
    最近更新 更多