Jed
Jed

Reputation: 1074

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!

Upvotes: 0

Views: 1017

Answers (3)

Sandy Veliz
Sandy Veliz

Reputation: 732

i do with this example

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

and it work well

Upvotes: 0

Bola
Bola

Reputation: 758

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.

Upvotes: 1

Kevin Le
Kevin Le

Reputation: 856

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

Upvotes: 1

Related Questions