简体   繁体   中英

C# Web API 2 & Angular - Microsoft Account Authentication

I've asked the question below a couple weeks ago and I didn't get a working answer. Or maybe just not suitable for my case.

C# Microsoft Authentication Get logged user from controller

So I thought maybe I wasn't asking the right question. What i'm trying to do is create an app which has a C# Web API 2 backend and an Angular 2 frontend. Now, I want that my authentication be using people's Microsoft Account which means this will be an external authentication.

What's the best way of doing this? It would be very much appreciated if you can give a link on a blog or article that explain what I'm looking for. On my link above I've used msal.js and so far it was working fine for me until I had to get the logged user's details. It was possible from Angular's side but I want to do it in Web API so it is more secured.

Thanks in advance!

From your code in the previous post, it looks like you need to read from the ClaimsPrincipal instead. ClaimsPrincipal is the implementation of IPrincipal when you use OAuthBearerTokens, so of course you can get the username from CurrentPrincipal.Current.Identity

From this documentation

https://msdn.microsoft.com/en-us/library/system.security.claims.claimsprincipal(v=vs.110).aspx

https://docs.microsoft.com/en-us/azure/active-directory-b2c/active-directory-b2c-devquickstarts-api-dotnet

public IEnumerable<Models.Task> Get()
{
    var user = ClaimsPrincipal.Current;
    ...
}

If you are using OpenId, you have claims that are returned when user is authorized. I am assuming you are using Azure B2C for authorization in which case you can select clams that will be returned as part of token.

For example, if you want to fetch user id:

var userId = ClaimsPrincipal.Current.FindFirst("http://schemas.microsoft.com/identity/claims/objectidentifier")?.Value;

Email:

string userName = ClaimsPrincipal.Current.Claims.Where(x => x.Type == "emails").FirstOrDefault()?.Value;

It depends what claims your authorization has returned, easiest way would be to put breakpoint on

ClaimsPrincipal.Current

and inspect it, it should return list of claims.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM