LanceM
LanceM

Reputation: 1988

How do you determine if the current user is logged into Azure AD in .NET Core 3.1

I have a .NET Core 3.1 program that hosts an Angular 9 app that will be used by users in a company that uses Azure AD. I need to determine if the user is already logged into their Azure AD and if so get some information about them. I would like to determine this before the Angular App is loaded for the user. This is pretty straight-forward in standard Windows AD and .NET but I can't find how to do this with .NET Core and Azure AD.

I've added some pseudo code below to help give an idea of what I'm trying to achieve:

[ApiController]
[Authorize]
[Route("api/[controller]/[action]")]
public class AuthenticationController : ControllerBase
{
    public AuthenticationController()
    {

    }


    [AllowAnonymous]
    [HttpPost]
    public LoginResult Login([FromBody] LoginRequestDC loginRequest)
    {
        LoginResult lr = new LoginResult();

        if (loginRequest != null)
        {
            try
            {
                if(NotLoggedInAzureAD)
        {
                    lr = LoginWithUserNameAndPasswordAndGetInfoFromDataBase(loginRequest);
        }
        else
        {
        lr.IsLoggedIn = true;
        lr.UserInfo = GetInfoFromAzureAD;
        }
            }
            catch (Exception ex)
            {
                Common.AppLogger.Error(ex, $"Unable to login.");
            }
        }

        return lr;
    }

private bool NotLoggedInAzureAD()
{
    //Not sure how you would get the Azure AD user in .net core 
    return CodeToAskAzureADIfUserLoggedIn(MyHttpContext.Current.User.Identity.Name);
}

private UserInfo GetInfoFromAzureAD()
{
    return CodeToAskAzureADForUserInfo(MyHttpContext.Current.User.Identity.Name);
}
 }

Please help.

Upvotes: 1

Views: 3510

Answers (1)

astaykov
astaykov

Reputation: 30903

Check out the Code Samples page. There are a lot of samples, for example .NET Core Web App. Like this one, which is a .NET Core 3.1.

But I suggest that you first start with Authentication basics, go over Security Tokens, the Application Model and finally understand the App Sign-In Flow in Microsoft Identity Platform.

Upvotes: 2

Related Questions