How check token received from Azure Active Directory? - azure

Let's say that a user logs in using the Microsoft login page and Azure requests application url with token. But how to validate it? Anybody can request application url with fake token. Does Azure API contain url for such a check?

But how to validate it?
To validate an id_token or an access_token, your app should validate both the token's signature and the claims. To validate access tokens, your app should also validate the issuer, the audience, and the signing tokens. These need to be validated against the values in the OpenID discovery document. For example, the tenant-independent version of the document is located at https://login.microsoftonline.com/common/.well-known/openid-configuration.
The Azure AD middleware has built-in capabilities for validating access tokens, and you can browse through the samples to find one in the language of your choice. For more information on how to explicitly validate a JWT token, see the manual JWT validation sample.
For more details, you could refer to Validating tokens.

Related

Azure AD token validation - why validate issuer?

I have an API service that uses Azure AD tokens for authentication and authorization. I plan to use https://github.com/AzureAD/passport-azure-ad library for this and need to use BearerStrategy - https://github.com/AzureAD/passport-azure-ad#42-bearerstrategy. I'm confused by the validateIssuer property.
validateIssuer and issuer configurations need to be used together if I understand the docs correctly. issuer is a URL that contains the tenant id and the AD version(1 or 2) used to issue the token.
As the API service who will validate token, why would the API service care about the AD version that was used to issue the token? And hence why would it validate the issuer url, when it should care only about the tenant id? I'm trying to understand why must the entire issuer url be verified and not just the tenant id.
In the API service the validators are defined in the library source file like Microsoft.IdentityModel.Tokens/Validators.cs. which validates the token based on the token validation parameters (Issuer, ValidateIssuer, signature etc..).
The issuer contains the URL for the actual tenant with the v1.0 and v2.0 endpoints.
Tokens always needs to match the endpoint they're requested from, and the tokens always match the format expected by the Web API your client will call using that token.
Why You need to validate the issuer because many services can generate tokens but you only want to trust certain source(s).
If we leave ValidateIssuer then middleware will not try to validate the issuer tenant and it would effectively mean that your application is open for anyone with a user in Azure AD.
For more information about the token validation please refer the documents Validateissuer and issuer

Validating Azure B2C Token in app that didn't authenticate user

I have a scenario whereby, a user would sign in/sign up to Azure AD B2C from a frontend application. There after they would make calls to an API application (with a JWT token) separate from this frontend. The requirement is that the API application validates a user's token and decides whether to execute the request. I can send the JWT token from frontend to API using the auth header. I can receive it in the API also. The challenge is to now validate that this token is not faked by a man-in-the-middle or just being abused by someone who got hold of it. I know each token comes with a timestamp and can be checked for expiration. However, this is not sufficient. I need to check it against Azure AD B2C somehow.
Update: the API is a NodeJs based Azure Functions app
You can validate the signatures of the token in your API app. A Token is signed by asymmetric keys.
Every user flow in AzureB2C has a associated metadata document which has all the details about the keys in the tag "jwks_uri"
"jwks_uri": "https://xxxxxx.b2clogin.com/xxxxxxxxx.onmicrosoft.com/discovery/v2.0/keys?p=b2c_1_pe",
you can fetch the key details from the link under jwks_uri tag and use it to validate the signature. Also remember these keys are rotated so you need to get the latest once every 24 hours.
Sample :-
https://github.com/azure-ad-b2c/samples/tree/master/policies/user_info
Doc https://learn.microsoft.com/en-us/azure/active-directory-b2c/tokens-overview
See this sample. The API is protected using the UseOAuthBearerAuthentication to verify the signature of the token. All Azure AD B2C tokens are signed JWTs. The sample code will find the metadata endpoint of your policy+tenant combination, and use the public key to ensure that the token signature is valid/unmodified and has been signed by the private keyholder (AAD B2C)

Azure AD OAuth Client Credentials Grant flow

Trying to set up Azure AD OAuth client credentials grant flow for my web api. I'm following the document in https://learn.microsoft.com/en-us/azure/active-directory/develop/v1-oauth2-client-creds-grant-flow. I have to expose my API to a 3rd party. I've created the APP in Azure AD (this is for the client that is requesting my API), generated the secrets and was able to get a response from oauth2/token endpoint. My questions are below:
What is the best way to validate the token? Is it by passing the JWT
(bearer token) as a HTTP header to my API, and then using the SDK to
validate the token
(System.IdentityModel.Tokens.Jwt.JwtSecurityTokenHandler)? I'm using
C#.
What is the significance of Azure AD -> App Registrations -> "My
API App" -> under Manage, Expose an API? It has an option to
"Authorize client applications". How could I use this feature to
conditionally block and approve the client applications?
I will have to share the secret, client id and the App Id Uri with the 3rd party for them to generate the token and I will validate the token when I receive it.
You're on the right track.
This answer, Azure AD OAuth client credentials grant flow with Web API AuthorizeAttribute Roles, will walk you through one way to do this, using the roles claim in the token to authorize the call.
You will need to:
define roles
create an App registration for each 3rd party
assign their application to your desired roles
You can then use the AuthorizeAttribute to map which roles can execute which controllers/actions, like so:
[Authorize(Roles = "Reader,Requester,Editor,Approver,Administrator")]
Token validation
Once you complete token obtaining flow, you receive a JWT bearer access token. From token consuming end (your service), you need to perform a JWT validation. This is done by validating JWT signature and Claims. One of the most important claim you validate is the audience (aud) claim which must be the identifier (ex:- your service's URL, an ID) unique to token receiving service. Where you register this ? That's your second question.
Please read through MS's guide on token validation which explains key points - Microsoft identity platform access tokens
Service registration
This is where you register valid token receivable endpoints (ex:- your api app). If you check your token request, you provide resource parameter which must match to registered identifier. This allows Azure to validate the token request and issue an access token the mentioned resource. You find this as aud claim in the token. Hope you got the connection now.
App secret
No, only the token obtaining party require the client credentials. Your API or any token consuming party does not need the secret. They only require a valid access token and token signing certificate details. certificate details are exposed at jwks_uri in openid-configuration endpoint.

What is the logic behind validating a user entity with Microsft Graph/Azure AD as the the authenticator of my API?

I already made the authentication flow with the Microsoft Graph/Azure AD authentication. Once I get the authenticated user's token I store them in his cookies. To validate the user's token I call the Microsft Graph API resource /me. This does not seem a good approach because basically everytime time a client does a request to my API, he is basically doing 2 requests because my API requests Azure AD for validation.
Is this a good flow?
No, it isn't.
Your front-end should acquire an access token for your API, which the API can verify using its digital signature.
The token will contain some info about the user as well as the app that acquired it.
The way in which the front-end acquires the token depends on the type of application.
Front-end single page apps use implicit grant flow for example.
Do note that you have to specifically ask for an access token for your API.
As long as your back-end is then configured with standard JWT Bearer authentication,
all is handled.
This is done by specifying the authority as your Azure AD tenant (or the common endpoint if it's multi-tenant),
and the standard bits for JWT authentication should download the public keys from Azure AD's metadata endpoint, which it can then use to verify validity of any access token it receives.
You do not have to validate tokens for an api that's not yours (issued to your AppId Uri).
For example, Graph validates the tokens that are sent to it (issued for "https://graph.microsoft.com).
If you build and register in Azure AD an Api of your own (say AppIdUri="https://myapi.mydomain.com"), your clients will request and receive access tokens with aud claim set to "https://myapi.mydomain.com".
The clients themselves don't need to validate the access token issued for your Api But your Api, when it receives those access tokens, has to validate them. The validations, among other things will validate the access token was issued to "https://myapi.mydomain.com".
Try out this sample, to get a good understanding around concepts of token validation.

Need help setting up Azure AD B2C SSO with Knack

Knack has an option to set up custom Single Sign On options. There are a few items I am unclear on as to where to find on Azure AD B2C. According to their help article, I must provide the following information for OAuth 2.0:
Authorization URL: the URL that your user is redirected to obtain permissions when they click the SSO button.
Access Token URL: used to obtain a token to verify future requests to the authentication provider to act on your user’s behalf.
Profile URL (OAuth only) - the URL where information about a user’s account can be retrieved. The Profile URL will be sent a GET request authenticated by the user’s token, and will be expected to return a JSON object.
For Authorization URL, I have tried to supply the 'Sign-up or Sign-in' Policy endpoint as that takes you to the login page. I think this is right however I am unsure.
For Access Token URL, I have tried either the Authorization Endpoint or Token Endpoint, but I'm not sure if those are right.
"authorization_endpoint": "https://login.microsoftonline.com/zyxelcustomers.onmicrosoft.com/oauth2/v2.0/authorize?p=b2c_1_zyxelcustomerssusi"
"token_endpoint": "https://login.microsoftonline.com/zyxelcustomers.onmicrosoft.com/oauth2/v2.0/token?p=b2c_1_zyxelcustomerssusi"
For Profile URL, I actually have no idea where I would find this on Azure AD B2C.
Single Sign On is new to me and I have gone through Azure AD documentation to try to help myself, but ultimately I am stuck.
Thanks in advance for your help and please let me know what other information I can provide.
Edit 9/26/2017:
This B2C documentation describes the purpose of Authorization URL and Access Token URL.
In short, Authorization URL is the endpoint to send the user to enter their credentials. If credentials are valid, an authorization code will be returned via URL to the designated Reply URL. The client app will then use the returned authorization code to request for an access token from the Access Token URL. If successful, the client can now attach the access token as a Bearer token in the Authorization header to authorize future API calls before the token expires.
Unfortunately, as of this time of writing, AADB2C does not support calling the Azure AD Graph or Microsoft Graph API for user profile information.
You should not need to provide a Profile URL since Azure AD B2C uses Open ID Connect, and not OAuth (similar protocols, but not identical). The Profile URL field is optional, so try configuring it without filling out the field.

Resources