如何为用户名、密码和JWT配置webSecurity?

huangapple go评论74阅读模式
英文:

How to configure webSecurity for username and password with jwt?

问题

我想配置服务器,使用JWT进行用户名和密码的身份验证。我想只允许公开访问注册端点,其他端点需要登录。但显然,注册端点仍然进入JWT身份验证过滤器,并返回状态码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

编辑:这是我的POST请求示例:

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

I want to configure the server for authentication with username and password using JWT. I want to allow only the sign-up endpoint to be allowed publicly, the others requiring to be logged in. But apparently the sign-up endpoint still enters in the JWTAuthenticationFilter and returns 200 with no action done whatsoever.
For the rest of the endpoints it returns 403, when I would expect 401.
Below is the httpSecurity configuration:

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

    @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 extends UsernamePasswordAuthenticationFilter <br/>
JWTAuthorizationFilter extends BasicAuthenticationFilter

Edit: This is how my post request looks like:

@PostMapping(&quot;/sign-up&quot;)
    public ResponseEntity&lt;AddUserResult&gt; signUp(@RequestBody AddUserCommand command) {
        return new ResponseEntity&lt;&gt;(bus.executeCommand(command), HttpStatus.CREATED);
    }

答案1

得分: 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"));
}
英文:

You can try the follwing , just mention the sign up or login URL that you want to be loaded without authentication . In this was you will be able to access the URL without any authentication.

Also in Controller method , it would be good If you do not mention @PreAuthorize annotation

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

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

        http.csrf().disable();

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

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

    }

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

huangapple
  • 本文由 发表于 2020年5月4日 22:00:38
  • 转载请务必保留本文链接:https://go.coder-hub.com/61594047.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定