我正在学习Spring,现在正在尝试配置安全性。我需要创建安全端点,而不需要注册安全端点。 但是当我试图访问http://localhost:8080/register时,我收到错误“在SecurityContext中找不到身份验证对象”和“AuthenticationCredentialsNotFoundException”。 我在文档中重复了一些示例,但仍然遇到此错误。
WebSecurityConfig.java
@Configuration
@EnableWebSecurity
@EnableResourceServer
@EnableGlobalMethodSecurity(prePostEnabled = true)
public class WebSecurityConfig extends WebSecurityConfigurerAdapter {
@Override
public void configure(HttpSecurity http) throws Exception {
http
.authorizeRequests()
.antMatchers("/register").permitAll();
}
@Bean
@Override
public AuthenticationManager authenticationManagerBean() throws Exception {
return super.authenticationManagerBean();
}
}
OAuth2Config.java
@Configuration
@EnableAuthorizationServer
public class OAuth2Config extends AuthorizationServerConfigurerAdapter {
@Autowired
@Qualifier("userDetailsService")
private UserDetailsService userDetailsService;
@Autowired
private AuthenticationManager authenticationManager;
@Value("3600")
private int expiration;
@Bean
public PasswordEncoder passwordEncoder() {
return new BCryptPasswordEncoder();
}
@Override
public void configure(AuthorizationServerEndpointsConfigurer configurer) throws Exception {
configurer.authenticationManager(authenticationManager);
configurer.userDetailsService(userDetailsService);
}
@Override
public void configure(ClientDetailsServiceConfigurer clients) throws Exception {
clients.inMemory().withClient("app").secret("secret").accessTokenValiditySeconds(expiration)
.scopes("read", "write").authorizedGrantTypes("password", "refresh_token").resourceIds("resource");
}
}
RegisterController.java
@RestController
public class RegisterController {
@Autowired
UserDao userDao;
@Autowired
CityDao cityDao;
@RequestMapping(value = "/register", method = RequestMethod.POST)
public ResponseEntity<?> addUser(@RequestParam(value = "email") String email, @RequestParam(value = "firstName") String firstName,
@RequestParam(value = "lastName") String lastName, @RequestParam(value = "city") Long cityId,
@RequestParam(value = "password") String password){
User userToFind = userDao.findByEmail(email);
City city = cityDao.findById(cityId).get();
if (userToFind != null) {
PasswordEncoder passwordEncoder = new BCryptPasswordEncoder();
User user = new User(firstName, lastName, email, city, passwordEncoder.encode(password));
return new ResponseEntity<>(userDao.save(user), HttpStatus.CREATED);
}
else{
return new ResponseEntity<>(HttpStatus.CONFLICT);
}
}
}