【问题标题】:Why am I getting 401 for authorization request when authorize with OAuth2 Server sent from localhost but works fine using Postman为什么我在使用从本地主机发送的 OAuth2 服务器进行授权时收到 401 授权请求,但使用 Postman 可以正常工作
【发布时间】: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


【解决方案1】:

浏览器阻止您的请求,因为出于安全原因,它通常允许来自同一来源的请求。您可以要求维护服务器的人员将您的主机名添加到 Access-Control-Allow-Origin 主机,服务器应返回类似于以下响应的标头:

Access-Control-Allow-Origin: yourhostname:port

或者您可以简单地在浏览器上禁用同源策略。如果是 chrome 并且您使用的是 linux,请打开终端并运行:

$ google-chrome --disable-web-security

如果您使用的是 OSX:

$ open -a Google\ Chrome --args --disable-web-security --user-data-dir

或 Windows 进入命令提示符并进入 Chrome.exe 所在的文件夹并键入:

chrome.exe --disable-web-security

【讨论】:

  • 嗨!问题是当我允许对所有 api 的所有访问时,cors 停止弹出。所以我很确定这不是因为 cors 并且状态码无论如何都是 401。感谢您的解释。
【解决方案2】:

所以我对 CORS 问题进行了一些研究,因为我认为 OAuth 实际上可能没有遵循我的 CORS 配置并实施它自己的策略。我发现了这个问题,最受好评的答案解决了我的问题

https://stackoverflow.com/a/44819743/10264578

如果有人像我一样遇到这个问题,您所要做的就是创建答案中给出的过滤器,然后将该过滤器配置到 Spring Security FilterChain 像这样

@Configuration
@EnableResourceServer
public class ResourceServerConfig extends ResourceServerConfigurerAdapter {

@Autowired
private CorsFilter filter;

    @Override
    public void configure(HttpSecurity http) throws Exception {
        // TODO Auto-generated method stub
        http.csrf().disable()
            .addFilterBefore(filter, UsernamePasswordAuthenticationFilter.class)
            .authorizeRequests()
                .antMatchers("/oauth/**").permitAll()
                .anyRequest().authenticated();
    }
}

【讨论】:

    猜你喜欢
    • 2020-05-07
    • 1970-01-01
    • 2017-11-10
    • 1970-01-01
    • 1970-01-01
    • 2016-12-04
    • 1970-01-01
    • 1970-01-01
    • 2022-11-29
    相关资源
    最近更新 更多