在新控制器中插入customAuthenticationManager。
@Autowired
private AuthenticationManager authenticationManager;
@RequestMapping(value = "${jwt.route.authentication.path}", method = RequestMethod.POST)
public ResponseEntity<?> createAuthenticationToken(@RequestBody JwtAuthenticationRequest authenticationRequest)
throws AuthenticationException {
Authentication customAuthentication = authenticationManager.authenticate(new UsernamePasswordAuthenticationToken(
authenticationRequest.getUsername(), authenticationRequest.getPassword()));
SecurityContextHolder.getContext().setAuthentication(authentication);
return ResponseEntity
.ok(new JwtAuthenticationResponse(customAuthentication.getToken(), customAuthentication.isActive()));
}
然后覆盖默认的Spring AuthenticationManager+AuthenticationProvider
@Configuration
@EnableWebSecurity
@EnableGlobalMethodSecurity(prePostEnabled = true)
public class WebSecurityConfig extends WebSecurityConfigurerAdapter {
@Autowired
private CustomAuthenticationProvider customAuthenticationProvider;
@Autowired
public void configureAuthentication(AuthenticationManagerBuilder authenticationManagerBuilder) {
authenticationManagerBuilder.authenticationProvider(customAuthenticationProvider);
}
@Bean(name = BeanIds.AUTHENTICATION_MANAGER)
@Override
public AuthenticationManager authenticationManagerBean() throws Exception {
return super.authenticationManagerBean();
}
import org.springframework.security.authentication.AuthenticationProvider;
@Component("customAuthenticationProvider")
public class CustomAuthenticationProvider implements AuthenticationProvider {