ReactJs FE and Django Rest Services with Azure AD for authentication & Authorization - reactjs

I'm having a Frontend application built in Reactjs connecting to Azure AD using msal for authentication. After authentication, the user needs to click a button which calls a Django rest API which is also authenticated using Azure AD.
React FE and Django connects to two separate App registrations in Azure AD. Even thought 1) FE is added to Django's App registration as known client 2) Django is exposing the API and the scope is given consent.
When the authenticated FE sends requests to the Django Rest service with Bearer token,
it fails to authenticate the request saying 'invalid token'.
I'm able to authenticate FE and Django rest service separately but authenticated FE is not able to connect to the Django Rest service. Please share your thoughts on what else needs to be checked or any solutions.

Please check if any of these configurations can be worked around
Check if you have given your react app’s URL in the redirect URL in portal and code , so that once the Azure AD validates the user and it’ll return back to your react app with ID Token.Also, enable Access Token and ID Token.
Check if you have created a scope for your web api (in Azure Portal > Your API > Expose an API). Then configure it on your client app on the API Permissions menu tab. Then add it on your scopes collection in code settings.Also, add grant admin consent for that API permission.
Check the manifest of your azure ad app: Below value is probably null or one, should be two: If you are using v2.0 endpoint,
"accessTokenAcceptedVersion": 2,
If you are using v2.0 endpoint, the scope should be api://{server_client_id}/.default.
In the code setting.py for your application, you'll need to provide the authority to which your web app delegates sign-in. (ex: authority: 'https://login.microsoftonline.com/(your tenant id>',)
auth: {
clientId: '232a1406-b27b-4667-b8c2-3a865c42b79c',
authority: 'https://login.microsoftonline.com/e4c9ab4e-bd27-40d5-8459-230ba2a757fb',
//
}
When we perform a token validation, Check your jwt token in http://jwt.io
Audience: The token is targeted for the web API.
"aud" value that is being generated for JWT token by azure is also controlled by "accessTokenAcceptedVersion" property in AD application manifest.(see if issuer or iss has v2 to confirm as v2 endpoint )
If you have set the access token accepted version to 2, then the client id and audience needs to be same (i.e. no need to write api:// in audience)
Note that Implicit flow is the only flow supported for SPA. Authorization code flow is intended for webapps, mobile and desktop apps but not for SPA.Please refer this document
References:
See how to configure Azure AD and how to determine the settings for
django-auth-adfs.
You can check this and find your use case scenario.
Check v2-supported-account-types for authentication-flows
Check OAuth2.0 On-Behalf-Of flow

Related

Spring OAuth2 Single Page Application Integration to Azure

I have been tasked with integrating Azure Active Directory Authorization into one of our applications and have tried out some of the samples with relative success.
I have a Javascript SPA application (GoogleWebToolkit) that communicates with a Spring REST (not Boot) API. The Rest API is currently secured with Spring Security and login URL username/password etc.
I want to change this to use Azure OAuth2.
Being new to OAuth2 I'm trying to figure out if I should be using either of the following Spring options.
With this option all the configuration is done at the server side, client id,secret
If I do a href from the SPA front end to 'oauth2/authorization/AzureAD' URL, its sends a redirect to the Azure Login page, allows authentication and redirects back to what redirect URL I enter into the Azure AD console configuration. This works to a degree but trying to extract the token and pass it back is not working so far.
http.oauth2Login()
.clientRegistrationRepository(clientRegistrationRepository())
.authorizedClientService(authorizedClientService())
.authorizationEndpoint()
.authorizationRequestResolver(
new CustomAuthorizationRequestResolver(
clientRegistrationRepository(),
#Bean
public ClientRegistration clientRegistration() {
ClientRegistration.Builder builder = ClientRegistration.withRegistrationId("AzureAD");
builder.clientAuthenticationMethod(ClientAuthenticationMethod.CLIENT_SECRET_POST);
builder.authorizationGrantType(AuthorizationGrantType.AUTHORIZATION_CODE);
........................
or
I haven't fully tried this option yet, but I think it involves doing the authorization directly from the SPA javascript front end, put all the values for the client id/secret into the javascript FE etc, and then passing the once acquired token via the Auth header for validation by the server side. Like at https://www.baeldung.com/spring-security-oauth-jwt
.oauth2ResourceServer()
.jwt()
.jwkSetUri("https://login.microsoftonline.com/common/discovery/v2.0/keys");
Could someone confirm where I should be using Option 1 or 2, and if I am understanding things properly?
Your understanding is correct in option 2. As per above scenario, let’s consider Front End Application which is Single Page Application (Java Script) to be OAuth Client App to orchestrate the process of obtaining access token and then grant access to resources from Spring back-end application.
So, here client Application need to be registered in Azure AD to acquire the access token secured by Azure AD.
We recommended MSAL libraries which helps to acquire tokens from the Microsoft identity platform and handle token in many ways to authenticate users and access secured web APIs.
Both the applications (front end and back end) need to register in Azure AD based on the scenario.
Update client-id, tenant-id, redirect URI to front end application configuration file based on application registration in Azure AD.
Back-end application also need to be registered in Azure Ad to secure by Microsoft Identity which can then define the delegated permissions(scopes) your API exposes.
Then business logic needs to add in back-end application to determine what is allowed or prohibited based on these scopes in access token.
To authorize the client request in Spring application:
Users will start by authenticating with a username and password in front end application.
Once authenticated, the client will receive a JWT representing an access token.
The client will include the access token in the authorization header of every request to a secure endpoint.
The resource server will validate the access token and determine if it has the right permissions, using the information within the token.
In this case, Spring serves as resource server and not acquiring any token in the back-end application .
Security Configuration in Spring provides numerous methods to add filters to the HTTP request to authenticate each request.
Here,
http.cors() will allows Cross-Origin Resource Sharing (CORS) checks to succeed.
All the requests need to authenticate before passing to the application(controllers).
Spring application serve as a resource server and authentication should be provided via JWT access tokens and further validate the roles and scopes in the application’s controller using #AllowedRoles annotation.
Our JWT access tokens are signed by Azure AD and application should check if their signature is correct. Azure AD has an endpoint with the public key to do so, which need to configure in spring application.
Also, as mentioned, we will need access token to call the protected back-end application because contents of the token are intended for the resource (back-end API) to perform authentication and authorization.
To validate the token, you can search the keys endpoint in the discovery document and then provide this JSON web key (JWK) endpoint straight away where JWK URI can be found.
# application.properties
spring.security.oauth2.resourceserver.jwt.jwk-set-uri=https://login.windows.net/common/discovery/keys
Note: The flow would be same to get the access token while integrating with Azure AD. i.e in Spring boot or in spring.

If possible, how to register front-end and back-end in a single application in Azure AD?

I have an application stack with a React SPA frontend and an Asp.net core web-api backend. Both resources had been successfully registered in AzureAD each with its own app and the authentication and authorization processes are working fine. However, would it be possible to use the same registration for both the front and backend in AD?
When using the AD Application ID from the backend in React:
auth: {
clientId: "xxxxxxxx-xxxx-xxxx-xxxx-xxxxxxxxxxxx",
authority: "https://login.microsoftonline.com/<tenantId>",
redirectUri: "http://localhost:3000"
}
I get the following error:
ServerError: invalid_request: AADSTS90009: Application 'xxxxxxxx-xxxx-xxxx-xxxx-xxxxxxxxxxxx'(api://xxxxxxxx-xxxx-xxxx-xxxx-xxxxxxxxxxxx) is requesting a token for itself. This scenario is supported only if resource is specified using the GUID based App Identifier.
I am using the MSAL library for the frontend.
Both the applications (front end and back end) need to be registered for sure in Azure AD.
As you are using client id of backend which is api to be secured , the Error is occurring.
Update client-id, tenant-id, redirect URI of front end application not backend api in configuration file based on application registration in Azure AD.
Then make sure to expose an API and grant admin consent to the API with required permissions.
Yes, this is possible. Your provider configuration looks correct, so check to make you app registration is setup properly. You will need the following things:
An SPA platform configuration with a redirect URI of http://localhost:3000
Add a scope (under 'Expose an API') and make sure your Application ID URI is created
Use the new scope in your MSAL authentication template

Azure AD with Single Page Application and ASP.Net core web api: how to access all relevant tokens?

Our application is an Angular SPA with ASP.Net Core Web API. The identity is provided by Microsoft Identity Platform (Azure AD) and authentication is provided by the same. The authorization is done in Web API basis "Application Roles". These "Application Roles" are held in the Azure AD directory (defined in the Application's manifest and assigned on the tenant domain to users).
The Angular SPA receives the tokens from Azure, as per these instructions. The relevant tokens that are issued are: an AccessToken for my Web API (following these instructions), an AccessToken for calling Graph API (following the same instructions) and an IdToken that includes the "Application Roles" as roles claim (this id token seems to be included automatically once roles have been assigned).
The problem I face is that I need to pass concurrent tokens to my Web API, but with the HTTP interceptor I can only include 1 token in the header request. For example, I need the first AccessToken to proof authentication to the Web API and I need to include the IdToken such that the Web API can perform authorization.
Q: How can I call my Web API with multiple tokens, when these tokens are all issued to the SPA and need to be included in the HTTP call to my Web API?
No matter whether you want to get Microsoft Graph data, the way you used to get Application role is incorrect.
An id token cannot be used to perform authorization for your Web API application. You have to use access token. See this answer to learn about the usage of id token and access token.
So you have to use an access token rather than id token.
In this case, you configure the app roles in the Azure AD app which represents Angular SPA (the front).
In fact, you should configure the app roles in the Azure AD app which represents ASP.Net Core Web API (the backend). Then you can get the "Application Roles" as roles claim in the AccessToken for your Web API.

Can't access Azure Appservice protected by AAD from Postman

I have an app service say https://blahablah.azurewebsites.net to which I have hosted an ASP. Net web api project(An api that returns list of to do items by GET request), so that I can access the API without any authentication using https://blahablah.azurewebsites.net/api/TodoItems as i had TodoItems as my controller.
Now when I create an Azure AD and set Advanced Authentication of the app service; I can't access the api on the previous endpoint; When I use postman with the client id, secret, auth and token endpoints, it says my redirect URL is not valid;
So what should be my redirect URL? How can i successfully send a GET request from POSTMAN?
Update 1: My endpoints were wrong, and I corrected it to login.microsoftonline.com instead of login.microsoft.com, so I'm getting the access token, but when I'm sending a get request to above api with that token in header, it still says 401 unauthorised.
And i'm using redirect url as https://www.getpostman.com/oauth2/callback
Update 2: Here is my configuration
1)I have 2 AAD apps: blahablahAAD aap and PostmanAAD app
2)For app service, blahablah i use the first AAD app thru Express authentication of Azure Active Directory;
3)I have made https://blahablah.azurewebsites.net/api as the first AAD app's Application ID URI, and hence am able to expose https://blahablah.azurewebsites.net/api/TodoItems with TodoItems as scope.
4)I have added the API to "API permissions" of the first AAD app; (uptil now it works well in browser asking me for login and then taking me to the endpoint;)
5) For the PostmanAAD, I use it's client id,secret in Postman and get the token; I send it as request header to API;but it failss
6) I have added PostmanAAD's client id in "Expose API->add client application" of blahablahAAD.
7) I have done step 4 for PostmanAAD also
8) I have granted admin consent to all in default directory.
Note: I haven't added any authorization related code to my ASP .NET web api project that i hosted as app service, but i believe i can access it without writing code(as in AAD will do the task for me).
Set resource url as the guid of the azure ad app instead of application id url.
Click azure ad app and choose Application Id in Overview.

Refresh token flow in Azure Active Directory with a federated Google user

I have set up an Azure Active Directory tenant with direct federation to Google. Next to that I have a .NET core web application using the OIDC code flow for getting both id_tokens and access and refresh tokens. The access token is used to call my API which is working fine.
Now the problem is whenever I use my refresh_token to get a new access_token I receive a new access_token, but no refresh_token. So I can only refresh once.
I only have this issue when authenticating with my Google account using direct federation. When I authenticate using a tenant native account I can refresh unlimited.
We have two multitenant Azure AD app registrations as described here. One for our single page application and one for our API. In our single page application backend we use the OpenIdConnect middleware to authenticate against Azure AD. Note that we are not using the common endpoint, but the tenant specific endpoint because otherwise direct federation does not work. We can reproduce this issue by intercepting the refresh token in the OnTokenResponseReceived event of the OIDC middleware and initiating the refresh flow as stated here (by using Postman for instance). The response is successful, but does only contain an access token, no refresh token.
Is this behavior by design?

Resources