Failure to generate access token using refresh token for O365 API - azure

I'm getting invalid_grant error while generating access token using refresh token
POST https://login.microsoftonline.com/common/oauth2/v2.0/token
Response
{
"error": "invalid_grant",
"error_description":
"AADSTS50173: The provided grant has expired due to it being revoked. The user might have changed or reset their password. The grant was issued on '2018-06-13T23:20:02.9860000Z' and the TokensValidFrom date for this user is '2018-06-15T17:21:11.0000000Z'\r\nTrace ID: 4237d0b8-51fe-43c2-9b5c-ca9148175400\r\nCorrelation ID: d192091b-6277-4ef9-859a-87ba7f87491a\r\nTimestamp: 2018-06-18 07:22:59Z",
"error_codes": [50173],
"timestamp": "2018-06-18 07:22:59Z",
"trace_id": "4237d0b8-51fe-43c2-9b5c-ca9148175400",
"correlation_id": "d192091b-6277-4ef9-859a-87ba7f87491a"
}
The user was asked to change password and the password was changed. Seeing this error even after the password is changed. Will the refresh token become invalid in this case?

If you get this error while using the azure-cli You can fix it by:
az account clear
az login
That happened because after you change your password, tokens that are based on passwords will expire. Then you need to clear your account and log in again.
More information here

Yes, refresh tokens will become invalid after a password change.
Only non-password based tokens will stay valid.
(see active directory token documentation for more information)

Environment: Office 365 - Okta - On-premise Active Directory.
Error message:
The provided grant has expired due to it being revoked, a fresh auth token is needed. The user might have changed or reset their password. The grant was issued on '{authTime}' and the TokensValidFrom date (before which tokens are not valid) for this user is '{validDate}'.
Workaround:
All you need to do is temporarily change the user’s UserPrincipalName to that of a managed domain, update the password and then change the UserPrincipalName back to the federated domain.
First step is you will need to get the user's ObjectId and UserPrincipalName.
Run this command to get the ObjectId and the user's UserPrincipalName:
Get-AzureADUser -SearchString pat.doe
Now, run the following command to change UPN to a managed domain:
Set-AzureADUser -ObjectId 11bb4111-11a0-1114-8501-111180bf51d3 -UserPrincipalName pat.doe#onmicrosoft.com
Next, update the password with the following command:
Set-AzureADUserPassword -ObjectId 11bb4111-11a0-1114-8501-111180bf51d3
Change the UPN back to the federated domain. Run the following command:
Set-AzureADUser -ObjectId 11bb4111-11a0-1114-8501-111180bf51d3 -UserPrincipalName pat.doe#contoso.com
That’s it. Now, reset the password in Okta or the Authoritative source (Active Directory).

Related

Change Azure B2C account password on behalf of a user

I'm trying to change the password of a user created in my Azure B2C Tenant. I'm using Microsoft.Graph C# SDK to do API calls.
First I create GraphServiceClient by providing details of my tenant:
var options = new TokenCredentialOptions
{
AuthorityHost = AzureAuthorityHosts.AzurePublicCloud
};
var clientSecretCredential = new ClientSecretCredential("tenantId", "clientId", "clientSecret", options);
_client = new GraphServiceClient(clientSecretCredential);
Then I use the built-in method of a client to change the user's password:
await _client.Users["userId"].ChangePassword(currentPassword, newPassword).Request().PostAsync();
But I get following error:
Microsoft.Graph.ServiceException: Code: Authorization_RequestDenied
Message: Access to change password operation is denied.
Is it possible to change the password on behalf of a user? I found conflicting information on this topic on the internet. If this is impossible, what is the valid approach to do this?
I have a SPA frontend app in which the user is authenticated with redirection flow. The access token is then passed to my backend to authorize the requests. Maybe I can use this token to somehow access MS Graph API and change the password?
Note: I would like to let users change their passwords without leaving my SPA application.
I tried in my environment and got below results:
Initially I tried with your code and got same error:
According to MS-DOCS change password we need Directory.AccessAsUser.All permission and it only supported for delegated (Work or school accounts).
Trying to reset the password in the B2C tenant using the Graph API its is not possible Unfortunately, because there is no Directory.AccessAsUser.All, B2C tenant does not allow this type of password reset. For B2C tenants, the Graph API includes the permission. Only offline access and openID are available as delegated rights in the B2C tenant.
You can reset the password in B2C tenant are either admin performing password reset via Azure Portal or by using Password Reset Policy and also refer this MS-Q&A for updating password in powershell and postman.
Reference:
"Upn from claims with value null is not a valid upn." - Microsoft Q&A by amanpreetsingh-msft.

Azure AD me profile

I have error "Access token validation failure. Invalid audience."
For application set api permissions to offline_access, openid, profile, User.Read.
User start auth, go to MS auth site, ask about login, password and grand.
After exchange code to access token i well receive
{'token_type': 'Bearer', 'scope': 'offline_access openid profile User.Read', 'expires_in': '3906', 'ext_expires_in': '3906', 'expires_on': '1653988700', 'not_before': '1653984493', 'resource': 'my_azure_client_id', ....}
Then i try get profile for current user with this access token.
As result i have error "Access token validation failure. Invalid audience."
Help pease)
UPDATE
Configured permissions
The reason behind getting that error is because your token has wrong audience.
Please check what token you are using to call Graph API.
I tried to reproduce the same in my environment.
If you are using ID Token instead of Access Token, you may get error like below:
To know whether you are giving access token or id token, decode it in JSON Web Tokens - jwt.io.
For access token, aud claim will be "https://graph.microsoft.com" or "00000003-0000-0000-c000-000000000000"
For id token, aud claim will be "your_app_client_id"
Choose the access token carefully with aud as "https://graph.microsoft.com" while calling Microsoft Graph API:
To get profile for current user, you can make use of below query:
GET https://graph.microsoft.com/v1.0/me
I got the profile successfully using access token like below:
Replace your scope with https://graph.microsoft.com/.default while generating access token to avoid confusion.
Reference:
oauth 2.0 - Microsoft Graph API: Access token validation failure. Invalid audience - Stack Overflow
UPDATE:
In order to get authorization code, make the request by changing scope like below:
https://login.microsoftonline.com/your_tenant_id/oauth2/v2.0/authorize?
client_id=your_client_id
&response_type=code
&redirect_uri=xxxxxx
&response_mode=query
&scope=https://graph.microsoft.com/.default
&state=12345

azure ad b2c custom policy - ROPC

as part of the "SignUpOrSignIn" userJourney, i would like to call MyAPI and run some business logic.
to accomplish that, i added a couple of orchestration steps to the "SignUpOrSignIn" userJourney after the user has successfully authenticated.
Step 1) make a simple http request to azure ad b2c token endpoint and get an access token to MyAPI
https://<tenant-name>.b2clogin.com/<tenant-name>.onmicrosoft.com/B2C_1_ROPC_Auth/oauth2/v2.0/token
username <user-name>
password <password>
grant_type password
scope <MyAPI Scope>
client_id <application-id of the client that has been granted access to MyAPI>
response_type token id_token
Step 2) use the access token from the previous response to call MyAPI.
I got this working. However, in Step (1), when i make the http request to get the access token, i am having to provide a hard coded username and password in the http request.
Is there a way to use the values of the username and password that were entered as part of "SignUpOrSignIn" to get the access token?
Thanks,
-Sashi.

We do not recognize this tenant ID 21f3be0a-713c-4b7f-ab75-3cc5ca25846. Please double-check the tenant ID and try again.",

I want to make multi-tenant application on https://apps.dev.microsoft.com.
This work fine with single tenant but
My process for making multi-tenant app ----
LogIn with Other Tenant and appear consent window and got code successfully which code I passed for getting token
Token successfully generated:
Call graph API for office 365
But error genrate --
"We do not recognize this tenant ID 21f3be0a-xx-4b7f-ab05-xxxxx6. Please double-check the tenant ID and try again.
]2
When access data for office 365 report why this tenant id not recognized error raised?
Need to edit in manifest ?
My App on https://apps.dev.microsoft.com. Have Three 3 Microsoft Graph Permissions
Delegated Permissions - user.read , Reports.Read.All (Admin Only)
You can check whether a tenant is valid or invalid using the Well Known OpenId Configuration endpoint:
https://login.microsoftonline.com/<tenant>/.well-known/openid-configuration
Doing this for your tenant id gives this result:
https://login.microsoftonline.com/21f3be0a-713c-4b7f-ab75-3cc5ca25846/.well-known/openid-configuration
error: "invalid_tenant"
error_description: "AADSTS90002: Tenant
21f3be0a-713c-4b7f-ab75-3cc5ca25846 not found. This may happen if
there are no active subscriptions for the tenant. Check with your
subscription administrator.\r\nTrace ID:
bdd561b1-bc36-44ce-b3ab-33e53fda0100\r\nCorrelation ID:
c6ce0c0d-6550-4f5f-a398-a82f085e28c1\r\nTimestamp: 2017-11-01
17:38:31Z"
So simply stated, the tenant id that you are using is not valid for the AAD Worldwide endpoint.
Is it possible you are getting a token for a different instance of AAD? Can you share the contents of your Access Token (removing any sensitive details)?
I did some mistakes thats why this Error raised then need not do anything becoz this Portal app by default Multitenant and send request to common platform ..
Login with other tenant get code
https://login.microsoftonline.com/common/oauth2/authorize?
client_id=XXXXX-XXX
&response_type=code
&redirect_uri=http://localhost:49876
&response_mode=query
&scope=Reports.Read.All
&prompt=consent
&state=12345
then get token
https://login.microsoftonline.com/common/oauth2/token
client_id =XXX
scope =
code= which you get
grant_type=
client_secret=
after get token use for Graph API & get office365 data for -https://graph.microsoft.com/beta/reports/getMailboxUsageMailboxCounts(period='D7')

Exact procedure to update access token life time

I have created access token using AcquireToken method (with default 1 hour expiration) and tried to login using below command
Add-AzureRmAccount -AccessToken "string" -AccountId "string"
It produces subscription details as expected by successful login.
After this i tried to update policy as below:
Set-AzureADPolicy -ObjectId <ObjectID FROM GET COMMAND> -DisplayName TenantDefaultPolicyUpdatedScenario -Definition #("{`"TokenLifetimePolicy`":{`"Version`":1,`"MaxAgeSingleFactor`":`"2.00:00:00`"}}")
But still token got expired in 1 hour.
Did i missed anything ?
what is the exact procedure and order of updating lifetime of token ?a
after setting policy how to ensure token life time ?
Thanks in advance.
According to this article, you should set AccessTokenLifetime property. Please try to use the following command.
Set-AzureADPolicy -Id <ObjectId FROM GET COMMAND> -DisplayName "OrganizationDefaultPolicyUpdatedScenario" -Definition #('{"TokenLifetimePolicy":{"Version":1,"AccessTokenLifetime":"1.00:00:00"}}')
The following is the snippet from the document.
Access Token Lifetime
String: AccessTokenLifetime
Affects: Access tokens, ID tokens
Summary: This policy controls how long access and ID tokens for this resource are considered valid. Reducing the Access Token Lifetime property mitigates the risk of an access token or ID token being used by a malicious actor for an extended period of time. (These tokens cannot be revoked.) The trade-off is that performance is adversely affected, because the tokens have to be replaced more often.
The MaxAgeSingleFactor property affects Refresh tokens.
Single-Factor Refresh Token Max Age
String: MaxAgeSingleFactor
Affects: Refresh tokens
Summary: This policy controls how long a user can use a refresh token to get a new access/refresh token pair after they last authenticated successfully by using only a single factor. After a user authenticates and receives a new refresh token, the user can use the refresh token flow for the specified period of time. (This is true as long as the current refresh token is not revoked, and it is not left unused for longer than the inactive time.) At that point, the user is forced to reauthenticate to receive a new refresh token.
Reducing the max age forces users to authenticate more often. Because single-factor authentication is considered less secure than multi-factor authentication, we recommend that you set this property to a value that is equal to or lesser than the Multi-Factor Refresh Token Max Age property.
Note: Access token without any expiry is a major security risk and it is not allowed in the Azure.
Default expiration of access token is 1 hour, minimum is 10 minutes, and the maximum is 1 day.
For more details, refer “Configurable token lifetimes in Azure Active Directory (Public Preview)”.

Resources