redistemplete请求spring security /oauth/token 报401错误,表示没有权限

/oauth/token

这个路径就是为了获取认证中心的token


        System.out.println("函数进来了");

        MultiValueMap<String, String> paramsMap = new LinkedMultiValueMap<>();
        paramsMap.put("grant_type", Collections.singletonList("password"));
        paramsMap.put("scope", Collections.singletonList("all"));
        paramsMap.put("client_id", Collections.singletonList("admin"));
        paramsMap.put("client_secret", Collections.singletonList("123456"));
        paramsMap.put("username", Collections.singletonList("admin"));
        paramsMap.put("password", Collections.singletonList("123456"));

        org.springframework.http.HttpHeaders headers = new org.springframework.http.HttpHeaders();
//        headers.set(HttpHeaders.CONTENT_TYPE, "application/x-www-form-urlencoded; charset=utf-8");
//        headers.set(HttpHeaders.AUTHORIZATION, "'username':'admin','password':'123456'");
        HttpEntity<MultiValueMap<String,String>> httpEntity = new HttpEntity<MultiValueMap<String,String>>(paramsMap,headers);

        restTemplate.setErrorHandler(new DefaultResponseErrorHandler(){
            @Override
            public void handleError(ClientHttpResponse clientHttpResponse) throws IOException {
                //只要重写此方法,不去抛出HttpClientErrorException异常即可
                HttpStatus statusCode = clientHttpResponse.getStatusCode();
                System.out.println("错误码 = "+statusCode);
            }
        });
//        JSONObject response = template.postForObject(url, paramsMap, JSONObject.class);
        JSONObject response = restTemplate.exchange("http://localhost:8085/uac/oauth/token",HttpMethod.POST, httpEntity, JSONObject.class,new Object[]{}).getBody();
        System.out.println(response.toString());
        System.out.println(response.get("access_token"));

大坑来了

有很多小伙伴都出来了401错误,表示没有权限.
首先,这上面的代码是没有错了的,错就错在了认证中心里
在/oauth/token 的请求中我们指定了client_id和client_secret,所以会走ClientCredentialsTokenEndpointFilter,此时需要我们配置支持allowFormAuthenticationForClients。

@Configuration
@EnableAuthorizationServer
public class AuthorizationServer extends AuthorizationServerConfigurerAdapter {
    @Override
    public void configure(AuthorizationServerSecurityConfigurer security){
        security
                .tokenKeyAccess("permitAll()")                    //oauth/token_key是公开
                .checkTokenAccess("permitAll()")                  //oauth/check_token公开
                .allowFormAuthenticationForClients()				//表单认证(申请令牌)
        ;
    }

}

如果还有错误,是其他原因,反正肯定不是走错了filter的原因了.

当然如果你没有以上配置,其实也是可以的,我尝试在postman测试的时候我的认证中心只有以下配置:

    @Override
    public void configure(AuthorizationServerSecurityConfigurer security) throws Exception {
        security
                .tokenKeyAccess("isAuthenticated()");
    }

这样子上面肯定会报权限失败,需要配置Authorization
在这里插入图片描述
在这里插入图片描述
配置这个选项大概意思就是,我们通过密码模式,然后要进行授权的认证

我在postman测试成功了,但是我在RestTemplate发送测试的时候模拟同样的配置没成功,我也不清楚,可能是我没配置成功.

网上出现401错误大多也是这两种解决办法,用代码改变Authorization这个配置项怎么去做就没人说,就说改变这个配置项能成功.

  • 0
    点赞
  • 3
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
针对前端请求OAuth框架自带的/oauth/token接口跨域问题,可以使用Spring Boot的CORS(跨域资源共享)来解决。CORS是一种机制,允许浏览器在发送AJAX请求时,跨域访问其他域下的资源。通过配置CORS,可以允许前端请求/oauth/token接口跨域访问。 在后台使用Spring Cloud框架,包括Eureka、Gateway,可以配置Hystrix简单实现和跨域功能。此外,还可以使用OAuth2来实现认证和授权,使用JWT token进行身份验证。 因此,可以通过在Spring Boot中配置CORS解决前端请求OAuth框架自带的/oauth/token接口跨域问题。<span class="em">1</span><span class="em">2</span><span class="em">3</span> #### 引用[.reference_title] - *1* *2* [Springboot通过cors解决跨域问题(解决spring security oath2的/oauth/token跨域问题)](https://blog.csdn.net/jazz2013/article/details/116591240)[target="_blank" data-report-click={"spm":"1018.2226.3001.9630","extra":{"utm_source":"vip_chatgpt_common_search_pc_result","utm_medium":"distribute.pc_search_result.none-task-cask-2~all~insert_cask~default-1-null.142^v93^chatsearchT3_2"}}] [.reference_item style="max-width: 50%"] - *3* [前端(ElementUI)后端(Spring Cloud Eureka、Gateway、OAuth2、JWTtoken、RSA)](https://download.csdn.net/download/qq_24296051/87646211)[target="_blank" data-report-click={"spm":"1018.2226.3001.9630","extra":{"utm_source":"vip_chatgpt_common_search_pc_result","utm_medium":"distribute.pc_search_result.none-task-cask-2~all~insert_cask~default-1-null.142^v93^chatsearchT3_2"}}] [.reference_item style="max-width: 50%"] [ .reference_list ]
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值