我的 Angular 4 应用程序无法向 Spring Boot Server 请求令牌
Posted
技术标签:
【中文标题】我的 Angular 4 应用程序无法向 Spring Boot Server 请求令牌【英文标题】:My Angular 4 Application cannot request token to Spring Boot Server 【发布时间】:2018-06-14 20:17:10 【问题描述】:我目前正在开发一个以 Spring Boot 作为后端的 Angular 4 应用程序。
当我想向后端服务器请求令牌时,每个浏览器都会收到不同的错误消息。 1. Chrome 控制台消息:
无法加载 http://localhost:4002/oauth/token?username=wiko&password=shefvaas&grant_type=password:预检响应包含无效的 HTTP 状态代码 401
-
Firefox 控制台消息:
跨域请求被阻止:同源策略不允许读取位于http://localhost:4002/oauth/token?username=wiko&password=shefvaas&grant_type=password 的远程资源。 (原因:CORS 预检通道未成功)
这是我的角度请求:
genHeaders(map?: ConfigurationMap)
const httpHeaders = new HttpHeaders(
'Content-Type': 'application/json',
'Authorization': ('Basic ' + btoa('fayaqun:satria'))
);
return
headers: httpHeaders,
withCredentials: true
;
这是我的 Spring Boot AuthorizationServerConfig:
@Autowired
private AuthenticationManager authManager;
@Override
public void configure(AuthorizationServerSecurityConfigurer security) throws Exception
security.checkTokenAccess("isAuthenticated()");
@Override
public void configure(ClientDetailsServiceConfigurer clients) throws Exception
clients.inMemory().withClient("fayaqun" )
.authorizedGrantTypes("client_credentials", "password", "refresh_token")
.authorities("ROLE_SUPERUSER", "ROLE_VALIDATOR", "ROLE_CLIENT", "ROLE_GUEST")
.scopes("read", "write", "trust")
.resourceIds("oauth2-resource")
.accessTokenValiditySeconds(86400)
.secret("satria");
@Override
public void configure(AuthorizationServerEndpointsConfigurer endpoints) throws Exception
endpoints.tokenStore(tokenStore()).authenticationManager(authManager);
@Bean
public TokenStore tokenStore()
return new InMemoryTokenStore();
有这方面的经验吗?
谢谢。
【问题讨论】:
【参考方案1】:我是几周前做的。 Spring 使用 Angular 4+Oauth2。
我认为你的问题是你的 CORS 授权。
import com.thespringwheels.api.config.property.TheWheelsApiProperty;
@Component
@Order(Ordered.HIGHEST_PRECEDENCE)
public class CorsFilter implements Filter
@Autowired
private TheWheelsApiProperty thewheelsApiProperty;
@Override
public void doFilter(ServletRequest req, ServletResponse resp, FilterChain chain)
throws IOException, ServletException
HttpServletRequest request = (HttpServletRequest) req;
HttpServletResponse response = (HttpServletResponse) resp;
for( String origin: thewheelsApiProperty.getOriginAllowed())
response.setHeader("Access-Control-Allow-Origin", origin);
response.setHeader("Access-Control-Allow-Credentials", "true");
if ("OPTIONS".equals(request.getMethod()) && thewheelsApiProperty.getOriginAllowed().contains(request.getHeader("Origin")) )
response.setHeader("Access-Control-Allow-Methods", "POST, GET, DELETE, PUT, OPTIONS");
response.setHeader("Access-Control-Allow-Headers", "Authorization, Content-Type, Accept");
response.setHeader("Access-Control-Max-Age", "3600");
response.setStatus(HttpServletResponse.SC_OK);
else
chain.doFilter(req, resp);
@Override
public void destroy()
@Override
public void init(FilterConfig arg0) throws ServletException
package com.thespringwheels.api.config.property;
import java.util.List;
import org.springframework.boot.context.properties.ConfigurationProperties;
import org.springframework.stereotype.Component;
@Component
@ConfigurationProperties("thewheels") //FIXME: Customize here
public class TheWheelsApiProperty
//FIXME: Customize here - Define the origin throught application.propertis or system initialization parameter
List<String> originAllowed = java.util.Arrays.asList( "http://localhost:4200");
private int accessTokenValiditySeconds=360;
private int refreshTokenValiditySeconds=120000;
private final Security security = new Security();
public Security getSecurity()
return security;
public List<String> getOriginAllowed()
return originAllowed;
public void setOriginAllowed(String originAllowed)
this.originAllowed.add(originAllowed);
public int getRefreshTokenValiditySeconds()
return refreshTokenValiditySeconds;
public void setRefreshTokenValiditySeconds(int refreshTokenValiditySeconds)
this.refreshTokenValiditySeconds = refreshTokenValiditySeconds;
public int getAccessTokenValiditySeconds()
return accessTokenValiditySeconds;
public void setAccessTokenValiditySeconds(int accessTokenValiditySeconds)
this.accessTokenValiditySeconds = accessTokenValiditySeconds;
public static class Security
private boolean enableHttps;
public boolean isEnableHttps()
return enableHttps;
public void setEnableHttps(boolean enableHttps)
this.enableHttps = enableHttps;
【讨论】:
以上是关于我的 Angular 4 应用程序无法向 Spring Boot Server 请求令牌的主要内容,如果未能解决你的问题,请参考以下文章
无法从另一个组件/ Angular 4中的auth.service访问错误消息
我无法在 Angular 4 上向 laravel api 发送带有标头的 http 请求
无法从 Webpack 配置向 Angular 2 提供环境变量