简体   繁体   中英

How To Set Current User Identity Information

I'm trying to implement login with discord. I have the user's discord information, now I need to make it so that they are authorized to view certain pages.

I've tried:

System.Web.HttpContext.Current.User.Identity.Name = User.id;
System.Web.HttpContext.Current.User.Identity.IsAuthenticated = true;

However, this won't work because they are read only values.

Here is what the User class currently looks like:

public class User
    {
        public string id;
        public string username;
        public string discriminator;
        public string avatar;
        public bool verified;
        public string email;
        public int flags;
        public int premium_type;
    }

And I am checking to see if the ID exists in the database. Then I am trying to have this be the current logged in user for asp.net Identity.

How can I set this user as the current logged in Identity?

You need to instantiate the UserManager and SignInManager.

In your controller add these dependencies.

private readonly UserManager _userManager;
private readonly SignInManager _signInManager;

public AccountController(
    UserManager userManager,
    SignInManager signInManager)
{
    _signInManager = signInManager;
    _userManager = userManager;
}

Then use those two managers to get the information you want

var appUser = _userManager.FindByIdAsync(user.Id);

To get your application user

_signInManager.SignInAsync(appUser);

Then that user will be signed in, assuming they already exist in your system. If they do not you will need to create a new user through the _userManager.

Here is some reference links:

https://docs.microsoft.com/en-us/aspnet/core/security/authentication/identity?view=aspnetcore-2.2&tabs=visual-studio

https://docs.microsoft.com/en-us/previous-versions/aspnet/dn613290(v%3Dvs.108)

https://docs.microsoft.com/en-us/dotnet/api/microsoft.aspnetcore.identity.signinmanager-1?view=aspnetcore-2.2

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM