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

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

Related

Azure AD integrate with frontend React and backend GoLang

I have a separate structure for backend using GoLang Gin and frontend ReactJS and would like to integrate the Azure AD Oauth2 login.
However, it's ok to authenticate GoLang App or React App, but how to pass the auth info to the backend when I authenticate in frontend using msal-react?
In my current backend API, I use JWT like this to protect APIs:
v1.Use(jwtauth.JWTAuth())
or should I authenticate the backend and pass the info to frontend? but I cannot get it to redirect(Azure login) since they are in different port...
Thanks!
The typical pattern is:
Front-end (React app in your case) uses msal (or other compatible library) to redirect the user to login
Front-end acquires access token for back-end using a scope defined in API app registration (or same app registration)
Front-end attaches access token to back-end requests
Back-end validates access token (signature using public keys from Azure AD, expiry time, audience, issuer, scopes etc.)
In .NET we configure an "authority" for JWT authentication, e.g. "https://login.microsoftonline.com/", and the authentication handler then downloads metadata + public keys from "https://login.microsoftonline.com//.well-known/openid-configuration".
It might be possible to configure something like this for your library as well.
Scopes you typically have to check yourself.

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

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

Migrate from msal angular to azure webapp authentication

I'm working on a web application deployed on an azure webapp authenticated with Azure AD.
It is mostly based on the angular template for ASP.Net Core. The backend hosts the frontend in a ClientApp directory.
For the authentication, the frontend works with the msal-angular plugin which on access redirects to the Azure AD authentication page. After login, the login page redirects back to the frontend, which catch the token, and makes all the calls to the backend with the token in the authorization bearer header.
The .Net Core backend is configured with :
services.AddAuthentication(AzureADDefaults.BearerAuthenticationScheme)
.AddAzureADBearer(options => Configuration.Bind("AzureActiveDirectory", options));
Finally, to make all these works, I have in the Azure AD app registration one entry for the backend and another for the frontend.
This works well, but we want to move away from that to use the Authentication directly on the webapp.
This way we could secure even more the application which would not even be downloaded if the user is not authenticated.
How do I manage to do that ?
Do I need to remove all authentication code from the backend and frontend ?
Do I still need 2 entries in the app registration on azure AD or one is now enough ?
How will I know which user is connected ? Actually I use the IHttpContextAccessor to get the UPN Claim.
Thanks for the help

Retrieve Access Token within a AAD secured Azure Web App

I have an Angular4 Application hosted in an Azure Web App and a .NET core Web API hosted in an Azure API App.
The API is secured with Azure Active Directory. Currently I use ng2-adal to aquire an access token which I inject to the headers to perform my API calls.
Now I try to remove the ng2-adal module and secure my Web App with the Authentication / Authorization feature using the same ClientId (like the API). When I browse to my website I get redirected to the AAD login and after I successfully login, I get redirected to my site. Now I wan't to call the API (that is secured with the same ClientId) within my Web App but can't find a way to retrieve the token.
Is there a way to retrieve the access token within my Angular App in this scenario?
It looks like the token is stored encrypted within the AppServiceAuthSession Cookie:
The AppServiceAuthSession is cookie which is different than a token. In this scenario, you need to modify the config of Azure app to make it acquire the access_token for the web API.
We can use the Resource Explore to modify the settings like below:
1 . locate the angular web app
2 . locate the config->authsettings(resource is the clientId of Azure app which used to protect your apps)
"additionalLoginParams": [
"response_type=code id_token",
"resource=3fa9607b-63cc-4050-82b7-91e44ff1df38"
],
3. config the redirect_uri for Azure app like below:
https://appfei.azurewebsites.net/.auth/login/aad/callback
Then after you login in the angular app, you can get the access_token via the endpoint:
https://appfei.azurewebsites.net/.auth/me
Then we need to protect the web API using the Advanced Azure Active Settings like figure below to enable the access_token could call the web API:
I've been working on this for a week.
So, I'd like to share how I got it.
I was able to have authentication for my app using AAD.
I have AppServiceAuthSession in my cookies storage.
Then on my application, I called the auth/me API.
https://yourwebsite.azurewebsites.net/.auth/me
So, it's like:
this.$http
.get('https://yourwebsite.azurewebsites.net/.auth/me').then(response => {
console.log(".auth/me", response)
}, err => {
console.log("Error: ", err)
})
I'm actually using Vue. calling your HTTP might be different.
And that's it.
I basically called the auth/me API to retrieve the information I needed.
P.S. You need to be authenticated of course.
found this solution:
just need to add your app url on
Authentication / Authorization-> ALLOWED EXTERNAL REDIRECT URLS
so the webapi will automatically accept those cookies.
ps: make sure your ajax request is passing those cookies on it.

How to enable multitenant authorization (AngularJS <-> Azure AD)?

How can I enable authentication with a multitenant AngularJS single page application calling a multitenant service Web API using Azure AD?
This is the high level flow I am trying to enable:
Multi-tenant AngularJS application [ClientApp] -> Multi-tenant ASP.NET Web API [ServicesApp]
I have a multi-tenant AngularJS application which requires Azure AD login using ADAL for JS (OpenID Connect). That web application is registered as a multi-tenant application ClientApp in a developer Azure AD, which I'll call DevAAD. I consented to use this ClientApp application in another Azure AD, which I'll call Tenant1. Once a user from the Tenant1 directory logs into the web application with their credentials into the login.microsoftonline.com portal, they are able to access the web UI. However, the UI is unable to call Web APIs on behalf of the user using the OAuth 2.0 Implicit Flow. This is the error message I am seeing in the Javascript code:
AADSTS65001: The user or administrator has not consented to use the
application with ID '<ClientApp_ClientID>'. Send an interactive
authorization request for this user and resource.
There is another Azure AD multi-tenant app representing backend Web API services called ServicesApp that is registered in the same DevAAD directory as the ClientApp UI application. The client ID and app ID URI of ServicesApp are the valid audiences for those services. This ServicesApp application has been consented to in the same Tenant1 directory. When invoked from a native client application with permissions to ServicesApp, the services are authorizing users from the Tenant1 directory using the OWIN middleware provided in System.IdentityModel.Tokens.Jwt 4.0.0 and the [System.Web.Http.Authorize] attribute in the controller.
Configuration details:
ClientApp
Azure AD application manifest has availableToOtherTenants set to true and oauth2AllowImplicitFlow set to true. ClientApp has permissions to access ServiceApp Azure AD application.
The AngularJS application has the following configuration:
adalAuthenticationServiceProvider.init(
{
tenant: 'common',
clientId: <ClientApp_ClientID>,
endpoints: { <ServiceEndpoint> : <ServiceApp_ClientID> }
}, $httpProvider);
ServiceApp
ValidateIssuer is set to false in TokenValidationParameters object in WindowsAzureActiveDirectoryBearerAuthenticationOptions configuration object passed to IAppBuilder.UseWindowsAzureActiveDirectoryBearerAuthentication()
"
knownClientApplications" property in "ServiceApp" Azure AD manifest is
set to ["<ClientApp_ClientID>"]
I have not been able to locate any examples of a multi-tenant web application calling multi-tenant Web APIs, specifically a single page application built with AngularJS. How can this be implemented with Azure AD?
You should try generating a Authorization Code URL using the template described here.
You can also copy this and replace the values with your own:
https://login.microsoftonline.com/common/oauth2/authorize?client_id=<appid>&response_type=code&redirect_uri=<replyurl>&resource=<resource>&prompt=admin_consent
Note at the end of the url I added the query string: "prompt=admin_consent".
This is something that only a company administrator can do, and it will consent to your app for the entire tenant, so that no one else needs to consent in the future. Note that you can change this to "prompt=consent" if you want to only consent at an individual user level, or remove it all together if you do not want to force a consent prompt.
Let me know if this helps!

Resources