首页 文章

Spring OAuth2 - CustomAuthenticationProvider登录问题

提问于
浏览
0

我已经设置了一个由Web应用程序使用的授权和资源服务器(所有这些都在Spring MVC 4.3.9中完成),但是在授权服务器上设置了OAuth2RestTemplate和 custom AuthenticationProvider 的请求时出现问题 .

在第一次请求时(当用户登录时),我设置自动装配的OAuth2RestTemplate( I'm using password grant )的用户名和密码,并将请求发送到API的URL,如:

@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服务器中完成的:

@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( I don't have permission to read user details from the LDAP server ,仅对user和pwd进行身份验证) .

问题是 after login ,当我使用自动装配的OAuth2RestTemplate执行其他请求时,再次调用提供程序身份验证方法,并且由于我有访问令牌,因此我不需要这样做,并且我检查了这是在登录时分配的那个),它返回401 Unauthorized .

问题是,我如何验证访问令牌和用户ID,或者如何跳过自定义提供程序中的验证,因为我不再需要进行身份验证?对于以下请求,只应使用访问令牌,或者我错过了什么?

1 回答

  • 0

    因此,我在首次登录时从OAuth2RestTemplate获取访问令牌,然后获取访问令牌,因此我将其作为正常RestTemplate的参数传递(作为?access_token = ...) . 当访问令牌到期时,OAuth2RestTemplate会通过刷新令牌自动获取另一个令牌(为此,您必须为同一客户端设置授权“refresh_token”) . 如果刷新令牌到期,则再次登录并重复循环 .

相关问题