@CrossOrigin(origins = "http://localhost:4200")
@RestController
@RequestMapping("/api/auth/")
public class LoginController {
private AuthenticationManager authenticationManager;
JwtTokenProvider jwtTokenProvider;
public JwtTokenProvider jwtTokenProvider() {
return jwtTokenProvider;
}
@Autowired
UserRepository users;
@Autowired
private CustomUserDetailsService userService;
@SuppressWarnings("rawtypes")
@PostMapping("/login")
public ResponseEntity login(@RequestBody AuthBody data) {
try {
String username = data.getEmail();
authenticationManager.authenticate(new UsernamePasswordAuthenticationToken(username, data.getPassword()));
String token = jwtTokenProvider.createToken(username, this.users.findByEmail(username).getRoles());
Map<Object, Object> model = new HashMap<>();
model.put("username", username);
model.put("token", token);
// return ResponseEntity.ok(model);
return new ResponseEntity<>(model.toString(), HttpStatus.OK);
} catch (AuthenticationException e) {
throw new BadCredentialsException("Invalid email/password supplied");
}
}
}
我的网络安全配置:
public class WebSecurityConfig extends WebSecurityConfigurerAdapter {
@Bean( name = BeanIds.AUTHENTICATION_MANAGER)
@Override
public AuthenticationManager authenticationManagerBean() throws Exception {
return super.authenticationManagerBean() ;
}
@Autowired
JwtTokenProvider jwtTokenProvider;
@Override
protected void configure(AuthenticationManagerBuilder auth) throws Exception {
UserDetailsService userDetailsService = mongoUserDetails();
auth.userDetailsService(userDetailsService).passwordEncoder(bCryptPasswordEncoder());
}
@Override
protected void configure(HttpSecurity http) throws Exception {
http.httpBasic().disable().csrf().disable().sessionManagement()
.sessionCreationPolicy(SessionCreationPolicy.STATELESS).and().authorizeRequests()
.antMatchers("/api/auth/login").permitAll().antMatchers("/api/auth/register").permitAll()
.antMatchers("/api/products/**").hasAuthority("ADMIN").anyRequest().authenticated().and().csrf()
.disable().exceptionHandling().authenticationEntryPoint(unauthorizedEntryPoint()).and()
.apply(new JwtConfigurer(jwtTokenProvider));
http.cors();
}
@Override
public void configure(WebSecurity web) throws Exception {
web.ignoring().antMatchers("/**");
}
@Bean
public PasswordEncoder bCryptPasswordEncoder() {
return new BCryptPasswordEncoder();
}
@Bean
public AuthenticationEntryPoint unauthorizedEntryPoint() {
return (request, response, authException) -> response.sendError(HttpServletResponse.SC_UNAUTHORIZED,
"Unauthorized");
}
@Bean
public UserDetailsService mongoUserDetails() {
return new CustomUserDetailsService();
}
}
我总是在
authentiticationMnager.authenticate
上遇到空指针异常!
我正在使用 spring security v 1.1.1 版本和 jjwt 版本 0.9.1 。
authenticationManager 始终为空。
已解决。
我的错误是包路径错误。
尝试添加
@Autowired
我有同样的问题。添加后就清空了。
你可以在 WebSecurityConfig 类中尝试这个注释吗
@EnableWebSecurity
@EnableGlobalMethodSecurity(prePostEnabled = true)