整体介绍
当用户登录某个系统的时候,一般都会在系统首页输入用户名和密码等用户信息,一般系统而言,在登陆的过程,后台会默默的调用某个方法,根据用户信息,生成一个字符串token,此过程,可以理解为token的加密
在oauth服务中
public OAuth2AccessToken token(HttpServletRequest request) {
//Http Basic 验证
String clientAndSecret = oAuth2ClientProperties.getClientId() + ":" + oAuth2ClientProperties.getClientSecret();
//这里需要注意为 Basic 而非 Bearer
clientAndSecret = MyConstant.BASIC + " " + Base64.getEncoder().encodeToString(clientAndSecret.getBytes());
//设置请求头信息
HttpHeaders httpHeaders = new HttpHeaders();
httpHeaders.set("Authorization", clientAndSecret);
MultiValueMap<String, String> map = new LinkedMultiValueMap<>();
// ##############################################################
// userNamemo模仿用户登录时候的用户名 //#
map.put("userName", Collections.singletonList("ev")); //#
//password模仿用户登录时候的密码 //#
map.put("passWord", Collections.singletonList("admin")); //#
//# #############################################################
//授权请求信息
map.put("grant_type", Collections.singletonList(oAuth2ProtectedResourceDetails.getGrantType()));
map.put("scope", oAuth2ProtectedResourceDetails.getScope());
//将请求头信息和登陆时候的用户信息封装成HttpEntity参数
HttpEntity httpEntity = new HttpEntity(map, httpHeaders);
//调用配置文件中定义的接口路径(http://localhost:8081/oauth/token)获取token
return restTemplate.exchange(oAuth2ProtectedResourceDetails.getAccessTokenUri(), HttpMethod.POST, httpEntity, OAuth2AccessToken.class).getBody();
}
上面代码块中,调用接口(http://localhost:8081/oauth/token)获取token,该接口是源码中自带的接口,代码如下
@FrameworkEndpoint
public class TokenEndpoint extends AbstractEndpoint {
@RequestMapping(value = "/oauth/token", method=RequestMethod.POST)
public ResponseEntity<OAuth2AccessToken> postAccessToken(Principal principal, @RequestParam Map<String, String> parameters) throws HttpRequestMethodNotSupportedException {
if (!(principal instanceof Authentication)) {
throw new InsufficientAuthenticationException(
"There is no client authentication. Try adding an appropriate authentication filter.");
}
String clientId = getClientId(principal);
ClientDetails authenticatedClient = getClientDetailsService().loadClientByClientId(clientId);
TokenRequest tokenRequest = getOAuth2RequestFactory().createTokenRequest(parameters, authenticatedClient)</