/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这个配置项怎么去做就没人说,就说改变这个配置项能成功.