.Net Core Web API Azure AD Authentication and Authorization
Vložit
- čas přidán 29. 06. 2024
- In this video I have demonstrated Securing WebAPI with Azure Active Directory Authentication and Authorization using .Net Core. In Asp.Net Core Web API, Authentication is the process of obtaining some kind of credentials from the users and using those credentials to check the user's identity. Authorization is the process of allowing an authenticated user access to resources. Authorization refers to the process that determines what a user is able to do. For example, an administrative user is allowed to create a document library, add documents, edit documents, and delete them. A non-administrative user working with the library is only authorized to read the documents.
-------------------------------------------------------
In this tutorial, I have created an Asp.net Core Web API application with two roles Readonly and Readwrite and integrated it with Azure Active Directory for authentication. The roles created are used for authorizing the clients when they are sending the requests and registered the application in Azure Active Directory App Registrations. Also I have configured resource url in Expose As API section of App registration and configured roles in App Roles section of App Registration.
-------------------------------------------------------
After that, I have created two more app registrations for readonly and redwrite clients. I have assigned roles to these clients. Later I have shown accessing the Azure Rest API with postman using the ClientId, ClientSecret and other parameters to get the token from Azure AD and later used the token to access C# Asp.Net Core Web API which uses Azure AD authenticaiton and Authorization. Please note that we have to generate client secrets for both the client applications.
As Readonly Client has Readonly permission It is not authorized to access readwrite end point of Asp.net core web api that has Azure AD authentication and Authorization. However, ReadWrite Clients can access both the end points.
-----------------------------------------------------------
Later I have created, two .net Core Console applications one for ReadOnly Client and the other for ReadWrite Client and configured AzureAD details in the application. I have used AuthenticationContext, ClientCredential classes of Azure Active directory nuget package to access token from Azure Active Directory token end point and later used the token to Access Asp.net Core Web API application that uses Azure Active Directory Authentication and Authorization.
-----------------------------------------------------------
00:00 Introduction
01:40 Creating App Registrations in Azure
02:28 Configuring API App Registration Roles
03:52 Creating Asp.net Core Web API with Azure AD authentication and Authorization
10:45 Configuring Client App Registrations
12:45 Testing Azure Web API with Postman
19:00 Creating Console Applications to Access Azure AD to get token and access Web API
Buy Me A Coffee - www.buymeacoffee.com/azuretea...
This was very easy to follow and straight to the point. I was able to reproduce with a .Net 5 Api. Thank you for putting this together!
Thank you so much! I've been trying to figure this out for a while and your video really made sense of things. The documentation I've read explained how to set of parts of this, but seeing how you set it up, used postman to test it and implement it in a client app was exactly what I needed to understand what's going on
Thanks for taking time in providing the feedback. If want to know role based authorization, here is the video - czcams.com/video/5lRbtDSyjjs/video.html
wow...crystal clear explanation...included Roles, access via postman/code...everything at one place...Thanks for this video.
Thanks for the feedback. Please subscribe to the channel if you have not subscribed yet. Thanks.
Really well done, very applicable, and very easy to understand. You separated the different steps quite nicely in chunks that made it simple to understand the different pieces of the puzzle on their own, as well as how they all tie together in the end.
Thanks for taking time to provide feedaback. Please subscribe to the channel if you have not subscribed yet. Thanks.
Excellent explanation! To the point and in detail! Loved it!
Thank you. In this video, I have shown authorization for applications. If you want to know authorizing users, watch - czcams.com/video/5lRbtDSyjjs/video.html . Please subscribe to the channel if you have not subscribed yet. :-)
Great video! I was looking for an explanation like this! Thank you so much!
There are videos on assigning roles to the user too. please checkout the channel. If you have not subsribed to the channel, please subscribe
Thank you very much for this super clear and helpful content 🙏💫
Very Nice, Very good explanation of the concept with use case and example. straight to the point and crisp and clear
Thank you. If you want to know, integrating Angular with Azure AD + Web API with Azure AD please refer - czcams.com/video/98T1CumHofI/video.html
Thank you very much.Very Practical and Very Simple Example. It is Great !!!!
Thank you. Here is the video for assigning roles to a user - czcams.com/video/5lRbtDSyjjs/video.html .
Simple and easy to understand !
Thank you for the feedback. Please subscribe to the channel if you have not subscribed yet.
Thank you! A well documented bare bones example. A few minor updates for .Net 6 and I'm up and running.
Thank you for the feedback. Please subscribe to the channel if you have not subscribed yet.
May I request what changes you did in code for .Net 6. I am getting 401, while following same steps as mentioned in the video. Hope the video is updated with .Net 6/7 ASAP.
Just what I was looking for
Thanks so much
please subscribe to the channel if you have not subscribed yet. Thanks.
The best I have ever seen, so well explained …thanks a million ❤
Thanks a lot for the feedback. please subscribe to the channel if you have not subscribed yet.
Excellent video,Thanks
Gold content on youtube Thank you man
Thanks for your words. It motivates me to make more good tutorials :-)
Thanks a lot! Really helpful and easy to understand
Glad it helped. There are other videos in the channel where you can assign roles to users unlike in this video where we assign permissions to applications.
Also, This video shows more easy ways to add the dependencies related to azure sdk using Visual Studio capabilities.
czcams.com/video/5lRbtDSyjjs/video.html
Please subscribe to the channel if you have not subscribed it.
Thanks for the valuable content
Great post. Thank You.
Thank you. There are more in the channel. Please take a look and subscribe if they are relevant to you. .Here is the link - czcams.com/channels/jT5Tn4qMkVkSYeP-L6gLVw.htmlvideos
Really good video
You're god, explained perfectly
well explained, keep it up. 😍
Thanks for the feedback. Please subscribe to the channel if you have not subscribed yet.
Good Explanation
Thanks a lot for your kind feedback. There is a lot in the channel. Please subscribe to the channel if you have not subscribed yet. Thank you.
Excellent job thanks alot, I request you to cover topics of most used Azure .NET services and Interview Questions realted
Thanks for the feedback. sure. I am a lot interested to make videos in practical approach rather explaining them theoretically. Please subscribe to the channel if you have not subscribed yet.
Very nicely explained, try to add Role based authorization. Thank you.
Here you go - czcams.com/video/5lRbtDSyjjs/video.html . There is a lot in the channel. Please subscribe and share it with your friends.
That was really helpful, Thank you Sir.
Can you also please share in short how we can implement OpenID Connect for Web API in Azure APIM?
New subscriber here! Good Video.
Thanks a lot.
Love it❤❤
thanks. please subscribe to the channel if you have not subscribed yet.
Excellent
thanks for the feedback. please subscribe to the channel if you have not subscribed yet.
super helpful. loved the content and the clarity of the explanation as well. Do you have any videos for the delegated permission ?
czcams.com/video/hBGUg1TagPE/video.html . This is the video which shows delegated permissions with Graph API. If you want to define your own roles for the web api, per the documentation we need to go for azure premium AD and that costs $3/month per the user. Only organizations have that :) .
Very nice video ... Can you help me or guide me ..how I can set up same kind of SSO as u have shown but only thing is when user tries to access client application , it should redirect to Microsoft login page where user will provide their own individual credentials and validate against azure ad ..
@@pranavkumar8412 check if this helps - czcams.com/video/S_xDAB_s-GM/video.html
@@azureteachnet thanks for help .. actually I have successfully set up SSO with my web API (asp.net core) .. now my question is ..this web api is called by another application which is react js based application .. and I want to show this Microsoft login page there .
I am not able to do that .. client is calling my web api via ajax call ..
@@pranavkumar8412 client has to implement something like this. docs.microsoft.com/en-us/azure/active-directory/develop/tutorial-v2-react . Soon I will be posting a video for angular for the same.
Great
Thanks for the feedback. please subscribe to the channel if you are not subscribed yet. In this video, I have added authentication packages manually just to understand the concepts. However we can use visual studio connected services option and no need to write code manually. The video is in the channel. please check it if you are interested. Thanks
Hi Thank you so much for this. Can you please show how to get the Domain Password Policy for Azure AD using the Graph API?
Great video and explain all steps very well !!! I need to use it for Delegated Permission in place of Application Permission any link or video you have, please share.
czcams.com/play/PLW6IC4y81fVucShJzKVKA5YOwO1H6R2kz.html
This playlist has all ways to connect to graph api including delegated permissions.
Please subscribe to the channel if you have not subscribed yet.
Is this useful for a real in production scenario? on what kind of architecture it could be applied?
Thanks for your content, it is very informative and useful
Yes it is useful. In this video, I have shown manual steps to add the dlls. Visual Studio connected services has scaffolding option to add authentication where you need not write code at all. It will be generated. VIdeo for the the same available on the channel. Thanks.
Great video, I have a question. The custom app roles defined in Azure AD App reigstrations ReadWriteClient and ReadOnlyClient, are these roles specific to the Client application? What is the purpose of entering them in Azure AD app roles?
Roles are specific to API. we are assigning them to the client applications. Purpose of entering them into azure ad app roles is , when the access token is created by azure, it will create it with appropriate roles based on scopes provided while requesting the access token. Here is the video for assigning roles to User - czcams.com/video/5lRbtDSyjjs/video.html .
Please subscribe to the channel if you have not subscribed yet.
@@azureteachnet Thank you!
On PostName, you are calling it in Postman as a Get instead of Post so, I am a little confused seeing a Get with a body may be I'm not up to date? Thanks
Those are being posted as xxx-url-encoded paremters. They will not be sent in body but instead on ulr parameters. But of course, latest versions of postman do allow body for get method.
Very useful video. Understood thoroughly.
One question though - I need to use Azure AD auth, JWT token based auth, Google/FB Auth in a Web API.
Azure AD auth is for admin users while rest of the auths are for external users.
How do I make them all work in a single API solution?
Do you have some pointers?
A simple solution will be to create 2 API solutions - one for Azure AD (admin users), another for JWT and Google/FB Auth.
But this would encourage code duplication - Entities, Models, DTOs, Services, Repositories etc will have to be duplicated to some extent to serve both the API solutions.
Can you please provide some pointers?
Thanks a lot
We can go with the approach that you have mentioned. But App services/Api apps built in support for Azure AD, FB, Google, Apple, Twitter etc authentications. We need to add authentication providers to the app service in Authentication section. I have created a video for both Microsoft and Facebook auth providers. You can refer to - czcams.com/video/sd6pmmNY1PY/video.html. We can add the external users in Azure AD and assign them roles in enterprise applications. I tried adding external users in my azure ad, but never tried adding roles. I think, If we do so, azure should give the token with the roles assigned even if you logon with external authentication providers like google and facebook.
@@azureteachnet Azure Global Admin wouldn't allow addition of external users to AD in my case. However Azure AD B2C is used for external users, it does have Google and Facebook auth providers. I'm not using B2C.
I have a solution though. I created 2 API solutions, and have encapsulated all the shared logic into dlls ultimately publishing private nuget package via Azure DevOps. This nuget package can be used in both the API solutions.
Hi ,
I am getting the below
Bearer error="invalid_token",error_description="The audience '00000002-0000-0000-c000-000000000000' is invalid" while trying to access the endpoint
Great article!. Thank you. Could you please post the source code?
sure
hello, when i try to access with an user i get : WWW-Authenticate: Bearer error="invalid_token", error_description="The signature is invalid" in the response header. Can you help me ?
please check if the user has required role. Go to Active Directory-->Enterprise applications-->your app registration-->Users and Groups-->assign the role to the user
Can you please add a demo to authenticate and authorize by logged in user ?
Here is the video - czcams.com/video/5lRbtDSyjjs/video.html Please subscribe to the channel if you have not subscribed yet.
Can I use Angular MSAL to authenticate at the Api? If I can, how?
Here is the video - czcams.com/video/98T1CumHofI/video.html
Please subscribe to the channel if you have not subscribed yet. Thanks
Thank you sir for the tutorial. I was able to achieve it and make it more in ASP.NET Core WebAPI. Now, I'm trying to incorporate and connect to my react.js to the created webapi based on your tutorial. Any help sir? Connecting from react.js to this kind of web api you created in this tutorial?
My Next video is connecting angular app + azure AD to Web API+Azure AD. That video may help you. I have future plans to create a video for react JS too.
@@azureteachnet Thank you so much, sir! Thanks for new learning. You really helping a lot of people around the world through your tutorials!
1.API (managed by other team) to API (my team) clientid/secret token based authentication can we implement in this way means In this case console app,web app and web api all are managed by you..Example you only having web api and Conole app and web app are external for you but same organization. Console app can take Write permissions directly here. That control we should have right.
2. Can we implement both token based + certificate based authentication in .net 6 single web api or .Net framework Web API. Please suggest
1.API to API client id/secret based authentication is possible. I am going to post a video in a week or two.
2. Web API with multiple authentication schemes is also possible.
Thank you very much..Can you please provide any reference links
1. docs.microsoft.com/en-us/azure/active-directory/develop/scenario-web-api-call-api-overview
I will post video by next Tuesday on the same.
2. Do you want to implement mixed authentication (token + certificate) or as Individual authentication schemes.
@@azureteachnet I wanted to implement mixed (token+ certificate ) based authentication for API to API..Thanks
Nice video, is it possible to set the roles per user?
yeah.. its possible. But needs Azure AD Premium which costs $3/month/per user.
@@azureteachnet I kept exploring and I finally manage to add a role in the app registration then I assigned in the enterprise application, I see the role in my token after logging in, I am not sure if this is the right approach but I don`t have any subscription attached
@@dacceto That is fine. But still here you are assigning role to an app registration but not to an individual user. Please let me know if you could assign a role to an individual user on an api access and do authorization without Azure AD premium.
@@azureteachnet oh no, I just created the role in the app registration, but I assigned to the user in the Enterprise Application/User&Groups :S
@@dacceto ok
What if the client secret compromise how to apply more security
You can use keyvault and keep your secret in it. If it is compromized, you can generate a new one. You can use certificates in a combination with appid and secrets so you can make sure that only the valid clients who have the certificate can access your application. You can block all other ips except the white listed ip addresses. It all depends on how critical your applicaiton is.
Hi how can I implement refresh token of msal in angular
Check if this helps - czcams.com/video/vjpKYSmvRKQ/video.html . Please subscribe to the channel if you have not subscribed yet. There are more azure videos in the channel and more to come. Thanks.
I am not getting startup.cs file why is it so? Actually I have not created azure account. Is this is the thing
Which version of .Net you are using? In .Net6 we dont have startup.cs
Can we use our own login page to azure ad user login if yes then how
you can create a login page and use Azure Ad's OAuth2.0 end points and send http requests to Azure ad and validate the user BUT IT IS NOT RECOMMENDED BY MICROSOFT.
How to add forget password with my login page any idea, I'm done login but how to forget password no idea
@@vijaymani6552 you have to enable the policy on Azure AD. This link will help you - docs.microsoft.com/en-us/azure/active-directory-b2c/add-password-reset-policy?pivots=b2c-user-flow
hello, when i try to access with an user i get : WWW-Authenticate: Bearer error="invalid_token" :c
please check if the user has required role. Go to Active Directory-->Enterprise applications-->your app registration-->Users and Groups-->assign the role to the user
@@azureteachnet I checked it and I have the default permissions and it doesn't work for me
@@franciscogajardo8498 Are you trying to access the application as a user or the way it is shown in the video where there are two applications accessing the api instead of logged in user?
@@azureteachnet I solved it but I have another question, sorry I'm new to this azure. My question is how do I have to do it if I need to register people, to later have an api that receives the user and returns the token to be able to access my other apis, I don't know if I'm explaining myself well
@@franciscogajardo8498 Do you want to assign access to the users on your apis?
can you drop here github link of this demo
github.com/AzureTeachNet/AzureTeachTutorials/tree/Angular_WebAPI_AzureAD_Authentication_Authorization
This is not exactly the same. But you can find both Web API and Angular authentication with Azure AD. Please subscribe to the channel if you have not subscribed yet. Thanks.
Hi bro
I need help azure ad authentication with Vue js and .net core web api.
I am struggling from last one month.
I will pay you for your work
Thanks for your interest. I have worked on vue.js but very less. Let me create a sample app with vuejs+azuread+webapi and get back to you. If I complete, will definitely help you. Thanks
I followed the same steps when i call the api with token still im getting Unauthorized, any one face this issue
How you are trying to access the API. Using App registration or with the logged in user?
@@azureteachnet using app registration, I use cliend app registration to get token, and pass it to web api same steps as you did. Still it says un authorized
same issue, i did what he did and postman ask me to sign in to my account for the GET request :/
@@Exosia Please post screenshot of your postman request in facebook.com/groups/203337538580278 facebook group. I will try my side and let you know the issue.
Face same issue. I have moved the Authorize Attribute to the top of the class and it worked.
source code no Attached
will attach by tomorrow EOD. Thanks.
Kids please dont do AsyncMethod().Result
😀 agree with you. It blocks the execution until it gets the result. However, here my focus is different than C# basics. Thank you.
And the Example?..... why don't you show the result?-----BAD top bad!
Did not get you. Could you please let me know which result you want and what you are expecting. If possible mention the time of the video.
Good Explanation and clearly able to understand. I m having do we have any other process for token fetching - because the acquiretokenmethod(context.AcquireTokenAsync(resource,clientCredential).Result.AccessToken;
) is deprecated in .net core 6.0, any alternative way to fetch token.
You can have dependency of ITokenAcquisition and using this interface, you can get token.
sir i used Entity framework =
[Authorize(Roles = "Api.ReadOnly")]
[Route("GetName")]
[HttpGet]
public async Task GetLoginUser()
this is not working showing unAuthorized 401 , please ,please,please help