How to use Spring Security 5 and OAuth2 Client to get refresh tokens and make API calls?

Sean G

I'm currently building a Spring Boot App with Spring Security + OAUth2 protocol.

Here is the Authorization Guide from Spotify I'm following

I'm having trouble understanding how to do steps 2 - 4 of Authorization Code Flow. I was able to get authorization and get a authorization code to exchange for a access and refresh token, but I'm not sure how to get the tokens and then start making API calls.

Reading the Spring documentation got me confused about certain things.

  1. How do I obtain the token? I notice its stored in the URL of my redirect after I login, do I get it using a query parameter or is it stored in an OAuth2ClientService object?
  2. The Authorization Guide states I have to make a POST call to the token endpoint to get the refresh and access token. I assume I'm not doing this with WebClient/RestTemplate since I was able to do a GET request for login using the application properties. If so how do I accomplish this?
  3. How can I then use these tokens to get access to API data? Normally I would use WebClient to make REST API calls if a token wasn't necessary. If I get a token do I proceed how I would normally but with an access token as my query.

Here is my application.properties

#
# OAuth ClientRegistration Properties
#
spring.security.oauth2.client.registration.spotify.client-id=#
spring.security.oauth2.client.registration.spotify.client-secret=#
spring.security.oauth2.client.registration.spotify.provider=spotify-provider
spring.security.oauth2.client.registration.spotify.client-authentication-method=basic
spring.security.oauth2.client.registration.spotify.authorization-grant-type=authorization_code
spring.security.oauth2.client.registration.spotify.redirect-uri=http://localhost:8080/redirect
spring.security.oauth2.client.registration.spotify.scope=user-read-private,user-read-email

#
# OAuth ProviderDetails Properties
#
spring.security.oauth2.client.provider.spotify-provider.authorization-            
uri=https://accounts.spotify.com/authorize?show_dialog=true

spring.security.oauth2.client.provider.spotify-provider.token-  
uri=https://accounts.spotify.com/api/token

spring.security.oauth2.client.provider.spotify-provider.user-info-uri=https://api.spotify.com/v1/me
spring.security.oauth2.client.provider.spotify-provider.user-name-attribute=id

Here is my WebSecurityConfig

@Configuration
@EnableWebSecurity
public class WebSecurityConfig extends WebSecurityConfigurerAdapter {

@Override
protected void configure(HttpSecurity http) throws Exception {

    http.authorizeRequests()
        .antMatchers("/redirect")
        .permitAll()

        .and()

        .authorizeRequests()
        .anyRequest().authenticated()

        .and()

        .oauth2Login()
        .loginPage("/login")
        .permitAll();
     }
 }

Controller

@Controller
public class HomeController {

@Autowired
private OAuth2AuthorizedClientService authorizedClientService;

@GetMapping("/login")
public String getLogin()
{
    return "login";
}

///login/oauth2/code/spotify

@GetMapping("/redirect")
public String getRedirect()
{
    return "redirect";
}

@GetMapping("/home")
public String getHome()
{       
    return "home";
}
}

I'm still a beginner at this, and it's taking me a while to understand so I thank you in advanced for the help.

Sean G

Got it to work. Apparently I was supposed to integrate WebClient with an ExchangeFilterFunction that makes use of the OAuth2AuthorizedClientManager which handles the authorization code exchange for access token and refresh token. I followed and read the documentation until I understood it. Here's the section that helped me the most.

Here are the changes I made to my code...

I added a new config class to integrate the webclient with a exchangefilterfunction.

@Configuration
public class WebClientConfig {

@Bean
public OAuth2AuthorizedClientManager authorizedClientManager(
        ClientRegistrationRepository clientRegistrationRepository,
        OAuth2AuthorizedClientRepository authorizedClientRepository) {

    OAuth2AuthorizedClientProvider authorizedClientProvider = 
            OAuth2AuthorizedClientProviderBuilder.builder()
            .authorizationCode()
            .refreshToken()
            .build();

    DefaultOAuth2AuthorizedClientManager authorizedClientManager =
            new DefaultOAuth2AuthorizedClientManager(
                    clientRegistrationRepository, authorizedClientRepository);

    authorizedClientManager.setAuthorizedClientProvider(authorizedClientProvider);

    return authorizedClientManager;
}


@Bean
public WebClient webClient(OAuth2AuthorizedClientManager authorizedClientManager) {

    ServletOAuth2AuthorizedClientExchangeFilterFunction oauth2Client = 
            new ServletOAuth2AuthorizedClientExchangeFilterFunction(authorizedClientManager);

    oauth2Client.setDefaultClientRegistrationId("spotify");

    return WebClient.builder()
            .apply(oauth2Client.oauth2Configuration())
            .build();
}
}

Then I just used the WebClient how I would regularly without doing OAuth2 in my controller:

@GetMapping("/redirect")
public String getRedirect()
{   
    String resourceUri = "https://api.spotify.com/v1/me/top/artists";

    String body = webClient
            .get()
            .uri(resourceUri)
            .retrieve()
            .bodyToMono(String.class)
            .block();

    System.out.println(body);

    return "redirect";
}

この記事はインターネットから収集されたものであり、転載の際にはソースを示してください。

侵害の場合は、連絡してください[email protected]

編集
0

コメントを追加

0

関連記事

分類Dev

How to use Spring Security 5 and OAuth2 Client to get refresh tokens and make API calls?

分類Dev

OAuth2 security in REST GET API

分類Dev

Migrating from Spring Boot Oauth2 to Spring Security 5

分類Dev

What benefits refresh tokens in OAuth2

分類Dev

Get refresh tokens of Microsoft Graph API with OAuthPrompt

分類Dev

How do you use Google API getRequestHeaders() to get an OAuth2 access token?

分類Dev

Where is an Example Spring Security OAuth2 Client Configuration using XML for Authorization Code?

分類Dev

How to enable /oauth/check_token with Spring Security Oauth2 using XML

分類Dev

Spring Security OAuth2: how to add multiple Security Filter Chain of type ResourceServerConfigurer?

分類Dev

Spring Security OAuth2 | InsufficientAuthenticationException

分類Dev

Spring Security OAuth2:InsufficientAuthenticationException

分類Dev

Spring Boot Security OAuth2 Get Access_token from Cookie

分類Dev

Android client for OAuth2 with Spring

分類Dev

OAuth2を使用したSpring Security 5レストクライアント

分類Dev

API Authentication and use of OAuth2

分類Dev

Spring Security 5とOAuth2クライアントを使用して更新トークンを取得し、API呼び出しを行う方法は?

分類Dev

Refresh tokens in oauth2 should not be replaced when getting a new access token

分類Dev

Spring boot 2.0.3 + Security + Oauth2 autoconfigure

分類Dev

Incremental authorization for Google OAuth2 Sign in with Spring Security

分類Dev

How i can post credentials from rest client to spring security rest api?

分類Dev

spring-security-oauth2-clientとspring-security-oauthの関係は何ですか?

分類Dev

Spring Boot 2、Spring Security 5、@ WithMockUser

分類Dev

How to implement JWT Refresh Tokens in asp.net core web api (no 3rd party)?

分類Dev

Spring Boot + JWT Oauth2:Spring5とSpring <5

分類Dev

Refresh OAuth token with jersey 2 client

分類Dev

Spring Boot SecurityのOAuth2ClientでのSSO

分類Dev

Spring Security OAuth2はJSONを受け入れる

分類Dev

Spring Security OAuth2ピュアリソースサーバー

分類Dev

GoogleでのSpring Security OAuth2ログイン

Related 関連記事

  1. 1

    How to use Spring Security 5 and OAuth2 Client to get refresh tokens and make API calls?

  2. 2

    OAuth2 security in REST GET API

  3. 3

    Migrating from Spring Boot Oauth2 to Spring Security 5

  4. 4

    What benefits refresh tokens in OAuth2

  5. 5

    Get refresh tokens of Microsoft Graph API with OAuthPrompt

  6. 6

    How do you use Google API getRequestHeaders() to get an OAuth2 access token?

  7. 7

    Where is an Example Spring Security OAuth2 Client Configuration using XML for Authorization Code?

  8. 8

    How to enable /oauth/check_token with Spring Security Oauth2 using XML

  9. 9

    Spring Security OAuth2: how to add multiple Security Filter Chain of type ResourceServerConfigurer?

  10. 10

    Spring Security OAuth2 | InsufficientAuthenticationException

  11. 11

    Spring Security OAuth2:InsufficientAuthenticationException

  12. 12

    Spring Boot Security OAuth2 Get Access_token from Cookie

  13. 13

    Android client for OAuth2 with Spring

  14. 14

    OAuth2を使用したSpring Security 5レストクライアント

  15. 15

    API Authentication and use of OAuth2

  16. 16

    Spring Security 5とOAuth2クライアントを使用して更新トークンを取得し、API呼び出しを行う方法は?

  17. 17

    Refresh tokens in oauth2 should not be replaced when getting a new access token

  18. 18

    Spring boot 2.0.3 + Security + Oauth2 autoconfigure

  19. 19

    Incremental authorization for Google OAuth2 Sign in with Spring Security

  20. 20

    How i can post credentials from rest client to spring security rest api?

  21. 21

    spring-security-oauth2-clientとspring-security-oauthの関係は何ですか?

  22. 22

    Spring Boot 2、Spring Security 5、@ WithMockUser

  23. 23

    How to implement JWT Refresh Tokens in asp.net core web api (no 3rd party)?

  24. 24

    Spring Boot + JWT Oauth2:Spring5とSpring <5

  25. 25

    Refresh OAuth token with jersey 2 client

  26. 26

    Spring Boot SecurityのOAuth2ClientでのSSO

  27. 27

    Spring Security OAuth2はJSONを受け入れる

  28. 28

    Spring Security OAuth2ピュアリソースサーバー

  29. 29

    GoogleでのSpring Security OAuth2ログイン

ホットタグ

アーカイブ