无法加载 http://localhost:9999/auth-service/oauth/token:预检响应具有无效的 HTTP 状态代码 401
Posted
技术标签:
【中文标题】无法加载 http://localhost:9999/auth-service/oauth/token:预检响应具有无效的 HTTP 状态代码 401【英文标题】:Failed to load http://localhost:9999/auth-service/oauth/token: Response for preflight has invalid HTTP status code 401 【发布时间】:2018-09-10 05:45:37 【问题描述】:尝试生成 Oauth2 令牌我使用了 Spring Boot Oauth2 和 Angular 5
在邮递员和 curl 中,我可以通过传递适当的值来生成令牌,并且使用相同的参数它在 Angular POST 中不起作用
错误
选项http://localhost:9999/auth-service/oauth/token 401 () 无法加载 http://localhost:9999/auth-service/oauth/token:响应 预检具有无效的 HTTP 状态代码 401。
角度代码
login2(credentials)
let headers = new Headers();
var creds = 'client_id=finance-service&client_secret=finance&grant_type=client_credentials&socpe=server';
headers.append('Content-Type', 'application/x-www-form-urlencoded');
headers.append("Authorization", "Basic " + btoa("finance-service:finance"));
console.log(btoa("finance-service:finance"))
return new Promise((resolve) =>
this.http.post(SMSGlobal.authPath, creds, headers : headers)
.subscribe((data) =>
console.log(data.json());
,
(error) =>
console.log(error);
)
)
我也在后端配置了 CORS
【问题讨论】:
如果出现这个错误,说明后台没有正确配置COS 呼!这可能有很多答案。提供的对您有用吗? 【参考方案1】:我在 Spring 5 + Angular 5 项目中遇到了同样的问题。我从 here 找到了解决方案
应添加 CORS 配置以解决此问题。代码如下
import org.springframework.boot.web.servlet.FilterRegistrationBean;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.core.Ordered;
import org.springframework.web.cors.CorsConfiguration;
import org.springframework.web.cors.UrlBasedCorsConfigurationSource;
import org.springframework.web.filter.CorsFilter;
@Configuration
public class CorsConfig
@Bean
public FilterRegistrationBean<CorsFilter> corsFilterRegistrationBean()
UrlBasedCorsConfigurationSource source = new UrlBasedCorsConfigurationSource();
CorsConfiguration config = new CorsConfiguration();
config.setAllowCredentials(true);
config.addAllowedOrigin("http://localhost:4200");
config.addAllowedHeader("Authorization");
config.addAllowedHeader("Content-Type");
config.addAllowedHeader("Accept");
config.addAllowedMethod("POST");
config.addAllowedMethod("GET");
config.addAllowedMethod("DELETE");
config.addAllowedMethod("PUT");
config.addAllowedMethod("OPTIONS");
config.setMaxAge(3600L);
// source.registerCorsConfiguration("/oauth/token", config); // Add "/oauth/token" explicitly
source.registerCorsConfiguration("/**", config); // Global for all paths
FilterRegistrationBean<CorsFilter> bean = new FilterRegistrationBean<CorsFilter>(new CorsFilter(source));
bean.setOrder(Ordered.HIGHEST_PRECEDENCE);
return bean;
【讨论】:
【参考方案2】:在 AuthorizationServerConfigurerAdapter 中你必须配置自定义的 TokenEndpointAuthenticationFilter
public class CorsFilter implements Filter
@Override
public void init(FilterConfig filterConfig) throws ServletException
@Override
public void doFilter(ServletRequest req, ServletResponse res, FilterChain chain) throws IOException, ServletException
HttpServletRequest request = (HttpServletRequest) req;
HttpServletResponse response = (HttpServletResponse) res;
response.setHeader("Access-Control-Allow-Origin", request.getHeader("Origin"));
response.setHeader("Access-Control-Allow-Credentials", "true");
response.setHeader("Access-Control-Allow-Headers", "*");
response.setHeader("Access-Control-Expose-Headers", "Content-Length, Content-Type, X-Requested-With");
response.setHeader("Access-Control-Allow-Methods", "*");
if ("OPTIONS".equalsIgnoreCase(request.getMethod()))
response.setStatus(HttpServletResponse.SC_OK);
else
chain.doFilter(req, res);
@Override
public void destroy()
AuthorizationServerConfigurerAdapter:
@Configuration
@EnableAuthorizationServer
public class AuthorizationServerConfiguration extends AuthorizationServerConfigurerAdapter
@Override
public void configure(AuthorizationServerSecurityConfigurer oauthServer) throws Exception
oauthServer.tokenKeyAccess("permitAll()").checkTokenAccess("isAuthenticated()")
.addTokenEndpointAuthenticationFilter(new CorsFilter());
路径/oauth/上的每个请求都进入过滤器,如果请求方法是OPTIONS,则将避免错误:预检响应具有无效的HTTP状态码401。
【讨论】:
以上是关于无法加载 http://localhost:9999/auth-service/oauth/token:预检响应具有无效的 HTTP 状态代码 401的主要内容,如果未能解决你的问题,请参考以下文章