Azure AD B2C Refresh Token Revoked 403 - azure

Good morning everyone,
I Have set up an App Service in Azure and added Authentication via Azure AD B2C. So far so good everything works fine. After 1 hour though, when the token expires, I try to refresh it but then I get an error back that the refresh token has been revoked. What goes wrong here ? I have set up the backend like explained in this post : and when logging in I pass the additional parameter like so :
user = await Manager.CurrentClient.LoginAsync(currentContext,MobileServiceAuthenticationProvider.WindowsAzureActiveDirectory,new Dictionary<string, string>() { { "response_type", "code id_token" } });
This is my refresh code :
user = await Manager.CurrentClient.RefreshUserAsync();
This is the error I am getting
{Microsoft.WindowsAzure.MobileServices.MobileServiceInvalidOperationException:
Refresh failed with a 403 Forbidden error. The refresh token was
revoked or expired. --->
Microsoft.WindowsAzure.MobileServices.MobileServiceInvalidOperationException:
You do not have permission to view this directory or page. at
Microsoft.WindowsAzure.MobileServices.MobileServiceHttpClient+d__24.MoveNext
() [0x001ec] in :0
Am I missing something here ?
Thank you
EDIT :
Here is a Screenshot of the Settings in the Portal
EDIT 2 :
Here is an error form the server logs when trying to refresh the token :
EDIT 3 :
And here the Application Log from the webserver for the given request :
2017-01-18T15:08:33 PID[6344] Verbose Received request: GET
https://api.near.lu/.auth/refresh 2017-01-18T15:08:33 PID[6344]
Verbose JWT validation succeeded. Subject:
'sid:453a1ad2710466bc9873240e888d8b91', Issuer:
'https://api.near.lu/'. 2017-01-18T15:08:33 PID[6344] Warning The
refresh request issued by sid:453a1ad2710466bc9873240e888d8b91 (SID:
ac22f7309036f0c07a54b1299b9601ef) failed because no refresh tokens
were found in the token store. 2017-01-18T15:08:33 PID[6344]
Information Sending response: 403.80 Forbidden 2017-01-18T15:08:34
PID[6344] Verbose Received request: GET
https://api.near.lu/.auth/login/aad?response_type=code%20id_token
2017-01-18T15:08:34 PID[6344] Verbose Downloading OpenID
configuration from
https://login.microsoftonline.com/nearauth.onmicrosoft.com/v2.0/.well-known/openid-configuration?p=B2C_1_Default
2017-01-18T15:08:36 PID[6344] Verbose Downloading OpenID issuer
keys from
https://login.microsoftonline.com/nearauth.onmicrosoft.com/discovery/v2.0/keys?p=b2c_1_default
2017-01-18T15:08:37 PID[6344] Information Redirecting:
https://login.microsoftonline.com/nearauth.onmicrosoft.com/oauth2/v2.0/authorize?response_type=code+id_token&redirect_uri=https%3A%2F%2Fapi.near.lu%2F.auth%2Flogin%2Faad%2Fcallback&client_id=c4c15bfb-eac4-4cdc-861f-eb01594e19d2&scope=openid+profile+email&response_mode=form_post&state=redir%3D%26b2cPolicy%3D&p=b2c_1_default&nonce=9e243549b62f49878cc370048c6effa9_20170118151334
2017-01-18T15:08:39 PID[6344] Verbose Received request: POST
https://api.near.lu/.auth/login/aad/callback 2017-01-18T15:08:39
PID[6344] Error An error of type 'unauthorized_client' occurred
during the login process: 'AADB2C90057: The provided application is
not configured to allow the OAuth Implicit flow. Correlation ID:
8336662f-8847-4f8b-bb37-6925a5d3e264 Timestamp: 2017-01-18 15:08:38Z '
2017-01-18T15:08:39 PID[6344] Information Sending response: 401.73
Unauthorized
EDIT 4:
This is the log of a successfull login :
2017-01-18T19:10:14 PID[6344] Verbose Received request: GET
https://api.near.lu/.auth/login/aad?response_type=code%20id_token
2017-01-18T19:10:14 PID[6344] Information Redirecting:
https://login.microsoftonline.com/nearauth.onmicrosoft.com/oauth2/v2.0/authorize?response_type=code+id_token&redirect_uri=https%3A%2F%2Fapi.near.lu%2F.auth%2Flogin%2Faad%2Fcallback&client_id=c4c15bfb-eac4-4cdc-861f-eb01594e19d2&scope=openid+profile+email&response_mode=form_post&state=redir%3D%26b2cPolicy%3D&p=b2c_1_default&nonce=817be561f67343688001637fa7808690_20170118191514
2017-01-18T19:10:30 PID[6344] Verbose Received request: POST
https://api.near.lu/.auth/login/aad/callback 2017-01-18T19:10:30
PID[6344] Verbose JWT validation succeeded. Subject:
'1eaf9f41-1562-4ac9-9538-b893c9123087', Issuer:
'https://login.microsoftonline.com/07407dc1-946a-4afc-9186-84e6023ba814/v2.0/'.
2017-01-18T19:10:30 PID[6344] Verbose Calling into external HTTP
endpoint POST
https://login.microsoftonline.com/nearauth.onmicrosoft.com/oauth2/v2.0/token.
2017-01-18T19:10:32 PID[6344] Information Login completed for 'aget'.
Provider: 'aad'. 2017-01-18T19:10:32 PID[6344] Verbose Writing
'AppServiceAuthSession' cookie for site 'api.near.lu'. Length: 792.
2017-01-18T19:10:32 PID[6344] Information Redirecting:
https://api.near.lu/.auth/login/done#token=%7B%22authenticationToken%22%3A%22ey--REMOVED PART OF THE TOKEN--%22%2C%22user%22%3A%7B%22userId%22%3A%22sid%3Aed01ed7507f147976aa1704783267861%22%7D%7D
2017-01-18T19:10:33 PID[6344] Verbose Received request: GET
https://api.near.lu/.auth/login/done 2017-01-18T19:10:33 PID[6344]
Information Sending response: 200.0 OK
This is the error log i get when I try to refresh immediatley after logging in :
2017-01-23T10:55:06 PID[6344] Verbose Received request: POST
https://api.near.lu/.auth/refresh 2017-01-23T10:55:06 PID[6344]
Verbose JWT validation succeeded. Subject:
'sid:ed01ed7507f147976aa1704783267861', Issuer:
'https://api.near.lu/'. 2017-01-23T10:55:06 PID[6344] Warning The
refresh request issued by sid:ed01ed7507f147976aa1704783267861 (SID:
9a6c2ee324a092937c5e2f953803e662) failed because no refresh tokens
were found in the token store. 2017-01-23T10:55:06 PID[6344]
Information Sending response: 403.80 Forbidden
Which is weird, as it can be seen in the above picture the token store is enabled...

The problem could be that your current App Service Authentication / Authorization setup is not configured to support token refresh. A simple way to confirm this would be to enable Application Logging and look at the warning messages in the application log stream when a refresh operation fails. More details on application logging can be found here: https://learn.microsoft.com/en-us/azure/app-service-web/web-sites-enable-diagnostic-log
See the following blog post (which I wrote) to learn more about how to update your Authentication / Authorization settings to support token refresh: https://cgillum.tech/2016/08/10/app-service-auth-and-azure-ad-b2c-part-2/#refresh. The short version is that you need to:
create an app key in your B2C app registration and set that as the client secret in your Authentication / Authorization "Advanced" settings for AAD in the portal.
Request the offline_access scope when logging in. This ensures you get a refresh token from AAD B2C when the user logs in.
Your login code should look like the following:
user = await Manager.CurrentClient.LoginAsync(
currentContext,
MobileServiceAuthenticationProvider.WindowsAzureActiveDirectory,
new Dictionary<string, string>() { { "scope", "openid offline_access" } });

To use the refresh user, we have to store the refresh token to the app service token store.
You can check whether there are refresh token via using the request below:
Get:https://{yourMoibleAppName}.azurewebsites.net/.auth/me
X-ZUMO-AUTH: {accessToken}
The access token you can get from user.MobileServiceAuthenticationToken.
If there is no refresh token returned, you can check whether following requirements are satisfied:
the token store is enable
the response_type of request contains code
Developers doesn't revoke the access_token, refresh_token, user permission
And all settings well, however the the app still get the 403 error, we should prompt user to login again(refer to Refreshing user logins in App Service Mobile Apps).
And to avoid misunderstanding, when you specify you were using Azure AD B2C tenant, would you mind sharing the detail steps you protected the mobile service?
Update( able to reproduce this issuing using the b2c app which register this way)

Related

Request_ResourceNotFound in azure issue

I am trying to upload document to OneDrive through my application. When i am trying to login Onedrive i am getting below error message.
(1002144-A1) Onedrive upload failed with exception:
Code: Request_ResourceNotFound
Message: Resource 'demo#domain.com' does not exist or one of its queried reference-property objects are not present.
My application is a multitenant application. Can anyone have an idea about this issue.
• You are getting this error because the required scopes and the permissions for the Azure AD app registration are not correct as well as there might be query formatting errors in your ‘Onedrive’ request from your application. For that purpose, kindly ensure the below settings are configured aptly in your application: -
a) Client ID and Key (client secret) as registered with Azure Active Directory (AAD)
b) Authorization code received from OAuth 2 authorization code flow
c) OneDrive for Business API endpoint URL
d) Access token for the OneDrive for Business resource
e) Refresh token to generate additional access tokens when the current token expires.
Thus, follow the steps as shown in the manner as above. Kindly get an authorization code as below: -
GET https://login.microsoftonline.com/common/oauth2/v2.0/authorize?client_id={client_id}&scope={scope}&response_type=code&redirect_uri={redirect_uri}
Then ensure to redeem the code for access tokens as below upon successful authentication and authorization wherein the response will be as below: -
Response: -
https://myapp.com/auth-redirect?code=df6aa589-1080-b241-b410-c4dff65dbf7c
Redeem the code for access tokens as below: -
POST https://login.microsoftonline.com/common/oauth2/v2.0/token
Content-Type: application/x-www-form-urlencoded
client_id={client_id}&redirect_uri={redirect_uri}&client_secret={client_secret}
&code={code}&grant_type=authorization_code
Then, further get a new access token or refresh token as below wherein the response should be as follows: -
Refresh token redemption: -
POST https://login.microsoftonline.com/common/oauth2/v2.0/token
Content-Type: application/x-www-form-urlencoded
client_id={client_id}&redirect_uri={redirect_uri}&client_secret={client_secret}
&refresh_token={refresh_token}&grant_type=refresh_token
Response: -
{
"token_type":"bearer",
"expires_in": 3600,
"scope": "wl.basic onedrive.readwrite wl.offline_access",
"access_token":"EwCo...AA==",
"refresh_token":"eyJh...9323"
}
As you can see above, upon successful authentication via Microsoft Graph as the orchestrator, you get the refresh token, access token and the valid scopes for it too. Also, please find the below snapshot which shows the scopes required for this: -
Also, do ensure that the application as an entity exists in the Azure AD app registration for the authentication to Onedrive API to happen as below: -
For more detailed information, kindly refer the below links: -
https://learn.microsoft.com/en-us/onedrive/developer/rest-api/getting-started/graph-oauth?view=odsp-graph-online
https://github.com/microsoftgraph/microsoft-graph-docs/issues/3539

AAD B2C returned "AADB2C90090: The provided JWE is not a valid 5 segment token." when calling token API

I am working a POC to verify the migration of our Signup & Signup flow to Azure AD B2C. I have successfully called the API authorize to get the access token and id token. Then I tried to call /token to refresh the token according to document , however I got the error message below.
AADB2C90090: The provided JWE is not a valid 5 segment token.\r\nCorrelation ID: ae943eb7-9290-4fd5-aeac-d56411d803c7\r\nTimestamp: 2022-10-26 07:13:40Z\r\n
Following is the url I used to get access token in Browser.
GET https://{tenant}.b2clogin.com/{tenant}.onmicrosoft.com/oauth2/v2.0/authorize?p=B2C_1_signupsignin1&client_id=7adbb5f8-17d2-4dfa-94cd-5ab1cbc9f425&nonce=defaultNonce&redirect_uri=https://jwt.ms&scope=openid offline_access&response_type=code+id_token&prompt=login
Following is the screenshot I used to call token API in Postman.
POST /{tenant}.onmicrosoft.com/B2C_1_signupsignin1/oauth2/v2.0/token HTTP/1.1
Host: {tenant}.b2clogin.com
Content-Type: application/x-www-form-urlencoded
Content-Length: 1971
grant_type=authorization_code&client_id=7adbb5f8-17d2-4dfa-94cd-5ab1cbc9f425&code=eyJraWQiOiJjcGltY29yZV8wOTI1MjAxNSIsInZlciI6IjEuMCIsInppcCI6IkRlZmxhdGUiLCJzZXIiOiIxLjAifQ..n8murSwIYYseViQm.WluJ_gU8aUQd1PPadPik4ODSso4KpKAu8geA5NmAlkbieJPVZb30MJSHGOiUsrxfwu4BoV69bshD7URJeVNFzfqPsCjBhpYDyeL8x0uUZIJwDQ7DTiflw8A4LbYf-SzjluqbfSqDwQFGyQvKesgsrnZzyxg9AnLiL1NoBW27Kd3ZcX3i1BHKr8c--qOyxbz8DtUyIzkJGcOq79wIQZRnDCr1_xPo6EhzOi59TlEIfJhzR4qfgLm3tlgK8zDaUY5Zf3a89olfkmpvrjS84vsfDyyWM4UZe_6MpymNQFe-6Q-fJRmWqdmqdvljaDykP2ZSZJS6jHkdmU9t9aYCTWPB4JgnN1PleQDzRK-MR9WPJ5ULoxmp2VOZ_YFdY94MOGEW8c_IeNGVuPRRC8jXEaQnEWA_3Fs5tzuNe4UjQUxRTTjNeZERb1MHFPk2YGZRc4CshvqvobuGQ2fVNKFHA8JvW9Qt6Xibw0gfY8D0tTZuOP6IxPwhFSWXa5nX4j_lDeFFxhTKA38CALXQ1FVWvHZmzYhB_yMYq44jdG46lpQYB4rV9CFIBvFzJ940EPH6LpOPAnLQzLNm6zqtsVKUoB49dXE2hapIbD5LHsoNoZYeQhu8qJdhxg.8PfqgqgrubNchCs9OxHQQA%26id_token%3DeyJ0eXAiOiJKV1QiLCJhbGciOiJSUzI1NiIsImtpZCI6Ilg1ZVhrNHh5b2pORnVtMWtsMll0djhkbE5QNC1jNTdkTzZRR1RWQndhTmsifQ.eyJleHAiOjE2NjY3NzE0MDUsIm5iZiI6MTY2Njc2NzgwNSwidmVyIjoiMS4wIiwiaXNzIjoiaHR0cHM6Ly9iZW5ueXpob3UuYjJjbG9naW4uY29tLzUzYjRjYmY0LWU1NDYtNDU2ZS04ZTI0LTlhM2RlOGQ3ZTljYy92Mi4wLyIsInN1YiI6ImUyN2YwZGU0LTMxODItNDZlYi1iMjYzLTdkMThkOGY4OWE1OCIsImF1ZCI6IjdhZGJiNWY4LTE3ZDItNGRmYS05NGNkLTVhYjFjYmM5ZjQxNSIsIm5vbmNlIjoiZGVmYXVsdE5vbmNlIiwiaWF0IjoxNjY2NzY3ODA1LCJhdXRoX3RpbWUiOjE2NjY3Njc4MDUsIm9pZCI6ImUyN2YwZGU0LTMxODItNDZlYi1iMjYzLTdkMThkOGY4OWE1OCIsImNvdW50cnkiOiJDaGluYSIsIm5hbWUiOiJLYXJsYSIsImVtYWlscyI6WyJrYXJsYS56aGFuZ0BtYWlzY3JtLmNvbSJdLCJ0ZnAiOiJCMkNfMV9zaWdudXBzaWduaW4xIiwiY19oYXNoIjoiOU1Oc2k5b05KQzZYWjRVSkFvS0N6dyJ9.RckgULrCBdXzw-7-VYgmB7k0Ghfg1jRMsJF8_1oxLbNXTOcZDe9grbJKcpWoesHp5L5_bVfAa1HQOFzMlmPwPPvM0a2yl1zT8UQzJ_a8W4EHkA4Ao3Xt3osbjoBhRh65Nu4fCVGHswPgxZNAR_N7jr4pR6Pf4PllmKpne-bw7onz_HjpT4ulyyq8jNZye3YokPZh0ha9LaV_19NiwfnVAR451lqfugKs2DWfseXbyGlOnjFCl_UHQDOxa1_ZUTmvF1JUgff2VAOmW2925RMQopzfDjCUEvwZMLr8pKTystErvUR6a8itRAKIFwbfEh3en8PqBun9T89-5qKmmN4NTQ&client_secret=h888Q~Jlg97L2ngl6GHpaKqS6FmkLygeTVY7Eb-h
I tried to search the error message but only get two discussion threads in Stackoverflow, however no useful info found.
https://stackoverflow.com/search?q=AADB2C90090%3A+The+provided+JWE+is+not+a+valid+5+segment+token.
I tried to reproduce the same in my environment and got the same error as below:
To generate the access token, ID token and code in the browser I used the below parameters:
GET https://Tenant.b2clogin.com/Tenant.onmicrosoft.com/B2C_1_testuserflow/oauth2/v2.0/authorize?
client_id=37cd7fca-ea8f-4300-XXXX-XXXXXXXXXX
&response_type=code+id_token
&redirect_uri=https://jwt.ms
&response_mode=fragment
&scope=openid
&state=12345
The error usually occurs if you pass invalid code value. To resolve the error, make sure to copy only the code value not with id token.
I am able to call /token to refresh the token successfully like below:

Office365: Refreshing access token results with "AADSTS9002313" invalid_grant execption

From last couple of weeks we have few clients complaining that our app is auto revoking Office365 oauth every 1 hour. This is the typical behiviour as access token have validity of 1 hour, so our app is designed to auto refresh the access token using refresh token captured during oauth.
This seems to be not working for atleast few customers from last few weeks. Below exception is thrown back by Office365 token api - https://login.windows.net/common/oauth2/token
{"error":"invalid_grant","error_description":"AADSTS9002313: Invalid request. Request is malformed or invalid.\r\nTrace ID: 7f80c2c3-41bc-41bd-8304-b56969c83a00\r\nCorrelation ID: 5a08714a-1e7d-4f32-814d-146bc721e8ab\r\nTimestamp: 2020-10-12 05:42:11Z","error_codes":[9002313],"timestamp":"2020-10-12 05:42:11Z","trace_id":"7f80c2c3-41bc-41bd-8304-b56969c83a00","correlation_id":"5a08714a-1e7d-4f32-814d-146bc721e8ab","error_uri":"https://login.windows.net/error?code=9002313"}
Here, the error code '9002313' states there is some issue related to auth parameters especially 'client_id' of our azure app. (reference)
Below data is sent to fetch new access token
client_id (related to azure app)
client_secret (related to azure app)
grant_type = 'refresh_token'
refresh_token
Edit 1: Update token endpoint to v2.0
Request URI
POST https://login.microsoftonline.com/common/oauth2/v2.0/token
Request Body
client_id=<client-id> &scope=https://outlook.office365.com/Calendars.ReadWrite https://outlook.office365.com/Contacts.ReadWrite https://outlook.office365.com/Mail.ReadWrite &refresh_token=OAAABAAAAiL9Kn2Z27UubvWFPbm0gLWQJVzCTE9UkP3pSx1aXxUjq... &grant_type=refresh_token &client_secret=<client-secret>
Reponse Body
{"error":"invalid_grant","error_description":"AADSTS9002313: Invalid request. Request is malformed or invalid.\r\nTrace ID: 4447c69e-09d6-4a00-8dfe-735106d71200\r\nCorrelation ID: 1820e135-a511-4516-99d9-b6cebb342eb2\r\nTimestamp: 2020-10-13 03:39:37Z","error_codes":[9002313],"timestamp":"2020-10-13 03:39:37Z","trace_id":"4447c69e-09d6-4a00-8dfe-735106d71200","correlation_id":"1820e135-a511-4516-99d9-b6cebb342eb2","error_uri":"https://login.microsoftonline.com/error?code=9002313"}
Your authority is old and you missed the scope in the request body(if use the v2.0 endpoint), if you want to get a new access token for O365 with the refresh token, use the sample request below.
Request url:
POST https://login.microsoftonline.com/common/oauth2/v2.0/token
Request body:
client_id=<client-id>
&scope=https://outlook.office365.com/.default
&refresh_token=OAAABAAAAiL9Kn2Z27UubvWFPbm0gLWQJVzCTE9UkP3pSx1aXxUjq...
&grant_type=refresh_token
&client_secret=<client-secret>
For more details, refer to the doc - Refresh the access token.
Update:
I test it for you, it works on my side. Make sure you also get the refresh token with the v2.0 endpoint, see here.
The permissions for my app:
Test to get a new access token in the postman after getting the refresh token.

Cannot Authenticate with Azure AD, losing cookie and redirect is showing no permissions

Really having a nightmare with this in all honesty.
I have the repo from https://github.com/Azure-Samples/active-directory-aspnetcore-webapp-openidconnect-v2/tree/master/1-WebApp-OIDC which should set up Azure AD and Open Id with ASP Core 3.0.
I am using Azure to deploy an application using ASP Core 3.0 MVC.
I have implemented the above repo into my solution which should take care of everything in startup.cs, my localhost is working absolutely fine.
Start up is the same as the 1-WebApp-OIDC solution (other than logging and DI related registrations).
The app is registered in the Azure portal, the tenant id and client id are fine, correct redirects are in there as well.
App Service Auth is turned off also (I read this could be an issue as many had solved this by turning it off).
Also Home, Index controller has [Authorize] attribute on.
Now when it comes to deployment I keep getting;
You do not have permission to view this directory or page.’
On my /signin-oidc redirect url.
Just to note I was getting this message even when not using the openidconnect class library.
If I go to https://mysite.azurewebsites.net/.auth/login/aad/callback -
I get 'You have successfully logged in' page, with the 'RETURN TO THE WEBSITE' link.
Once clicked, back to the same message as above.
I'm also getting a token from https://mysite.azurewebsites.net/.auth.me - have read .NET Core app with Azure App Service Authentication but he was able to get past the login and just wasn't getting the right claim identities.
Now .. when I check in Azure at the domain's sign ins, it shows as success.
I then log into Kudu to check the logs (in .../application) with contradictions.
The diagnostics logs say:
2020-02-01 10:32:19.279 +00:00 [Debug] Microsoft.AspNetCore.Routing.EndpointRoutingMiddleware: Request did not match any endpoints
2020-02-01 10:32:19.279 +00:00 [Debug] Microsoft.AspNetCore.Authentication.Cookies.CookieAuthenticationHandler: AuthenticationScheme: AzureADCookie was not authenticated.
The other set of logs which generate a guid for each session show:
2020-02-01T10:32:01 PID[3780] Verbose Received request: GET https://mysite.azurewebsites.net/
2020-02-01T10:32:01 PID[3780] Information Redirecting: https://login.windows.net/89f3808f-0cff-4297-b17a-313007c7b8a6/oauth2/authorize?response_type=id_token&redirect_uri=https%3A%2F%2Fmysite.azurewebsites.net%2F.auth%2Flogin%2Faad%2Fcallback&client_id=f70bd4d6-3cb3-463e-9fca-974053e2f177&scope=openid+profile+email&response_mode=form_post&nonce=6f1c5c8d07f5481193439dd95c3cf03b_20200201103701&state=redir%3D%252F
2020-02-01T10:32:02 PID[3780] Verbose Received request: POST https://mysite.azurewebsites.net/.auth/login/aad/callback
2020-02-01T10:32:02 PID[3780] Verbose JWT validation succeeded. Subject: 'C6JYPu8NBYT8sC-s6G33w6sxNkct28RdeeyfL1SndjA', Issuer: 'https://sts.windows.net/89f3808f-0cff-4297-b17a-313007c7b8a6/'.
2020-02-01T10:32:02 PID[3780] Information Login completed for 'DanADLogin#company.com'. Provider: 'aad'.
2020-02-01T10:32:02 PID[3780] Verbose Writing 'AppServiceAuthSession' cookie for site 'mysite.azurewebsites.net'. Length: 920.
2020-02-01T10:32:02 PID[3780] Information Redirecting: https://mysite.azurewebsites.net/
2020-02-01T10:32:02 PID[3780] Verbose Received request: GET https://mysite.azurewebsites.net/
2020-02-01T10:32:02 PID[3780] Verbose Found 'AppServiceAuthSession' cookie for site 'mysite.azurewebsites.net'. Length: 920.
2020-02-01T10:32:02 PID[3780] Verbose Authenticated DanADLogin#company.com successfully using 'Session Cookie' authentication.
2020-02-01T10:32:19 PID[3780] Verbose Received request: POST https://mysite.azurewebsites.net/signin-oidc
2020-02-01T10:32:19 PID[3780] Verbose Found 'AppServiceAuthSession' cookie for site 'mysite.azurewebsites.net'. Length: 920.
2020-02-01T10:32:19 PID[3780] Information Sending response: 403.60 Forbidden
2020-02-01T10:32:19 PID[3780] Warning Cross-site request forgery detected for user 'DanADLogin#company.com' from referer 'login.microsoftonline.com'!
2020-02-01T10:32:19 PID[3780] Verbose Received request: GET https://mysite.azurewebsites.net/favicon.ico
2020-02-01T10:32:19 PID[3780] Verbose Found 'AppServiceAuthSession' cookie for site 'mysite.azurewebsites.net'. Length: 920.
2020-02-01T10:32:19 PID[3780] Verbose Authenticated DanADLogin#company.com successfully using 'Session Cookie' authentication.
Clearly the cookie is being lost somewhere, I've read about a redirect loop that interferes with cookies from core and cookies from open id.
I’ve exhausted stack overflow and other articles all to no avail.
There is one issue that is very similar but using Google Auth - Requesting refresh token fails.No refresh tokens were found in the token store. This does not work for AAD.
I’m genuinely out of what to do, I have persevered long enough and I think I may go mad if I spend another day on this. I'm sure it cannot be this difficult 😅.
Any help or guidance would be greatly appreciated.
Clearly a lot of interest lol ...
This was actually nothing to do with Azure AD or OpenId at all.
It was a db call in my data layer that was calling an external db in my home controller (not in Azure) that was throwing all these issues.

Requesting Azure App Service authentication refresh tokens

I struggle with getting the refresh tokens to work for certain authentication providers in Azure App Service using a Mobile App. CGillum has written a great post (http://cgillum.tech/2016/03/07/app-service-token-store/) on this and when following that post I get the refresh method to work like a charm for Microsoft Accounts but I struggle with refreshing the access tokens for Facebook and Google. Our application (Xamarin Forms) is using Microsoft Account, Google and Facebook as authentication providers. With your instructions in the post it works like a charm for Microsoft Account.
For Google when setting the access_mode=offline in the LoginAsync I still are unable to refresh my access tokens and getting an error in the streaming logs from Azure that point to where the problem lies but I cannot understand what to do. For Facebook I get the same kind of error in the logs but I do not know how to request the offline access so here the problem is more of 'how do I request offline access for Facebook'.
The error is as follows:
Logging in with Google renders the following log entries (removed some details....)
2016-03-29T14:45:12 PID[5536] Verbose Received request: GET https://nnn.azurewebsites.net/.auth/login/google?access_mode=offline
2016-03-29T14:45:12 PID[5536] Information Redirecting: https://accounts.google.com/o/oauth2/v2/auth?response_type............
2016-03-29T14:45:38 PID[5536] Verbose Received request: GET https://nnn.azurewebsites.net/.auth/login/google/callback?state=nonce%3Dfd.......
2016-03-29T14:45:38 PID[5536] Verbose Calling into external HTTP endpoint POST https://www.googleapis.com/oauth2/v4/token.
2016-03-29T14:45:38 PID[5536] Information Login completed for 'nnn#nnn.com'. Provider: 'google'.
2016-03-29T14:45:38 PID[5536] Verbose Writing 'AppServiceAuthSession' cookie for site 'nnn.azurewebsites.net'. Length: 664.
2016-03-29T14:45:38 PID[5536] Information Redirecting: https://nnn.azurewebsites.net/.auth/login/done#token=%7B%22authenticationToken%22%3A
%22eyJ0e........
2016-03-29T14:45:39 PID[5536] Verbose Received request: GET https://nnn.azurewebsites.net/.auth/login/done
2016-03-29T14:45:39 PID[5536] Information Sending response: 200.0 OK
Then when trying to call the refresh method the following is written in the logs:
2016-03-29T14:53:14 PID[5536] Verbose Received request: GET https://nnn.azurewebsites.net/.auth/refresh
2016-03-29T14:53:14 PID[5536] Verbose JWT validation succeeded. Subject: 'sid:cc7e265f97060b2b067367d1ee02d808', Issuer:
'https://nnn.azurewebsites.net/'.
2016-03-29T14:53:14 PID[5536] Warning The refresh request issued by sid:cc7e265f97060b2b067367d1ee02d808 (SID:
37776b6cabedf8ff38df56de2e5db739) failed because no refresh tokens were found in the token store.
2016-03-29T14:53:14 PID[5536] Information Sending response: 400.80 Bad Request
The token store is enabled for the service and is works perfect for Microsoft Accounts. Does anyone have any clue here to what goes wrong and what to do in order to get refresh for access tokens using Google going?
How to enable refresh tokens for Facebook?
The code used for refreshing the access token and thus producing the output in the Azure logs above is:
public async Task<bool> RefreshAccessToken()
{
// http://cgillum.tech/2016/03/07/app-service-token-store/
// Calling /.auth/refresh will update the tokens in the token store
// and will also return a new mobile authentication token.
JObject refreshJson = (JObject)await App.m_azureMSClient.InvokeApiAsync("/.auth/refresh", HttpMethod.Get, null);
string newToken = refreshJson["authenticationToken"].Value<string>();
App.m_azureMSClient.CurrentUser.MobileServiceAuthenticationToken = newToken;
App.Current.Properties[App.m_propNameAuthToken] = newToken; // persist it
return true;
}
Token Refresh for Facebook is not supported in App Service. The tokens last for 60 days, however, so there is less of a need for this capability since you can require the user to log in interactively once every 60 days (and it should succeed immediately in most cases).
If you strongly need to be able to refresh Facebook tokens, another option you have is to use the Facebook SDK, which automatically handles refresh for you. More information here: https://developers.facebook.com/docs/facebook-login/access-tokens/expiration-and-extension. In this case, you can login again using the non-interactive login of mobile apps (also known as client-directed login) in order to get up-to-date authentication tokens for calling your APIs.
EDIT:
Regarding Google, it looks like your query string may be wrong. Try access_type=offline. It looks like you are specifying access_mode=offline, which is not correct.

Resources