刚开始研究的时候我在好奇,为什么不直接/oauth/token来获取token,而要使用refresh_token来获取呢?
因为/oauth/token需要code参数(授权码模式),但是code是一次性的参数,无法获取,所以就需要refresh_token来获取AccessToken了。
使用refresh_token需要配置userDetailsService
/**自定义UserDetailsService **/
@Component
public class AuthUserDetailsService implements UserDetailsService {@Autowired
private UserInfoMapper userInfoMapper;
@Override
public UserDetails loadUserByUsername(String username) throws UsernameNotFoundException {
UserInfo userInfo = userInfoMapper.findByUserName(username);
List<GrantedAuthority> grantedAuths = new ArrayList<>();
grantedAuths.add(new SimpleGrantedAuthority("ROLE_USER"));
return new User(username, userInfo.getUserPwd(), grantedAuths);
}}
/*** 认证服务器配置
*/
@Configuration
@EnableAuthorizationServer
public class AuthServerConfig extends AuthorizationServerConfigurerAdapter{
@Autowired
private AuthenticationManager authenticationManager;
@Autowired
private UserDetailsService userDetailsService;
……@Override
public void configure(AuthorizationServerEndpointsConfigurer endpoints) throws Exception {
endpoints.authenticationManager(authenticationManager).userDetailsService(userDetailsService);
}
……
}
另外,再包装一下token失效后的返回错误信息
@Configuration@EnableResourceServer
public class ResourceServerConfig extends ResourceServerConfigurerAdapter {
……
@Override
public void configure(ResourceServerSecurityConfigurer resources) throws Exception {
super.configure(resources);
resources.authenticationEntryPoint(new AuthEntryPoint());
}
}/**重写这个commence方法**/
public class AuthEntryPoint extends OAuth2AuthenticationEntryPoint {
private static final Logger LOG = LoggerFactory.getLogger(AuthEntryPoint.class);
private WebResponseExceptionTranslator exceptionTranslator = new DefaultWebResponseExceptionTranslator();
@Override
public void commence(HttpServletRequest request, HttpServletResponse response, AuthenticationException authException) throws IOException, ServletException {
try {
ResponseEntity<?> result = exceptionTranslator.translate(authException);
if (result.getStatusCode() == HttpStatus.UNAUTHORIZED) {
response.setCharacterEncoding("UTF-8");
response.setContentType("application/json; charset=utf-8");
PrintWriter writer = response.getWriter();
writer.append(HttpStatus.UNAUTHORIZED.toString());
} else {
super.commence(request,response,authException);
}
} catch (Exception e) {
LOG.error("failed to commence: {}", e.getMessage(), e);
}
}
}