【发布时间】: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 UserDetailsService userDetailsService;
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