搭建了一个oauth2服务端,对外接口都想用token进行校验,因为oauth2本身提供了/oauth/token接口,可以获取token,但是每次调用有效期都是减少的,需要再主动调用刷新token的接口,有效期才会重置,为了方便第三方厂商的对接,最好是每次调用都重置有效期,网上找了一下,结合几个帖子和自己的想法,有了下面的代码:
@Autowired
private TokenEndpoint tokenEndPoint;
private SimpleAuthenticationManager samgr = new SimpleAuthenticationManager();
@GetMapping("/getToken")
@ResponseBody
public Result<Object> getToken(String username,String password) {
Authentication token = new UsernamePasswordAuthenticationToken(username, password);
Authentication auth = samgr.authenticate(token);
Map<String, String> parameters = new HashMap<String, String>();
parameters.put("client_id", username);
parameters.put("client_secret", password);
parameters.put("grant_type", "password");
parameters.put("username", username);
parameters.put("password", password);
try {
ResponseEntity<OAuth2AccessToken> result = tokenEndPoint.getAccessToken(auth, parameters);
String refreshToken = result.getBody().getRefreshToken().getValue();
parameters.put("grant_type", "refresh_token");
parameters.put("refresh_token", refreshToken);
result = tokenEndPoint.getAccessToken(auth, parameters);
return new ResultUtil<Object>().setData(result.getBody());
} catch (Exception e) {
log.info("获取token失败:"+e.getMessage());
return new ResultUtil<Object>().setErrorMsg(e.getMessage());
}
}
class SimpleAuthenticationManager implements AuthenticationManager {
static final List<GrantedAuthority> AUTHORITIES = new ArrayList<GrantedAuthority>();
static {
AUTHORITIES.add(new SimpleGrantedAuthority("Role"));
}
public Authentication authenticate(Authentication auth)
throws AuthenticationException {
return new UsernamePasswordAuthenticationToken(auth.getName(),
auth.getCredentials(), AUTHORITIES);
}
}
这样每次输入用户名密码即可获取token,且有效期每次调用都重置了。