【问题标题】:endpoint for authentication with spring security使用 Spring Security 进行身份验证的端点
【发布时间】:2021-11-25 11:30:39
【问题描述】:

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

@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);
}

当密码和用户名正确但返回 200 和登录表单而不是 401 时,它可以正常工作。

@EnableWebSecurity

公共类 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();
}

}

【问题讨论】:

    标签: java spring-security endpoint


    【解决方案1】:

    试试类似的方法:

    别忘了 Autowire 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);
            }
    

    【讨论】:

      猜你喜欢
      • 2012-11-27
      • 1970-01-01
      • 2015-06-29
      • 2011-10-17
      • 2018-08-09
      • 2012-11-10
      • 2017-04-15
      • 2011-08-14
      相关资源
      最近更新 更多