0

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!

3 Answers 3

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.

Sign up to request clarification or add additional context in comments.

3 Comments

Thank you! I was able to get the logged user's info.
Btw, I just like to point out that in my case I had to use Where(x => x.Type == "preferred_username") to get the email of the logged in user.
Yeah, it depends what type of claims you get back, best is to put breakpoint and inspect what you get back.
1

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://learn.microsoft.com/en-us/azure/active-directory-b2c/active-directory-b2c-devquickstarts-api-dotnet

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

Comments

0

i do with this example

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

and it work well

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.