【发布时间】:2018-12-31 17:23:09
【问题描述】:
我正在使用 spring security 和 oauthv2 使用 spring boot 创建一个应用程序,并且我创建了我的授权服务器,当我从邮递员访问资源“http://localhost:8181/oauth/token”时它工作正常但是当我从我的角度应用程序访问相同的资源时它每次都给我401。我不知道我每次都从角度得到 401。
授权服务器
@Configuration
@EnableAuthorizationServer
@EnableGlobalMethodSecurity(prePostEnabled = true)
@Import(ServerSecurityConfig.class)
public class AuthServerOAuth2Config extends AuthorizationServerConfigurerAdapter {
@Autowired
private AuthenticationManager authenticationManager;
@Autowired
private UserDetailsService userDetailsService;
private final AppConfig appConfig;
@Autowired
public AuthServerOAuth2Config( AppConfig appConfig) {
this.appConfig = appConfig;
}
@Bean
public TokenStore tokenStore() {
return new JdbcTokenStore(appConfig.dataSource());
}
@Bean
public OAuth2AccessDeniedHandler oauthAccessDeniedHandler() {
return new OAuth2AccessDeniedHandler();
}
@Override
public void configure(AuthorizationServerSecurityConfigurer oauthServer) {
oauthServer.tokenKeyAccess("permitAll()").checkTokenAccess("isAuthenticated()");
}
@Override
public void configure(ClientDetailsServiceConfigurer clients) throws Exception {
clients.jdbc(appConfig.dataSource());
}
@Override
public void configure(AuthorizationServerEndpointsConfigurer endpoints) {
endpoints.tokenStore(tokenStore()).authenticationManager(authenticationManager).userDetailsService(userDetailsService);
}
}
CorsFilter
@Component
@Order(Ordered.HIGHEST_PRECEDENCE)
public class CorsFilter implements Filter {
@Override
public void doFilter(ServletRequest req, ServletResponse res, FilterChain chain) throws IOException, ServletException {
final HttpServletResponse response = (HttpServletResponse) res;
final HttpServletRequest request = (HttpServletRequest) req;
response.addHeader("Access-Control-Allow-Origin", "*");
if ("OPTIONS".equalsIgnoreCase(request.getMethod())) {
response.setHeader("Access-Control-Allow-Methods", "POST,GET,DELETE");
response.setHeader("Access-Control-Max-Age", "3600");
response.setHeader("Access-Control-Allow-Headers", "content-type,access-control-request-headers,access-control-request-method,accept,origin,authorization,x-requested-with");
response.setStatus(HttpServletResponse.SC_OK);
} else {
chain.doFilter(req, res);
}
}
@Override
public void destroy() {
}
@Override
public void init(FilterConfig config) throws ServletException {
}
}
角度代码
signin(user: User){
let params = new URLSearchParams();
params.append('username',user.username);
params.append('password',user.password);
params.append('grant_type','password');
params.append('client_id','web');
let headers = new Headers({'Content-type': 'application/x-www-form-urlencoded; charset=utf-8',
'Authorization': 'Basic '+btoa("fooClientIdPassword:secret")});
let options = new RequestOptions({ headers: headers });
return this._http.post('http://192.168.0.14:8181/oauth/token', params.toString(), options);
}
【问题讨论】:
-
添加请求和响应,包括标头,例如浏览器中开发工具的屏幕截图。
标签: spring-boot spring-security oauth-2.0