React Oauth2 Header问题:使用clientID和client-secret进行授权

时间:2019-03-27 18:05:07

标签: reactjs spring-security oauth-2.0 http-headers http-status-code-401

我试图将参数传递给服务器并获取访问令牌。我已经使用cURL和Postman对它进行了测试,并且它的工作原理就像是一种魅力。但是,在React中,我总是以401 Unauthorized结束(这与我在Postman中不添加clientId和secret时得到的相同)。因此,我怀疑凭据设置中可能存在问题。在Postman上,我做clinetid:clientpass@server:/path。如果按如下所示使用no-cors,它会通过但我会收到一个没有正文的opaque响应(该响应在浏览器中,但不在获取请求中)。如果没有,我会收到401未经授权。

这是详细信息

  1. 服务器:本地主机:8080

  2. 路径:oauth /令牌

  3. client-id:clinetId

  4. clinet-secret:clientSecret

{x-www-form-urlencoded值}

  1. 用户名:user@test.com
  2. 密码:passUser
  3. grant_type:密码

这就是我所拥有的:

let myHeader = new Headers({
        "Authorization": "Basic " + btoa("clientId" + ':' + "clientSecret"),
        "Content-Type": "application/x-www-form-urlencoded"
    });


var data = new URLSearchParams();
        data.append('grant_type', 'password');
        data.append('userName', 'user@test.com');
        data.append('password', 'passUser');

const requestOptions = {
        method: 'POST',
        headers: myHeader,

        body: data,
        mode: 'no-cors', // if this is disabled it fails
        withCredentials: true,
        credentials: 'include'
    };

return fetch(`http://localhost:8080/oauth/token`, requestOptions)
.then(handleResponse)
.then(...

响应头看起来像

HTTP/1.1 401 Unauthorized
Date: Thu, 28 Mar 2019 01:50:04 GMT
WWW-Authenticate: Basic realm="oauth2/client"
X-Content-Type-Options: nosniff
X-XSS-Protection: 1; mode=block
Pragma: no-cache
X-Frame-Options: DENY
Vary: Origin
Vary: Access-Control-Request-Method
Vary: Access-Control-Request-Headers
Access-Control-Allow-Origin: http://localhost:3000
Access-Control-Allow-Methods: POST
Access-Control-Allow-Headers: access-control-allow-origin, authorization
Access-Control-Allow-Credentials: true
Access-Control-Max-Age: 1800
Allow: GET, HEAD, POST, PUT, DELETE, TRACE, OPTIONS, PATCH
Content-Length: 0

spring -boot中的安全配置看起来像

@Override
    protected void configure(HttpSecurity http) throws Exception {
        http
                .cors().and()
                .sessionManagement().sessionCreationPolicy(SessionCreationPolicy.STATELESS)
                .and()
                .authorizeRequests()
                .anyRequest()
                .authenticated()
                .and().exceptionHandling().authenticationEntryPoint(restAuthenticationEntryPoint).accessDeniedHandler(new RestAccessDeniedHandler());
    }

    @Bean
    CorsConfigurationSource corsConfigurationSource() {
        CorsConfiguration configuration = new CorsConfiguration();
        configuration.setAllowedOrigins(Arrays.asList("*"));
        configuration.setAllowedMethods(Arrays.asList("GET","POST"));
        UrlBasedCorsConfigurationSource source = new UrlBasedCorsConfigurationSource();
        source.registerCorsConfiguration("/**", configuration);
        return source;
    }

关于我做错了什么或在正确的道路上前进的方向的任何想法都很棒。谢谢。

0 个答案:

没有答案