Authenticate a USER in Asp.net MVC 5 without passw

2019-08-17 05:33发布

问题:

I want to authenticate a user with only user name and no password. My application does not have any user management data and I just want to create Identity with user details so that I can use it in the application.

I tried to copy the SingInAsync method to put this up

    private async Task InitializeUser()
    {
        var user = new ApplicationUser();
        user.Id = "abcd";
        user.UserName = "abcd";

        AuthenticationManager.SignOut(DefaultAuthenticationTypes.ExternalCookie);
        var identity = await UserManager.CreateIdentityAsync(user, DefaultAuthenticationTypes.ApplicationCookie);
        AuthenticationManager.SignIn(new AuthenticationProperties() { IsPersistent = false }, identity);
    }

But it tells me and error - that user ID cannot be found. Is there someway I can just authenticate the user by username and assign the Identity with some details??

回答1:

With no users just forget about the UserManager and create the ClaimsIdentity yourself.

private async Task InitializeUser()
{
    var user = new ApplicationUser();
    user.Id = "abcd";
    user.UserName = "abcd";

    AuthenticationManager.SignOut(DefaultAuthenticationTypes.ApplicationCookie);

    var id = new ClaimsIdentity(DefaultAuthenticationTypes.ApplicationCookie, ClaimsIdentity.DefaultNameClaimType, ClaimsIdentity.DefaultRoleClaimType);
    id.AddClaim(new Claim("http://schemas.microsoft.com/accesscontrolservice/2010/07/claims/identityprovider", "ASP.NET Identity", ClaimValueTypes.String));
    id.AddClaim(new Claim(ClaimsIdentity.DefaultNameClaimType, user.UserName, ClaimValueTypes.String));
    id.AddClaim(new Claim(ClaimTypes.NameIdentifier, user.Id, ClaimValueTypes.String));

    AuthenticationManager.SignIn(new AuthenticationProperties() { IsPersistent = false }, id);
}

You probably want to tweak this a bit to make it cleaner.