oidc-client authentication failure: sub from user info endpoint does not match sub in access_token - oidc-client-js

I have an angular app using oidc-client to access an API that uses IdentityServer3 to provide OpenID Connect authentication.
During authentication the oidc-client throws an error:
sub from user info endpoint does not match sub in access_token
FYI the following steps were successful:
POST to the API's /openid/login?signin=xxx
redirect to the API's /openid/connect/authorize
redirect back to the angular app
But then oidc-client made a call to the API's /openid/connect/userinfo.
The API does not implement the userinfo endpoint, the /openid/connect/userinfo returns an empty object: {}.
And then oidc-client stopped the whole thing with the above error message.
Is there an option in oidc-client to skip that call to the userinfo endpoint? Or is it mandatory for the API to implement that endpoint?

oidc will always call the userinfo internally to verify user as by default it is set to true and its incoming access_token by querying the .well-known/openid-configuration.
It is also not good idea to skip this. Is your client application registered properly on IDP.
Look at the below oidc-client option configuration which controls the userinfo endpoint:
oidc-client-js
loadUserInfo (boolean, default: true): Flag to control if additional identity data is loaded from the user info endpoint in order to populate the user's profile.

Related

OIDC Azure AD token?

I am trying to configure a third party web application to use Azure AD as the OIDC provider. The authentication works fine, however I am looking for some claims and not able to find an ID or Access Token. Here is the flow as I am seeing it
Call to the login page of the web application. This gets a 302 redirect to the Microsoft OAuth endpoint as below
The URL is https://login.microsoftonline.com/-tenantid-/oauth2/v2.0/authorize?client_id=-clientid-&redirect_uri=-encodedCallbackURI-&response_type=code&scope=openid+email+profile&state=123 This does a 302 to below URL
Next call is to https://login.microsoftonline.com/-tenantid-/oauth2/v2.0/authorize?client_id=-clientid-&redirect_uri=-encodedCallbackURI-&response_type=code&scope=openid+email+profile&state=123&**sso_nonce=O.eyJ0eXAiOiJK......**&client-request-id=-guid-&mscrid=-guid- This returns a 200
Next is the redirect back to the hosted web application indicated in teh callback - https://webApplicationURL/callback?code=0.AQ4Ayjxg80......&state=123&session_state=5b7c2e43-9eab-4bb1-9f24-d020f144d30d
At this point, the user has successfully been authenticated. However, I would like to find the ID or Access Token received.
The sso_nonce(in #3) is in a JWT format but has no claims.
The code(in #4) doesn't have any of the claims either and doesnt really seem to be a JWT token format.
So where is the ID Token or Access Token that I can use to decode and see what claims are getting passed (or not)?
Thanks in advance,
Jake.
To get tokens while calling login page of the web application, you can execute the below request in browser by including response_type as id_token+token:
https://login.microsoftonline.com/<tenant_ID>/oauth2/v2.0/authorize?
client_id=da5daf42-xxxx-xxxx-xxxxxx04a52 //your AppID
&response_type=id_token+token //Required
&redirect_uri=https://jwt.ms //your Redirect URL
&response_mode=fragment
&scope=openid+profile+email
&state=12345
&nonce=678910
Make sure to enable tokens for your web application before executing the above request like below:
Go to Azure Active Directory -> App Registrations -> Your App -> Authentication -> Enable tokens -> Save
I tried to reproduce the same in my environment and got the below results:
When I executed the above-mentioned request in the browser, it asked me to sign in like below:
After successful sign-in, it took me to the redirect URL with tokens in the address bar like below:
When you copy-paste the above in Notepad or any, you can find both access_token and id_token like this:
I got the claims successfully when I decoded the token like below:
Reference:
OpenID Connect (OIDC) | Microsoft Docs

Salesforce OAuth User Agent Flow: obtain refresh token with

I am developing a web application that allows any user to connect with its Salesforce account. I've implemented User-Agent Flow and I obtain correctly access_token and other info but I can't obtain refresh_token, even if I have the correct scopes (api, web, refresh_token, offline_access).
This is the request I use:
https://login.salesforce.com/services/oauth2/authorize?response_type=token&scope=refresh_token&client_id=[MY_CLIENT_ID]&redirect_uri=[MY_REDIRECT_URL]
And my redirect URL is:
http://[MYSITE].com/#/services/oauth2/success
(that corresponds to the host from where I make the call)
This call correctly gives me access_token but not refresh_token.
if I use "https" instead "http" as redirect uri I receive this error:
error=invalid_scope&error_description=the requested scope is not available
From the documentation, I read that:
The refresh token for the user-agent flow is only issued if you
requested scope=refresh_token and one of the following scenarios is
true:
....
The redirect URL host matches the request host and includes the servlet services/oauth2/success.
...
I think to be in this case, what am I doing wrong?
Thanks in advance
Try adding Perform requests at any time (refresh_token, offline_access) under Selected OAuth Scopes in your connected app

Is this possible to use cognito's Authorization code grant type as a authorizer in the api-gateway?

I would like to know is there any way or possibility to implement authorization code grant type as Authroizer in securing API gateway? As is searched, 'Authorization code' grant type is most recommended for securing API.
i found below article which explain's using cognito 'client credentials' as grant type to secure the api gateway,
https://medium.com/#awskarthik82/part-1-securing-aws-api-gateway-using-aws-cognito-oauth2-scopes-410e7fb4a4c0
I tried the similar way to create an API gateway, where i have done following integration:
Created user pool 'UI Hosted' in cognito with the grant type - 'Authorization code'
Add the resource server
Choosed default scopes as i don't want to add any new scope
Associated call back uri
Now iam able to access the login page to sign up and sign in and it return the 'Authorization code' in the call back uri
In API gateway
I created an API and integrated some mock response
Attached above user pool as Authorizer in the api gateway and deployed
Now when i invoke the api without passing token, it returns 'Unauthorized'
So i used below approach to extract the access token from cognito
How programtically exchange the authorization code to get the access token from cognito using python
And passed the token in the api header using post man, but still i am getting 'Unauthorized' response
So would like to know what needs to be done in api gateway in order to verify the token or what went wrong in this approach..?
Appreciate if anybody can help on this?
Thanks
Your API's role is to just deal with incoming access tokens from API clients. The API doesn't care what flow was used to get the token. Here is by far the most common behaviour:
UI logs the user in using Authorization Code flow - usually the PKCE variant
This involves the UI calling the Authorization Server - eg AWS Cognito
Once login completes the UI calls the API Gateway URL with an access token / JWT
The API then needs to validate the access token by verifying its signature
Here is some sample code in case it helps:
Lambda Authorizer Code to Verify Cognito Tokens
Web UI Code to implement Authorization Code Flow
AWS API Gateway has built in support for Cognito authorizers as in the screenshot on the left below.
For more control over behaviour you can instead create a custom lambda authorizer in code, which returns an AWS policy document, as in the screenshot on the right. My blog post and the above source code link has some further details, though it is quite detailed / advanced.
finally i got the answer here..
https://aws.amazon.com/blogs/mobile/understanding-amazon-cognito-user-pool-oauth-2-0-grants/
so i created a simple flask logic here to exchange the auth code to get the 'id_token' from cognito, which further can pass in the api header to get the response.
def getToken(auth_code):
response=''
try:
print("Code is", auth_code)
response = requests.post(url + '/oauth2/token',{'Content-Type':'application/x-www-form-urlencoded', 'grant_type': grant_type, 'client_id': App_client_id, 'code': auth_code, 'redirect_uri': 'http://localhost:5000/login'})
if response.status_code != 200:
return "Not a valid response"
print("Response is", response.json())
token_value = response.json()
print("Token value", token_value['id_token'])
return token_value['id_token']
except TypeError as e:
print("Error is",e)

How to access another user's data via the Graph API?

Using the Graph API and related authentication/authorization flows, how can I access data of all users in an organization? Also, multiple organizations/tenants need to be able to use the app.
As an example: I have an app which needs to read events from all calendars of all users under contoso.onmicrosoft.com. I would like that jack#contoso.onmicrosoft.com, the administrator, authorizes the app which will then be able to read the mentioned the data. Using the Managed API this can be easily done via impersonation.
However, I am trying to do the same with Graph API and OAuth, but I can't find a straight forward solution, or I must be missing something very obvious. I have created an app through manage.windowsazure.com (multi-tenant), and configured it so that it requires Microsoft Graph API (all application and delegated permissions).
I did the following:
1) Point jack#contoso.onmicrosoft.com towards https://login.microsoftonline.com/common/oauth2/authorize?response_type=code&redirect_uri=<my redirect url>&client_id=<my client id>
2) Jack authorizes the app
3) I get back: <my redirect url>/?code=<my authorization code>&session_state=<blah>
4) I send a POST request like below:
POST https://login.microsoftonline.com/common/oauth2/token
Headers: content-type: application/x-www-form-urlencoded
Body:
grant_type=authorization_code&code=<my auth code from step above>
&redirect_uri=<my redirect url>
&client_id=<my client id>
&client_secret=<my client secret>
&resource=https%3A%2F%2Fgraph.microsoft.com%2F
5) When I do the following:
GET https://graph.microsoft.com/v1.0/users/jack#contoso.onmicrosoft.com/messages
Headers: Authorization: Bearer <auth token from step #4>
I get a 200 OK response with the messages.
When I do the following:
GET https://graph.microsoft.com/v1.0/users/anyotheruser#contoso.onmicrosoft.com/messages
Headers: Authorization: Bearer <auth token from step #4>
I get a 403 Forbidden response with:
{
"error": {
"code": "ErrorAccessDenied",
"innerError": {
"date": "2016-06-07T08:47:27",
"request-id": "5b629e30-e6bd-474d-b3dd-8ce25c5ad1c4"
},
"message": "Access is denied. Check credentials and try again."
}
}
The flow/URLs you've referenced are for the authorization code flow which leverages delegated scopes.
A) If you want the app to only work (i.e. access all calendars) for admins then you are using the right flow.
B) If you want the app to work for all users after the admin consents to it, you'll need to use the app (client credentials) flow and use application scopes. This means that you'll need to separate out consent from the regular auth flow.
For consent you'll need to to point the admin to the following url:
GET https://login.microsoftonline.com/common/oauth2/authorize?resource=https://graph.microsoft.com/&client_id=<YourClientId>&client_secret=<YourClientSecret>&response_type=code&redirectUri=<YourRedirectUri>&prompt=admin_consent
For auth flow you'll need a single call from your web server:
POST https://login.microsoftonline.com/common/oauth2/token
body resource=https://graph.microsoft.com/&client_id=<YourClientId>&client_secret=<YourClientSecret>&response_type=code
Or better yet, just use ADAL's AquireToken(resource, clientCredentials) overload.
Once that's done, your app should be good to go to make requests to Graph.
Regardless if you want to stick to A) or switch over to B), to double check that things are set up correctly you can:
Check the token that you get back from Graph (the one you attach to the request along with Bearer) and confirm that it has a roles entry with the roles you need i.e. Calendars.Read
NOTE: The following steps 2.a & 2.b require you to have admin to a test tenant where you'd be consenting to the application.
2.a Use GraphExplorer (https://graphexplorer2.azurewebsites.net/) and confirm that consent has been properly set up by querying
beta/servicePrincipals?$filter=displayName eq '[YourApplicationName]'
If nothing shows up, then the no one has consented to the application.
2.b (only applicable for auth code flow with delegated scopes) Use GraphExplorer and confirm that either delegation has been authorized correctly by querying
beta/oauth2permissiongrants?$filter=clientId eq '[IdFrom ServicePrincipal in 2.a]'
And ensuring you get either a result for the specific user in question or for "AllPrincipals".
More info on app vs delegated scopes here: http://graph.microsoft.io/en-us/docs/authorization/permission_scopes
More info on app flow here: https://graph.microsoft.io/en-us/docs/authorization/app_only
Please use the app-only auth flow (see https://graph.microsoft.io/en-us/docs/authorization/app_only) to use the application permissions - for the token request (step 4) you need to pass grant_type=client_credentials instead of grant_type=authorization_code.

OAuth 2.0 for MVC - How does the RequestToken work?

I'm working with OAuth 2.0 for MVC, found here: http://community.codesmithtools.com/CodeSmith_Community/b/tdupont/archive/2011/03/18/oauth-2-0-for-mvc-two-legged-implementation.aspx
For anyone who's worked with this - I'm confused about the RequestToken. There is a controller implemented that lets you get a request token, which expires in 5 minutes, and you pass that token back in to get an AccessToken. But it never checks the request token for validity - it seems like you can pass in any access token you want to. What is the idea for the RequestToken here - are you supposed to create your own method of storing, referencing, and then deleting that token for those 5 minutes?
Thanks,
Andy
This is all about how OAuth works in conjunction with your application Id, application secret key and valid domains for your application. Here is the process in general
Your application sends a request to the OAuth provider using your application Id and secret along with a callback (return Url).
The OAuth provider gets the request, checks your application Id and secret and validates that the callback url is from a domain that you have specified for your application.
2a. If the callback url is not from a domain that you have specified, then the request is rejected with error.
2b If the callback url is from your domain, it returns a temporary request key to your server.
Given that you received a request key, you send that back to the OAuth provider to get the actual access token for the user.
Now, as to why the request key step is in place, this is to prevent and help protect 'bad people' from attempting to use your application id to falsely authenticate other users. By sending the request token to you (a callback URL that you have approved), the OAuth provider has confidence that the request actually came from your servers.
You most certainly could send any string back instead of the request token, but you would quickly get an error back from the OAuth provider as that request token does not correspond to any existing authentication request from any known application.
Lastly, I am not clear on what you mean by 'validating the request token'? You did not generate the token not probably do not have insight into the algorithm to generate the request token. Given that, I am not sure how you would validate this. If you are concerned about validating the first step, take a look at the Facebook OAuth process. In there, they recommend sending a request key as part of your return Url(as a query string parameter). That request key will come back to your application which you could then use as a validation that, indeed, this is a response to a request that you made. How you store and track that request key is up to you (session, database). In the PHP samples, they use a 'state' variable to track a unique/arbitrary string: Facebook OAuth Server Side Login Example (in PHP)

Resources