具有 spring 安全性的身份验证端点

endpoint for authentication with spring security

我想为登录创建自定义端点。

@PostMapping("/login")
public ResponseEntity<?> login(@RequestBody LoginUserRequest userRequest) {
    Authentication authentication = authenticationManager.authenticate(
            new UsernamePasswordAuthenticationToken(userRequest.getUsername(), userRequest.getPassword()));
    if (authentication != null && !(authentication instanceof AnonymousAuthenticationToken) && authentication.isAuthenticated()) {
        SecurityContextHolder.getContext().setAuthentication(authentication);
        return new ResponseEntity<>(null, null, HttpStatus.OK);
    }
    return new ResponseEntity<>(null, null, HttpStatus.UNAUTHORIZED);
}

密码和用户名正确时工作正常,但 returns 200 和登录表单而不是 401 数据不正确。

@EnableWebSecurity

public class SecurityConfiguration 扩展 WebSecurityConfigurerAdapter { private final UserDetailsS​​ervice userDetailsS​​ervice;

public SecurityConfiguration(UserDetailsService userDetailsService) {
    this.userDetailsService = userDetailsService;
}

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

@Override
protected void configure(HttpSecurity http) throws Exception {
    http.cors()
            .and()
            .authorizeRequests()
            .antMatchers(HttpMethod.GET).hasAuthority(UserRole.USER.name())
            .antMatchers(HttpMethod.POST, "/users").permitAll()
            .antMatchers(HttpMethod.POST, "/users/login").permitAll()
            .antMatchers(HttpMethod.POST).hasAuthority(UserRole.USER.name())
            .and()
            .formLogin()
            .permitAll()
            .and()
            .logout().invalidateHttpSession(true)
            .clearAuthentication(true).permitAll()
            .and()
            .csrf().disable();
}

@Override
@Bean
public AuthenticationManager authenticationManagerBean() throws Exception {
    return super.authenticationManagerBean();
}

}

试试这样:

不要忘记自动装配 AuthenticationManager 和其他服务!

 @RequestMapping(value = "/auth", method = RequestMethod.POST)
    public ResponseEntity<?> getAuthenticationToken(
            @RequestBody YourRequestDTO yourRequestDTO
    ) {
       
        try {

            authenticationManager.authenticate(
                    new UsernamePasswordAuthenticationToken(
                            authenticationRequest.getLogin(),
                            authenticationRequest.getPassword()
                    )
            );
        } catch (BadCredentialsException e) {
            ErrorResponse errors = new ErrorResponse();
            errors.addError("credentials", "Wrong password or username!");
            return ResponseEntity.status(YourStatus).body(errors);
        }