jamheadart
jamheadart

Reputation: 5343

c# - how can I access an `Microsoft.AspNetCore.Authorization` authorised user's details

I've set up authorisation on my site, which uses context_A - now all I need to do is add the [Authorize] attribute to the top of any controller to make sure the user is signed in to use it.

I've done this on one particular controller which uses another context, context_B - the authorisation still works, but now I'm left wondering how I can access the authorised user's details on the controller that uses a different context.

using Microsoft.AspNetCore.Authorization;

namespace projectA.Controllers
{
    [Authorize] // this is authorised using contextA
    public class SomeController : Controller
    {
        private readonly ContextB _context;

        public SomeController(ContextB context) // I pass in completely different context here
        {
            _context = context;
        }
    }
}

I want to access the auth context in my controller, something like

`string x = AuthorisationContext.CurrentUser.Email`

but I don't know what's going on behind the scenes when using [Authorize] - I'm not sure where/when it's pushing and pulling data using contextA

I'm guessing I probably should have the authorisation done within the same context for loads of reasons, but is it possible to pluck the current authorised user's details into the controller even though I've simply added the [Authorize] attribute?

Upvotes: 0

Views: 217

Answers (1)

Xueli Chen
Xueli Chen

Reputation: 12725

From the Controller base class, you can get the IClaimsPrincipal from the User property. Other fields can be fetched from the database's User entity:

1.Get the user manager using dependency injection

private UserManager<IdentityUser> _userManager;

private readonly ContextB _context;

public SomeController(ContextB context, UserManager<IdentityUser> userManager)
{
        _context = context;
        _userManager = userManager;
}

2.And use it:

public async void GetUserInfo()
{
        var user = await _userManager.GetUserAsync(User);
        var email = user.Email;
}

Upvotes: 2

Related Questions