我正在尝试配置spring安全性和控制器CORS请求,但是预检请求不起作用。我有一个与问题相关的控制器,测试和spring安全配置。我做错了吗?)
Java 8,Spring Boot 2.1.4
控制器
@RestController
@RequestMapping("/login")
@CrossOrigin
public class LoginController {
@RequestMapping(path = "/admin", consumes = "application/json", produces = "application/json")
public ResponseEntity<Admin> loginAdmin(@RequestBody Admin admin) {
String username = admin.getUsername();
String password = admin.getPassword();
authenticationManager.authenticate(new UsernamePasswordAuthenticationToken(username, password));
ResponseEntity<Admin> responseEntity;
Admin foundAdmin = adminRepository.findByUsername(username);
if (foundAdmin != null) {
String token = jwtTokenProvider.createToken(username, adminRepository.findByUsername(username).getRoles());
AdminAuthenticatedResponse contractorAuthenticatedResponse = new AdminAuthenticatedResponse(foundAdmin, token);
responseEntity = new ResponseEntity<>(contractorAuthenticatedResponse, HttpStatus.ACCEPTED);
} else {
responseEntity = new ResponseEntity<>(admin, HttpStatus.NOT_FOUND);
}
return responseEntity;
}
}
安全配置
@Override
protected void configure(HttpSecurity http) throws Exception {
http
.httpBasic().disable()
.csrf().disable()
.cors().and().formLogin().and()
.sessionManagement().sessionCreationPolicy(SessionCreationPolicy.STATELESS)
.and()
.authorizeRequests()
.antMatchers("/login/**").permitAll()
.antMatchers("/register/**").permitAll()
.antMatchers("/h2-console/**").permitAll()
.antMatchers(HttpMethod.GET, "/restapi/customers/**").permitAll()
.antMatchers(HttpMethod.DELETE, "/restapi/customers/**").hasRole("CUSTOMER")
.antMatchers(HttpMethod.PUT, "/restapi/customers/**").hasRole("CUSTOMER")
.antMatchers(HttpMethod.PATCH, "/restapi/customers/**").hasRole("CUSTOMER")
.antMatchers(HttpMethod.GET, "/restapi/contractors/**").permitAll()
.antMatchers(HttpMethod.DELETE, "/restapi/contractors/**").hasRole("CONTRACTOR")
.antMatchers(HttpMethod.PUT, "/restapi/contractors/**").hasRole("CONTRACTOR")
.antMatchers(HttpMethod.PATCH, "/restapi/contractors/**").hasRole("CONTRACTOR")
.antMatchers(HttpMethod.PATCH, "/restapi/workRequests/**").hasAnyRole("CONTRACTOR", "CONTRACTOR", "ADMIN")
.antMatchers(HttpMethod.PUT, "/restapi/workRequests/**").hasAnyRole("CONTRACTOR", "CONTRACTOR", "ADMIN")
.antMatchers(HttpMethod.POST, "/restapi/workRequests/**").hasAnyRole("CONTRACTOR", "CONTRACTOR", "ADMIN")
.antMatchers(HttpMethod.DELETE, "/restapi/workRequests/**").hasAnyRole("CONTRACTOR", "CONTRACTOR", "ADMIN")
.antMatchers(HttpMethod.GET, "/restapi/workRequests/**").hasAnyRole("CONTRACTOR", "CONTRACTOR", "ADMIN")
.anyRequest().authenticated()
.and()
.apply(new JwtConfigurer(jwtTokenProvider))
// Allow pages to be loaded in frames from the same origin; needed for H2-Console
.and()
.headers()
.frameOptions()
.sameOrigin();
}
@Override
protected void configure(AuthenticationManagerBuilder auth) throws Exception {
auth
.userDetailsService(userRepositoryUserDetailsService)
.passwordEncoder(encoder());
}
@Bean
CorsConfigurationSource corsConfigurationSource() {
CorsConfiguration configuration = new CorsConfiguration();
configuration.setAllowedOrigins(Arrays.asList(ALL));
configuration.setAllowedMethods(Arrays.asList(ALL));
UrlBasedCorsConfigurationSource source = new UrlBasedCorsConfigurationSource();
source.registerCorsConfiguration("/**", configuration);
return source;
}
@Override
public void configure(WebSecurity web) throws Exception {
web.ignoring()
.antMatchers("/**", "/resources/**", "/index.html", "/login/admin", "/template/**", "/",
"/error/**", "/h2-console", "*/h2-console/*");
}
测试
@Test
public void testLogin() {
Admin admin = new Admin("network", "network");
// adminRepository.save(admin);
String s = adminRepository.findByUsername("network").getUsername();
RequestEntity<Admin> requestEntity =
RequestEntity
.post(uri("/login/admin"))
.contentType(MediaType.APPLICATION_JSON)
.body(admin);
ResponseEntity<Admin> responseEntity = this.restTemplate.exchange(requestEntity, Admin.class);
assertNotNull(responseEntity);
System.out.println(responseEntity.getStatusCode());
}
我期望成功的请求,但是我收到内部服务器错误。
答案 0 :(得分:0)
403禁止访问或没有访问权限。 403禁止错误表示您没有查看请求的文件或资源的权限
请尝试使用@WithMockUser运行测试
@Test
@WithMockUser
public void corsWithAnnotation() throws Exception {
ResponseEntity<Admin> entity = this.restTemplate.exchange(
...
}