【发布时间】:2019-02-25 18:17:18
【问题描述】:
我正在使用 spring mvc 5 和 angular 6 启动应用程序,当我尝试通过发送带有 angular 的发布请求来获取令牌时,它会在我的浏览器控制台中显示此消息:
Cross-Origin Request Blocked: The Same Origin Policy disallows reading the remote resource at http://localhost:8080/gestion/oauth/token. (Reason: CORS header ‘Access-Control-Allow-Origin’ missing).
这是我的弹簧配置:
@Configuration
@EnableAuthorizationServer
@EnableGlobalMethodSecurity(prePostEnabled = true)
@Import(ServerSecurityConfig.class)
public class AuthServerOAuth2Config extends AuthorizationServerConfigurerAdapter {
@Autowired
private DataSource dataSource;
@Autowired
private AuthenticationManager authenticationManager;
@Autowired
private UserDetailsService userDetailsService;
@Autowired
private PasswordEncoder oauthClientPasswordEncoder;
@Bean
public TokenStore tokenStore() {
return new JdbcTokenStore(dataSource);
}
@Bean
public OAuth2AccessDeniedHandler oauthAccessDeniedHandler() {
return new OAuth2AccessDeniedHandler();
}
@Override
public void configure(AuthorizationServerSecurityConfigurer oauthServer) {
oauthServer.tokenKeyAccess("permitAll()").checkTokenAccess("isAuthenticated()").passwordEncoder(oauthClientPasswordEncoder);
}
@Override
public void configure(ClientDetailsServiceConfigurer clients) throws Exception {
clients.jdbc(dataSource);
}
@Override
public void configure(AuthorizationServerEndpointsConfigurer endpoints) {
endpoints.tokenStore(tokenStore()).authenticationManager(authenticationManager).userDetailsService(userDetailsService);
}
}
我的资源服务器配置类:
@Configuration
@EnableResourceServer
public class ResourceServerConfiguration extends ResourceServerConfigurerAdapter {
@Override
public void configure(HttpSecurity http) throws Exception {
http
.csrf().disable()
.requestMatchers().antMatchers("/api/**").and().authorizeRequests()
.antMatchers(HttpMethod.POST, "/api/**").access("#oauth2.hasScope('write')")
.anyRequest().access("#oauth2.hasScope('read')");
}
}
这是我的网络安全配置器类:
@Configuration
@EnableWebSecurity
@Import(Encoders.class)
public class ServerSecurityConfig extends WebSecurityConfigurerAdapter {
@Autowired
private UserDetailsService userDetailsService;
@Autowired
private PasswordEncoder userPasswordEncoder;
@Override
@Bean
public AuthenticationManager authenticationManagerBean() throws Exception {
return super.authenticationManagerBean();
}
@Override
protected void configure(AuthenticationManagerBuilder auth) throws Exception {
auth.userDetailsService(userDetailsService).passwordEncoder(userPasswordEncoder);
}
}
这是我的 APP 初始化程序:
public class AppInitializer extends AbstractAnnotationConfigDispatcherServletInitializer {
@Override
protected Class<?>[] getRootConfigClasses() {
return new Class[] {
AppConfig.class};
}
@Override
protected Class<?>[] getServletConfigClasses() {
return null;
}
@Override
protected String[] getServletMappings() {
return new String[] { "/" };
}
@Override
protected Filter[] getServletFilters() {
Filter [] filters = {new CorsFilter()};
return filters;
}
}
我的自定义过滤器:
public class CorsFilter implements Filter {
@Override
public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain)
throws IOException, ServletException {
HttpServletResponse httpResponse = (HttpServletResponse) response;
httpResponse.setHeader("Access-Control-Allow-Origin", "*");
chain.doFilter(request, response);
}
@Override
public void init(FilterConfig filterConfig) throws ServletException {
}
@Override
public void destroy() {
}
}
我的角度服务:
public login(credentials: any): Observable<any> {
const body = `username=${credentials.username}&password=${credentials.password}&grant_type=password&client_id=admin`;
return this.httpClient.post<any>(this.URL, body, { headers: new HttpHeaders({
'Authorization': `Basic ${btoa('admin:admin')}`,
'Content-type': 'application/x-www-form-urlencoded'
})});
}
我的问题是如何让 Angular HttpClient 发送这个 post 请求来生成令牌
【问题讨论】:
-
请调试您的浏览器并在此处发布结果。您应该会在 chrome 开发工具的网络选项卡下找到 401 错误。
标签: spring angular spring-mvc spring-security spring-oauth2