【发布时间】:2019-10-23 05:58:38
【问题描述】:
我正在设置一个 React 和 SpringBoot 应用程序,对于安全方法,我正在使用以下配置实现 OAuth2。我测试了授权端点“http:localhost:8080/oauth/token”以及在 Postman 上生成的令牌的 Client_id、Client_secret、用户凭据,一切正常,我取回了令牌。但是,当我尝试在 ReactJS 服务器上执行相同操作时,我总是得到 401 Unauthorized Response,此外,我在 Spring Server 中禁用了 CORS(出于测试目的),最终,我一直收到消息
CORS 策略已阻止从源“http://localhost:3000”获取“http://localhost:8080/oauth/token”的访问权限:对预检请求的响应未通过访问控制检查:它没有 HTTP ok 状态。
这是我的 AuthorizationServerConfig
@Configuration
@EnableAuthorizationServer
public class AuthorizationServerConfig extends
AuthorizationServerConfigurerAdapter {
@Autowired
private CustomAuthenticationManager authenticationManager;
@Override
public void configure(AuthorizationServerEndpointsConfigurer endpoints) throws Exception {
// TODO Auto-generated method stub
endpoints.authenticationManager(authenticationManager);
}
@Override
public void configure(ClientDetailsServiceConfigurer clients) throws Exception {
// TODO Auto-generated method stub
clients
.inMemory().withClient("client-id")
.secret(new BCryptPasswordEncoder().encode("secret"))
.scopes("resource:read")
.authorizedGrantTypes("password");
}
@Override
public void configure(AuthorizationServerSecurityConfigurer security) throws Exception {
// TODO Auto-generated method stub
security
.checkTokenAccess("isAuthenticated()")
.passwordEncoder(new BCryptPasswordEncoder());
}
}
这是我的资源服务器配置
@Configuration
@EnableResourceServer
public class ResourceServerConfig extends ResourceServerConfigurerAdapter {
@Override
public void configure(HttpSecurity http) throws Exception {
// TODO Auto-generated method stub
http.cors().disable().csrf().disable()
.authorizeRequests()
.antMatchers("/oauth/**").permitAll()
.anyRequest().authenticated();
}
}
重写方法以确保在 WebMvcConfigurer 实现的类中禁用 CORS
@Override
public void addCorsMappings(CorsRegistry registry) {
registry.addMapping("/**").allowedMethods("*").allowedHeaders("*").allowedOrigins("http://localhost:3000");
}
我的 React(客户端)代码
let form = new FormData();
form.append("grant_type", "password");
form.append("username", "myusername");
form.append("password", "mypassword");
let code = new Buffer("client-id:secret").toString('base64');
console.log(code); // gives the same string as appeared in Postman code snippets
fetch("http://localhost:8080/oauth/token", {
method: "POST",
mode: "no-cors", // even if I remove this or change it to 'cors', result was still the same but
// (but I want cors enabled when I've successfully test out this authorize method)
headers: {
"Authorization" : "Basic " + code
},
body: form
})
.then(
res => console.log(res)
)
任何帮助将不胜感激。谢谢。
【问题讨论】:
-
配置参数以在您的服务器上处理 CORS。
-
我已经用配置文件中的 HttpSecurity 覆盖了 addCorsMapping 并禁用了 CORS,我还需要做些什么吗?
标签: reactjs spring-boot oauth-2.0