问题
I have a .Net Core 3.1 program that hosts an Angular 10 application. The Angular application has a login page where the user can enter a username and password which gets sent to a login function in .Net Core which returns an oAuth token that is used in all calls to the api from Angular. The token only gets returned once the username and password are checked against a database. I would like to have a "Sign in with Microsoft" button on the login form that the user could click instead of entering a username and password. I would like the .Net core application to then call Azure Active Directory and get a token. If the user is already signed into Azure AD, it would just return the token, if not it would asked the user for their Active AD credentials and then return the token after successful log in. The .Net Core program could then interrogate the Azure AD token (instead of checking username and password in the database) and if it is ok it would return the oAuth token to the Angular app. I'm clear on most of this apart from the code in .Net Core to do the following:
- See if the user is already logged into Azure AD and if not prompt the user to log into Azure AD
- Make a request to Azure AD to send a token for the Authenticated user
Please help.
回答1:
When signing a user in with Azure AD there is a specific flow you should follow. Just like for the Angular library, the Microsoft.IdentityModel library can hide most of this complexity from you. Since you are using Angular, handling the login portion in your SPA will be simpler, but you don't have to.
There is a sample app that specifically implements AAD authentication with Angular and .NET Core: https://github.com/Azure-Samples/ms-identity-javascript-angular-spa-aspnetcore-webapi
There's also a tutorial that goes through several different scenarios including that sample app that you may want to explore: https://github.com/Azure-Samples/active-directory-aspnetcore-webapp-openidconnect-v2/
You are on the right path with having two login endpoints in your API. The main issue is having your API handle the actual login. If you need to have Azure AD authenticate a user, you should always have that handled by Azure AD in the browser. Since their Microsoft login isn't just for your site, it is a massive security risk for the user to give them to you at any point. If they have 2-factor enabled on their account, there is no way for your API to do the authentication even if you have their user name and password.
If the user is signed in to Azure AD but not your site specifically they won't be asked to sign in again. They may see the popup or redirect briefly, but Azure AD will immediately send them back to your site with a token for your API.
来源:https://stackoverflow.com/questions/63222266/how-can-i-get-azure-ad-authentication-from-net-core-program-for-angular-app