我是一个新手,在做认证服务。当我尝试从Postman中获取访问令牌时,一切都很正常。但是当我使用Angular时,我得到了这个错误。
Access to XMLHttpRequest at 'localhost:8082/oauth/token' from origin 'http://localhost:4200' has been blocked by CORS policy: Cross origin requests are only supported for protocol schemes: http, data, chrome, chrome-extension, https.
我的配置是。
@SpringBootApplication
@EnableEurekaClient
@EnableWebSecurity
public class AuthMsApplication extends WebSecurityConfigurerAdapter {
public static void main(String[] args) {
SpringApplication.run(AuthMsApplication.class, args);
}
}
@Component
@Order(Ordered.HIGHEST_PRECEDENCE)
@WebFilter("/*")
public class CorsFilter implements Filter {
@Override
public void doFilter(ServletRequest req, ServletResponse res, FilterChain chain) throws IOException, ServletException {
final HttpServletResponse response = (HttpServletResponse) res;
response.setHeader("Access-Control-Allow-Origin", "*");
response.setHeader("Access-Control-Allow-Methods", "POST, PUT, GET, OPTIONS, DELETE");
response.setHeader("Access-Control-Allow-Headers", "content-type, x-requested-with, authorization");
response.setHeader("Access-Control-Max-Age", "3600");
if ("OPTIONS".equalsIgnoreCase(((HttpServletRequest) req).getMethod())) {
response.setStatus(HttpServletResponse.SC_OK);
} else {
chain.doFilter(req, res);
}
}
}
@EnableAuthorizationServer
@Configuration
public class OAuth2Config extends AuthorizationServerConfigurerAdapter {
private static final String READ = "read";
private static final String WRITE = "write";
private static final String PASSWORD = "password";
private static final String REFRESH_TOKEN = "refresh_token";
@Value("${client.id}")
private String clientId;
@Value("${client.secret}")
private String clientSecret;
@Value("${tokenSignature}")
private String tokenSignature;
@Value("${accessTokenValiditySeconds}")
private int accessTokenValiditySeconds;
@Value("${refreshTokenValiditySeconds}")
private int refreshTokenValiditySeconds;
private final AuthenticationManager authenticationManager;
private final UserDetailsService customDetailsService;
public OAuth2Config(@Qualifier("authenticationProviderImpl") AuthenticationManager authenticationManager,
UserDetailsService customDetailsService) {
this.authenticationManager = authenticationManager;
this.customDetailsService = customDetailsService;
}
@Bean
public JwtAccessTokenConverter tokenEnhancer() {
JwtAccessTokenConverter converter = new JwtAccessTokenConverter();
converter.setSigningKey(tokenSignature);
return converter;
}
@Bean
public JwtTokenStore tokenStore() {
return new JwtTokenStore(tokenEnhancer());
}
@Override
public void configure(AuthorizationServerEndpointsConfigurer endpoints) {
endpoints.authenticationManager(authenticationManager)
.tokenStore(tokenStore())
.accessTokenConverter(tokenEnhancer())
.userDetailsService(customDetailsService);
}
@Bean
public PasswordEncoder encoder() {
return new BCryptPasswordEncoder();
}
@Override
public void configure(AuthorizationServerSecurityConfigurer security) {
security.tokenKeyAccess("permitAll()").checkTokenAccess("isAuthenticated()");
}
@Override
public void configure(ClientDetailsServiceConfigurer clients) throws Exception {
String encodedClientSecret = encoder().encode(clientSecret);
clients.inMemory()
.withClient(clientId)
.secret(encodedClientSecret)
.scopes(READ, WRITE)
.authorizedGrantTypes(PASSWORD, REFRESH_TOKEN)
.accessTokenValiditySeconds(accessTokenValiditySeconds)
.refreshTokenValiditySeconds(refreshTokenValiditySeconds);
}
}
Any searching info not working as global CORS. 有一件事是工作的,它是
@CrossOrigin(origins = "*", allowedHeaders = "*")
但我可以把这个放在我自己的控制器上,但我不知道如何为authtoken端点设置它。
这个官方文档的解决方案无法使用。https:/docs.spring.iospring-securitysitedocs4.2.xreferencehtmlcors.html。
过滤器也不工作。
3天后,我找到了解决方案。首先,我删除了我的Auth服务中的所有过滤器。其次,我在我的网关服务中添加这个道具。
cloud:
gateway:
globalcors:
corsConfigurations:
'[/**]':
allowedOrigins: "*"
allowedHeaders:
- content-type
- x-requested-with
- Authorization
allowedMethods:
- GET
- POST
- OPTIONS
- DELETE
- PUT
你只需要在网关道具中为你的所有服务添加全局头文件,这也可以与服务中的过滤器结合起来,以实现更灵活的设置.我希望这可以帮助一些人节省3天时间)
这是各地普遍存在的问题,由于产地不同,保护了不同产地的注入。
解决方法:1)如果你使用的是开发版,那么在chrome上启用CORS(扩展)(POSTMAN默认是这样做的)。
1)如果你是用于开发,那么在chrome(扩展)上启用CORS(POSTMAN默认这样做)
2)在生产中,托管的angular应用应该白名单你的API URL。
3)第三套科室允许原产地标头