Getting 401 unauthorized : Authentication Failed: Could not obtain access token in okta web app - jhipster

I created a jhipster monolithic application (jhipster version v4.14.2). Also I create a Okta web application with following settings:
Login redirect URIs -> http://localhost:8080/login
Initiate login URI -> http://localhost:8080
Create groups for admin and user, setup the claim in the default authorization server, and assign them to the application and my user
I updated the application.yaml of my jhipster application as follow:
security:
basic:
enabled: false
oauth2:
client:
access-token-uri: https://dev-779125.oktapreview.com/oauth2/default/v1/token
user-authorization-uri: https://dev-779125.oktapreview.com/oauth2/default/v1/authorize
client-id: ????????
client-secret: ????????
client-authentication-scheme: form
scope: openid profile email
resource:
filter-order: 3
user-info-uri: https://dev-779125.oktapreview.com/oauth2/default/v1/userinfo
token-info-uri: https://dev-779125.oktapreview.com/oauth2/default/v1/introspect
prefer-token-info: false
When I start the application and then I try to sign in. I do get the Okta login page, however after adding my credential I always get the following error:
Your request cannot be processed
Sorry, an error has occurred.
Status: Unauthorized (Unauthorized)
Message: Authentication Failed: Could not obtain access token
I followed instruction in jhipster security documention and can't make it work. Any idea why I still get the unauthorized error?

This might have nothing to do with jhipster. Make sure your you URL for accessing the access token is right.
What Grant type are you using?
https://developer.okta.com/authentication-guide/implementing-authentication/
I think the error is here:
access-token-uri: https://dev-779125.oktapreview.com/oauth2/default/v1/token
user-authorization-uri: https://dev-779125.oktapreview.com/oauth2/default/v1/authorize
Is "user-authorization-uri" jhipster way of of asking for "issuer URL"?

Related

Postman with OAuth2.0 to a registered app in Azure Active Directory fails with Invalid Resource

I am following the tutorial here: https://learn.microsoft.com/en-us/sharepoint/dev/apis/webhooks/get-started-webhooks
I am having trouble finishing step 5. Postman always gives me this error and I am not sure why.
Troubleshooting details
If you contact your administrator, send this info to them.
Copy info to clipboard
Request Id: XXXXXXXX-XXXX-XXXX-XXXX-XXXXXXXXXXXX
Correlation Id: XXXXXXXX-XXXX-XXXX-XXXX-XXXXXXXXXXXX
Timestamp: 2022-11-18T09:34:11Z
Message: AADSTS650057: Invalid resource. The client has requested access to a resource which is not listed in the requested permissions in the client's application registration. Client app ID: XXXXXXXX-XXXX-XXXX-XXXX-XXXXXXXXXXXX(Postman App). Resource value from request: https://<mysite>.sharepoint.com. Resource app ID: 00000003-0000-0ff1-ce00-000000000000. List of valid resources from app registration: fe7b6ec1-3281-4dd6-8864-dff33cd1021e, 00000003-0000-0000-c000-000000000000.
Flag sign-in errors for review: Enable flagging
If you plan on getting help for this problem, enable flagging and try to reproduce the error within 20 minutes. Flagged events make diagnostics available and are raised to admin attention.
00000003-0000-0000-c000-000000000000 is Graph.
fe7b6ec1-3281-4dd6-8864-dff33cd1021e is SharePoint Online Client Extensibility Web Application Principal Helper.
In the error it says the app id (00000003-0000-0ff1-ce00-000000000000) that I am trying to use and then lists the valid resources form my app. I can add another resource to the app and it will be listed there in the error message but I do not know how to add my specific resource to the list. Does anyone know how I can do that or if that is even what I need to be doing?
I tried to reproduce the same in my environment and got the results successfully like below:
I created an Multi-Tenant Azure AD application and consented the below API permissions:
To generate the access token, I used below parameters:
Grant Type : Authorization Code
Callback URL : redirect_uri
Auth URL : https://login.microsoftonline.com/common/oauth2/authorize?resource=https://TENANT.sharepoint.com
Access Token URL : https://login.microsoftonline.com/common/oauth2/v2.0/token
Client ID : CLIENTID
Client Secret : ClientSecret
Access token successfully generated like below:
To get Documents list Id click on Use Token and execute the query like below:
GET https://XXXX.sharepoint.com/_api/web/lists/getbytitle('Documents')?$select=Title,Id

For IMAP.AccessAsUser.All Scope ADSTS65001: The user or administrator has not consented to use the application

In my java web application I want to get access to user's mailbox by using jakarta mail. For that purpose I followed https://learn.microsoft.com/en-us/exchange/client-developer/legacy-protocols/how-to-authenticate-an-imap-pop-smtp-application-by-using-oauth for OAuth2 authorization code flow.
On Azure port I setup my app and added API permissions as below
Now user is redirecting to below authorize endpoint:
https://login.microsoftonline.com/5426ee07-9b73-4a9e-8075-395ab439c6fa/oauth2/v2.0/authorize?client_id=b6067ad9-7195-430b-a35d-97b7aa7beb8f&response_type=code&redirect_uri=http://localhost:8080/callback/microsoft&response_mode=query&scope=offline_access%20https%3A%2F%2Fgraph.microsoft.com%2FIMAP.AccessAsUser.All%20https%3A%2F%2Fgraph.microsoft.com%2FSMTP.Send
After entering credentials and accepting the consent redirect_uri gets hit with auth code. Based on that auth code I formed token endpoint URL and hitting it from server, the token endpoint is as follow:
URL: https://login.microsoftonline.com/5426ee07-9b73-4a9e-8075-395ab439c6fa/oauth2/v2.0/token
Form Data:
client_id=b6067ad9-7195-430b-a35d-97b7aa7beb8f
scope=offline_access%20https%3A%2F%2Foutlook.office.com%2FIMAP.AccessAsUser.All
redirect_uri=http://localhost:8080/callback/microsoft
grant_type=authorization_code
client_secret=QUs8Q~aboLBiopTezMTKwzQjIwWsFFXjc2kCRaRs (I know I have shared the secret)
code={code received from authorize end point}
Response to this post request comes as:
{"error":"invalid_grant","error_description":"AADSTS65001: The user or administrator has not consented to use the application with ID 'b6067ad9-7195-430b-a35d-97b7aa7beb8f' named 'Email Connector'. Send an interactive authorization request for this user and resource.\r\nTrace ID: dc008ced-e23f-4919-bd45-b7ae7c68b000\r\nCorrelation ID: 9b6ede03-3c05-4a78-8975-036a3cb20773\r\nTimestamp: 2022-06-07 19:51:30Z","error_codes":[65001],"timestamp":"2022-06-07 19:51:30Z","trace_id":"dc008ced-e23f-4919-bd45-b7ae7c68b000","correlation_id":"9b6ede03-3c05-4a78-8975-036a3cb20773","suberror":"consent_required"}
Here, I don't understand why the error is saying The user or administrator has not consented to use the application, user has accepted the consent after entering credentials on authorize end point. Event more If we look at the screenshot above admin has already given grant to access the directory.
I tried to reproduce the same scenario in my environment and got the same error as below:
To resolve the error, please check the authorize endpoint you are using to get the code.
Avoid using Microsoft graph API scopes while getting the code.
Replace it with the scope you are using to get access token like below:
https://login.microsoftonline.com/Your_TenantID/oauth2/v2.0/authorize?
client_id=Your_ClientID
&response_type=code
&redirect_uri=http://localhost:8080/callback/microsoft
&response_mode=query
&scope= offline_access https://outlook.office.com/IMAP.AccessAsUser.All
&state=12345
Get the code from the above authorization endpoint.
I got the access token successfully after modifying the endpoint like below:
To validate the access token decode it in jwt.io and check the aud and scp claims like below:

Get Azure Webjob History - 403 Token invalid

I am trying to retrieve the web job history of an Azure web job via REST using a .NET backend and the OAuth2 credentials flow (as described here
https://learn.microsoft.com/en-us/rest/api/appservice/web-apps/get-triggered-web-job-history-slot)
How do I need to authenticate correctly?
I retrieve the token as follows:
POST https://login.microsoftonline.com/{MySubscription}/oauth2/v2.0/token
client_id={MyApp}
&grant_type=client_credentials
&scope=https://management.azure.com/.default
&client_secret={myclient_secret}
I get a token back, however I get a 403 error message when I try to retrieve the resource:
GET https://management.azure.com/subscriptions/{MySubscription}/resourceGroups/{MyResource}/providers/Microsoft.Web/sites/{MyApp}/slots/{MySlot}/triggeredwebjobs/{MyWebjob}/history?api-version=2021-02-01
Authorization: Bearer {MyToken}
Client '{MyApp}' with object ID '{MyApp}' is not
authorized to perform the action
'Microsoft.Web/sites/slots/triggeredwebjobs/history/read' using the
scope
'/subscriptions/{MySubscription}/resourceGroups/{MyResource}/providers/Microsoft.Web/sites/{MyApp}/slots/{MySlot}/triggeredwebjobs/{MyWebjob}'
or the scope is invalid. If access was granted recently, please update
your credentials.
What am I doing wrong?
I already added the API-Permission
The "403 Token invalid" error usually occurs if you missed giving permissions to particular scope (Azure Service Management).
By giving this scope it enables you to access https://management.azure.com
To resolve this error, please follow below steps:
Go to Azure Ad ->your application -> API permissions -> Add permission -> Azure Service Management -> delegated permissions ->User impersonation -> Add
After giving these permissions try to retrieve the resource again, there won't be any error.
Since I didn't find a solution that worked with OAuth2 and the Credentials flow, I got it working with Basic Authentication. The username (userName) and password (userPWD) can be taken from the publishing profile of the respective app service.
GET https://{appservicename}.scm.azurewebsites.net/api/triggeredwebjobs/{jobName}/history
Authorization Basic ....

How to implement "Organizational account" authentication in Excel on server side?

I have Java application which provides some reports in plain HTML.
I want to secure these reports with Microsoft SSO (OAuth).
I was able to do this in browser - I created new "AppRegistration" in Azure AD, get client_id, client_secret, Oauth 2 authentication_url, configured correct redirect_uri in this application and implemented Oauth flow in browser - it works as expected.
But users don't want to check reports in browser, they want to process them in Excel 2019.
It has "Organizational account" authentication.
I believe, that it uses the same OAuth 2 flow.
So, I added WWW-Authenticate: Bearer authorization_url="https://login.microsoftonline.com/256be541-f611-4412-975e-cb56ee6fb03b/oauth2/v2.0/authorize"
I'm trying to access URL like: https://localhost:8443/report/1
Now Excel asks me to enter login and password, but after successfull authentication the error is shown:
invalid_resource: AADSTS500011: The resource principal named https://localhost:8443 was not found in the tenant named 256be541-f611-4412-975e-cb56ee6fb03b. This can happen if the application has not been installed by the administrator of the tenant or consented to by any user in the tenant. You might have sent your authentication request to the wrong tenant.
Trace ID: 57324bfe-ab46-4c2e-9128-a336aa287e00
Correlation ID: d9c4c732-76cc-4659-9d8a-d27abec617d3
Timestamp: 2021-02-02 16:50:13Z.
https://localhost:8443 - is address of my application and this address is included to redirect_uri in App registration.
But I don't think that mentioned "resource principal" is about redirect_uri.
So, how can I create "resource" principal in Azure AD and give it name "https://localhost:8443" ?
In fact, this is the case. According to your error message, it says that the resource body of https://localhost:8443 cannot be found, which means that you set the scope to: https://localhost:8443 when requesting an access token.
However, you only set it to redirect_uri at the beginning, and did not set the Application ID URI to: https://localhost:8443 in the Expose API tab, so when you request the resource, the error message will report that it cannot be found the resource.
By the way, scope is different from redirect_uri. The scope puts the resource you want to access, while redirect_uri is just the callback url that is not the resource you want to access. This is why you still get an error when setting the url in redirect_uri.

"authentication failed due to: jwt audience is invalid" with Azure AD

First I'm describing how I setup my applications then I will describe how I'm using the APIs.
Setup
In my Azure Active Directory, I have two applications registered: UI and Backend
UI has the client ID clientId1 and backend has client ID clientId2 (it's a GUID, but for simplicity)
Both are under the same tenant tentant1 (single tenant)
Backend (Web API)
Backend has an exposed API with scope "api://clientId2/access_as_user" and authorized client "clientId1" with the scope just mentioned selected
I'm using passport and passport-azure-ad (I pretty much copied https://github.com/Azure-Samples/active-directory-javascript-nodejs-webapi-v2).
My config:
const config = {
identityMetadata: "https://login.microsoftonline.com/tenant1/v2.0/.well-known/openid-configuration",
clientID: "clientId2",
validateIssuer: false,
loggingLevel: 'info',
passReqToCallback: false,
loggingNoPII: false
};
I get this message when starting the server:
{"name":"AzureAD: Bearer Strategy","hostname":"DESKTOP-NCVLN56","pid":16052,"level":40,"msg":"Production environments should always validate the issuer.","time":"2020-04-11T13:25:44.283Z","v":0}
{"name":"AzureAD: Bearer Strategy","hostname":"DESKTOP-NCVLN56","pid":16052,"level":30,"msg":"In BearerStrategy constructor: created strategy with options {\"identityMetadata\":\"https://login.microsoftonline.com/tenant1/v2.0/.well-known/openid-configuration\",\"clientID\":\"clientId2\",\"validateIssuer\":false,\"loggingLevel\":\"info\",\"passReqToCallback\":false,\"loggingNoPII\":false,\"clockSkew\":300,\"allowMultiAudiencesInToken\":false,\"audience\":[\"clientId2\",\"spn:clientId2\"]\"isB2C\":false,\"_isCommonEndpoint\":false}","time":"2020-04-11T13:25:44.285Z","v":0}
Listening on port 5000
UI (Angular SPA)
UI has permissions was granted automatically permission to access Microsoft Graph (profile, user.read, user.read.all -- last one I think I granted). The permissions are in "API permissions"
I went ahead and also granted access to the Backend access_as_user
For the UI code I'm using the MSAL library and again I pretty much copied the repo (https://github.com/Azure-Samples/active-directory-javascript-singlepageapp-angular)
In the protectedResourceMap field I added the following
['https://graph.microsoft.com/v1.0/me', ['user.read']],
['http://localhost:5000', ['api://clientId2/access_as_user']],
I am able to log in and read my user profile, but when trying to access http://localhost:5000/hello (protected), I'm getting the error the title of this question
{"name":"AzureAD: Bearer Strategy","hostname":"DESKTOP-NCVLN56","pid":20720,"level":30,"msg":"authentication failed due to: jwt audience is invalid","time":"2020-04-11T13:38:08.700Z","v":0}
--
I can see the Bearer Token coming (in the UI and backend), the server decodes the token (I can see all my profile info in the server logs), but it's saying the JWT is invalid?!
I'm not defining an audience, yet I can see in the token when it gets decoded the audience with aud: 'api://clientId2'.
I can also see when the backend starts it shows the audience as [clientId2, sps:clientId2] by default (step4 on the backend). When I define in the config audience: 'api://clientId2', I get a 403 with the message:
{"name":"AzureAD: Bearer Strategy","hostname":"DESKTOP-NCVLN56","pid":12644,"level":30,"msg":"In Strategy.prototype.jwtVerify: We did not pass Req back to Callback","time":"2020-04-11T16:19:30.398Z","v":0}
Any help would be appreciated. Thank you.
Turns out their code in the repository is not using proper configuration to verify the scope access...
https://github.com/Azure-Samples/active-directory-javascript-nodejs-webapi-v2/blob/master/index.js#L41
if (req.authInfo['scp'].split(" ").indexOf("demo.read") >= 0) {
I needed to change the scope from "demo.read" to "access_as_user".
In my case it was just that the clock of my VM where the application was running on was 15mins behind. So the time of the token was created was in the future...

Resources