Azure-Samples / ms-identity-java-webapp

A Java web application calling Microsoft graph that is secured using the Microsoft identity platform
MIT License
118 stars 105 forks source link

Access Token expired after 1 hour and UserRedirectRequiredException thrown #69

Closed Ranbir-Sinha closed 3 years ago

Ranbir-Sinha commented 3 years ago

The OAuth2 SSO implementation works perfectly with "@EnableOAuth2Sso" but after an hour of activity, the token expires and the OAuth2RestTemplate is unable to refresh access token, resulting in the following exception.

org.springframework.security.oauth2.client.resource.UserRedirectRequiredException: A redirect is required to get the users approval
    at org.springframework.security.oauth2.client.token.grant.code.AuthorizationCodeAccessTokenProvider.getRedirectForAuthorization(AuthorizationCodeAccessTokenProvider.java:359)
    at org.springframework.security.oauth2.client.token.grant.code.AuthorizationCodeAccessTokenProvider.obtainAccessToken(AuthorizationCodeAccessTokenProvider.java:205)
    at org.springframework.security.oauth2.client.token.AccessTokenProviderChain.obtainNewAccessTokenInternal(AccessTokenProviderChain.java:148)
    at org.springframework.security.oauth2.client.token.AccessTokenProviderChain.obtainAccessToken(AccessTokenProviderChain.java:121)
    at org.springframework.security.oauth2.client.OAuth2RestTemplate.acquireAccessToken(OAuth2RestTemplate.java:221)
    at org.springframework.security.oauth2.client.OAuth2RestTemplate.getAccessToken(OAuth2RestTemplate.java:173)

I tried few suggestion listed on stackoverflow (related to filter registration) and here but none of them worked.

Do you have a solution to this problem?

Ranbir-Sinha commented 3 years ago

It happened because "offline_access" was not present in the scope. Without this scope, app cannot receive refresh token and the access token usually expires in one hour. Refresh tokens are long-lived. The app can get new access tokens as older ones expire.

Ranbir-Sinha commented 3 years ago

Add "offline_access" in the scope and get admin consent for this scope in the Azure app registration.