SignInManager.使用非现有用户登录

本文关键字:用户 登录 SignInManager | 更新日期: 2023-09-27 18:05:19

我刚刚创建了一个ASP。MVC项目,并希望提供临时登录(让我们称之为客户登录)。这应该不需要注册,并且我希望避免为该用户创建数据库条目。

我扩展了AccountController的默认Login-action:

public async Task<ActionResult> Login(LoginViewModel model, string returnUrl)
{
    if (!ModelState.IsValid)
        return View(model);
    if (model.GuestLogin) {
        var user = UserManager.FindByEmail(model.Email);
        if (user != null) {
            ModelState.AddModelError("", "Invalid login attempt.");
            return View(model);
        }
        var appUser = new ApplicationUser() { Email = model.Email, UserName = model.Email, Id = Guid.NewGuid().ToString() };
        //var creationResult = UserManager.Create(appUser);
        SignInManager.SignIn(appUser, false, model.RememberMe);
        return RedirectToLocal(returnUrl);
    }
    //common login stuff ...
}

System.

sign -call失败

是否有可能以某种方式存档?

Thanks in advance

SignInManager.使用非现有用户登录

好的,

问题在于ClaimsIdentityFactory,它试图在签到过程中添加一些与用户实体相关的声明(例如用户角色或安全戳声明)。

通过防止这种情况,使用不存在的用户登录似乎不再是问题了。

这是我的索赔工厂类:

public class MyClaimsFactory : ClaimsIdentityFactory<MyUser, string>
{
    public override async Task<ClaimsIdentity> CreateAsync(UserManager<MyUser, string> manager, MyUser user, string authenticationType)
    {
        if (manager == null)
            throw new ArgumentNullException("manager");
        if (user == null)
            throw new ArgumentNullException("user");
        ClaimsIdentity claimsIdentity = new ClaimsIdentity(authenticationType, this.UserNameClaimType, this.RoleClaimType);
        claimsIdentity.AddClaim(new Claim(this.UserIdClaimType, this.ConvertIdToString(user.Id), "http://www.w3.org/2001/XMLSchema#string"));
        claimsIdentity.AddClaim(new Claim(this.UserNameClaimType, user.UserName, "http://www.w3.org/2001/XMLSchema#string"));
        claimsIdentity.AddClaim(new Claim("http://schemas.microsoft.com/accesscontrolservice/2010/07/claims/identityprovider", "ASP.NET Identity", "http://www.w3.org/2001/XMLSchema#string"));
        if (!user.IsGuest)
        {
            if (manager.SupportsUserSecurityStamp)
                claimsIdentity.AddClaim(new Claim(this.SecurityStampClaimType, await manager.GetSecurityStampAsync(user.Id).WithCurrentCulture<string>()));
            if (manager.SupportsUserRole)
            {
                IList<string> list = await manager.GetRolesAsync(user.Id).WithCurrentCulture<IList<string>>();
                foreach (string current in list)
                {
                    claimsIdentity.AddClaim(new Claim(this.RoleClaimType, current, "http://www.w3.org/2001/XMLSchema#string"));
                }
            }
            if (manager.SupportsUserClaim)
                claimsIdentity.AddClaims(await manager.GetClaimsAsync(user.Id).WithCurrentCulture<IList<Claim>>());
        }
        return claimsIdentity;
    }
}