C# Web API 2 & Angular - Microsoft Account Authentication

早过忘川 提交于 2019-12-13 03:44:20

问题


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!


回答1:


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.




回答2:


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;
    ...
}



回答3:


i do with this example

https://github.com/Azure-Samples/active-directory-b2c-javascript-angular2.4-spa

and it work well



来源:https://stackoverflow.com/questions/48942837/c-sharp-web-api-2-angular-microsoft-account-authentication

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!