我已经设置了一个要由Web应用程序消费的授权和资源服务器(所有在Spring MVC 4.3.9中完成(,但对于使用Oauth2restTemplate和a <的请求有问题strong>自定义Authentication Provider 在授权服务器上设置。的请求有问题strong>
在第一个请求(用户登录时(,我将自动oauth2restTemplate的用户名和密码设置喜欢:
@Autowired
OAuth2RestOperations restTemplate;
..
public <T> T postEntityNoAuth(String restMethod, Credentials credentials, ParameterizedTypeReference<T> resultType) {
HttpHeaders headers = new HttpHeaders();
headers.setContentType(MediaType.APPLICATION_JSON);
// set your entity to send
HttpEntity entity = new HttpEntity(credentials, headers);
restTemplate.getOAuth2ClientContext().getAccessTokenRequest().set("username", credentials.getUsername());
restTemplate.getOAuth2ClientContext().getAccessTokenRequest().set("password", credentials.getPassword());
ResponseEntity<T> restResult = restTemplate.exchange(authServerURL + restMethod, HttpMethod.POST, entity,
resultType);
OAuth2AccessToken token = restTemplate.getAccessToken();
return restResult.getBody();
}
一切都很好,我得到了一个访问令牌,因为身份验证成功,这是在Auth Server中完成的:
@Configuration
@EnableWebSecurity(debug = false)
public class SecurityConfig extends WebSecurityConfigurerAdapter {
@Autowired
CustomAuthenticationProvider customAuthProvider;
@Autowired
public void configureGlobal(AuthenticationManagerBuilder auth) throws Exception {
auth.authenticationProvider(customAuthProvider);
}
//more code
自定义身份验证提供商可以针对LDAP搜索进行验证,因为我没有UserDetailsservice(我没有权限可以从LDAP服务器读取用户详细信息,只能使用用户和PWD进行身份验证(。
事实是,登录,当我使用自动启用的oauth2resttemplate执行其他请求时,再次调用了提供者身份验证的方法,并且鉴于我不再具有凭据如果我有一个访问令牌,则不需要情况,并且我检查了在登录时分配的访问权限(,它将未经授权返回401。
问题是,鉴于我不再需要对访问权限验证,我如何验证访问令牌和用户ID,或者如何跳过自定义提供商中的验证?对于以下请求,仅应使用访问令牌,或者我缺少某些内容?
所以,我在第一次登录时最终从oauth2resttemplate获取访问令牌,然后获取访问令牌,因此我将其作为正常retstemplate的参数(as?access_token = .. ..(。当访问令牌到期时,OAuth2RestTemplate会通过刷新令牌自动获取另一个(为此,您必须为同一客户端设置授予的" Refresh_token"(。如果刷新令牌到期,则该再次登录并重复循环。