Authenticate a USER in Asp.net MVC 5 without password

↘锁芯ラ 提交于 2020-01-06 14:53:29

问题


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.



来源:https://stackoverflow.com/questions/30126344/authenticate-a-user-in-asp-net-mvc-5-without-password

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!