簡體   English   中英

Spring Security Oauth客戶端-像郵遞員示例的請求

[英]Spring security Oauth client - Request like a postman example

我正在嘗試執行一個執行OAuth流的JUnit測試。

我的客戶建立了一個OAuth提供程序,當我使用郵遞員進行測試時,郵遞員會顯示一個屏幕以填寫憑據,然后郵遞員存儲信息(access_token,id_token和所有JWT信息),就可以了。

參見示例:

在此處輸入圖片說明

我要測試的代碼是:

@Test
    public void getAccessTokenViaSpringSecurityOAuthClient() {
        try {

            OAuth2ProtectedResourceDetails resourceDetails = googleOAuth2Details();

            OAuth2RestTemplate oAuthRestTemplate = new OAuth2RestTemplate(resourceDetails);

            org.springframework.http.HttpHeaders headers = new org.springframework.http.HttpHeaders();
            headers.setContentType(MediaType.APPLICATION_JSON);

            OAuth2AccessToken token = oAuthRestTemplate.getAccessToken();
            System.out.println(oAuthRestTemplate.getResource());
            System.out.println(oAuthRestTemplate.getOAuth2ClientContext());
            System.out.println(token);

            Assert.assertTrue(token != null);

        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    public OAuth2ProtectedResourceDetails googleOAuth2Details() {
        AuthorizationCodeResourceDetails googleOAuth2Details = new AuthorizationCodeResourceDetails();
        googleOAuth2Details.setClientId("xxxxx");
        googleOAuth2Details.setUserAuthorizationUri("https://xxx/yyy/oauth2/authorize");
        googleOAuth2Details.setAccessTokenUri("https://xxx/yyy/oauth2/token");
        googleOAuth2Details.setScope(Arrays.asList("openid"));
        googleOAuth2Details.setPreEstablishedRedirectUri("https://www.getpostman.com/oauth2/callback");
        googleOAuth2Details.setAuthenticationScheme(AuthenticationScheme.query);
        googleOAuth2Details.setClientAuthenticationScheme(AuthenticationScheme.form);

        return googleOAuth2Details;
    }

當我運行任務時,會發生以下異常:

org.springframework.security.oauth2.client.resource.UserRedirectRequiredException: A redirect is required to get the users approval

是否可以測試此流程? 我該怎么做?

異常說明了問題: A redirect is required to get the users approval

Postman隱藏了以下事實:授權過程結束后,授權服務器會將您的瀏覽器redirect_uriredirect_uri或Postman為其命名的Callback URL。 該URL收集授權服務器提供的授權代碼,並請求令牌。
有關更多詳細信息,請參見授權代碼流:

這意味着您不能對授權服務器的授權代碼授予進行“單元測試”。 您需要某種Web服務器來處理授權代碼流的回調。

通過使用@EnableOAuth2Sso與Spring Boot應用程序創建@SpringBootTest ,您可能可以更快地測試授權。 Spring Boot將為您自動配置一個OAuth2RestTemplate ,您可以在JUnit測試中將它@Autowired

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM