我正在从angular向我的服务器发送一个带有标题的请求
withCredentials
作为
true
http://0.0.0.0:4200
我的角跑。因为我的请求包含它发送的authorization头
飞行前请求
请求头的值中没有通配符
“访问控制允许原点”
.
角度法:
const headers = new HttpHeaders(credentials ? {
authorization : 'Basic ' + btoa(credentials.username + ':' + credentials.password)
} : {});
headers.set("Access-Control-Allow-Origin","http://localhost:4200")
this.http.get('http://localhost:8080/user', {headers: headers , withCredentials: true }).subscribe(response => {..}
服务器端代码:-
public class CorsFilter extends OncePerRequestFilter {
@Override
protected void doFilterInternal(HttpServletRequest request,
HttpServletResponse response, FilterChain filterChain)
throws ServletException, IOException {
response.setHeader("Access-Control-Allow-Origin", "http://localhost:4200");
response.setHeader("Access-Control-Allow-Methods", "GET, POST, PUT, DELETE, OPTIONS");
response.setHeader("Access-Control-Allow-Headers", "authorization,withCredentials, content-type, xsrf-token, Cache-Control, Cookie");
response.addHeader("Access-Control-Expose-Headers", "xsrf-token");
response.addHeader("Access-Control-Allow-Credentials", "true");
if ("OPTIONS".equals(request.getMethod())) {
response.setStatus(HttpServletResponse.SC_OK);
} else {
filterChain.doFilter(request, response);
}
}
}
@EnableWebSecurity
@Configuration
public class WebSecurityConfig extends WebSecurityConfigurerAdapter {
@Override
protected void configure(HttpSecurity http) throws Exception {
http.addFilterBefore(new CorsFilter(), ChannelProcessingFilter.class);
http
.httpBasic()
.and()
.authorizeRequests()
.antMatchers("/").permitAll()
.anyRequest().authenticated().and().csrf()
.csrfTokenRepository(CookieCsrfTokenRepository.withHttpOnlyFalse());;
}
}
@RestController
@CrossOrigin
public class SecurityController {
@GetMapping("/hi")
public Response method() {
return new Response("Hi this is resposne from hi");
}
@GetMapping("/hi2")
public Response method2() {
return new Response("Hi this is resposne from hi2");
}
@RequestMapping("/user")
public Principal user(Principal user) {
return user;
}
}