如何在没有用户的情况下 Asp.Net MVC 中登录客户端



我有一个系统,我使用它 Asp.Net Identity来记录具有声明的用户。每个用户对系统功能都有不同的访问权限,因为我创建了不同的授权过滤器。

我的问题是:该系统用于管理车身工作和喷漆。它有公司,用户使用 Asp.Net 身份技术登录。但是我需要记录没有用户名或密码的特殊用户,这些用户是公司的客户,必须使用客户车辆的车牌和一些个人信息(如社会安全号码)登录。

到目前为止,我一直在设法做的事情:查找客户是否在一家公司拥有车辆,并验证所提供的客户数据是否正确。但是系统在 SignInManager.SignInAsync() methrod 中失败。它给了我找不到用户ID的错误。

这是我的代码:

if (!ModelState.IsValid)
{
    return View(model);
}
var serviceOrder = Repository.ServiceOrders
    .Where(so => so.IsActive && so.Vehicle.LicensePlate == model.LicensePlate &&
        so.Client.Document.Substring(0, 3) == model.Password)
    .OrderByDescending(so => so.CreatedAt).FirstOrDefault();
if (serviceOrder != null)
{
    var userId = Guid.NewGuid().ToString();
    var user = new ServerModels.User
    {
        Id = userId,
        Name = serviceOrder.Client.Name,
        UserName = model.LicensePlate,
        SecurityStamp = userId,
        Claims =
        {
            new IdentityUserClaim
            {
                UserId = userId,
                ClaimType = ClaimTypes.Role,
                ClaimValue = AppRoleClaims.Client
            },
            new IdentityUserClaim
            {
                UserId = userId,
                ClaimType = AppAccessClaims.ClientScreenAccess,
                ClaimValue = AppAccessClaimsValues.Visualize,   
            }
        }
    };
    try
    {
        await SignInManager.SignInAsync(user, model.RememberMe, false);
        return Redirect("/cliente/consultarveiculo");
    }
    catch (Exception ex)
    {
        ModelState.AddModelError("", "Tentativa de login inválida. - " + ex.Message);
        return View(model);
    }

和错误 堆栈跟踪:

em Microsoft.AspNet.Identity.UserManager`2.<GetSecurityStampAsync>d__42.MoveNext()
--- Fim do rastreamento de pilha do local anterior onde a exceção foi gerada ---
   em System.Runtime.CompilerServices.TaskAwaiter.ThrowForNonSuccess(Task task)
   em System.Runtime.CompilerServices.TaskAwaiter.HandleNonSuccessAndDebuggerNotification(Task task)
   em System.Runtime.CompilerServices.TaskAwaiter`1.GetResult()
   em Microsoft.AspNet.Identity.TaskExtensions.CultureAwaiter`1.GetResult()
   em Microsoft.AspNet.Identity.ClaimsIdentityFactory`2.<CreateAsync>d__0.MoveNext()
--- Fim do rastreamento de pilha do local anterior onde a exceção foi gerada ---
   em System.Runtime.CompilerServices.TaskAwaiter.ThrowForNonSuccess(Task task)
   em System.Runtime.CompilerServices.TaskAwaiter.HandleNonSuccessAndDebuggerNotification(Task task)
   em System.Runtime.CompilerServices.TaskAwaiter`1.GetResult()
   em SGOM.Server.Models.User.<GenerateUserIdentityAsync>d__20.MoveNext() na C:UsersAdaltoDocumentsVisual Studio 2015ProjectsMonitoraCarSGOMServerModelsModelsUser.cs:linha 25
--- Fim do rastreamento de pilha do local anterior onde a exceção foi gerada ---
   em System.Runtime.CompilerServices.TaskAwaiter.ThrowForNonSuccess(Task task)
   em System.Runtime.CompilerServices.TaskAwaiter.HandleNonSuccessAndDebuggerNotification(Task task)
   em System.Runtime.CompilerServices.TaskAwaiter`1.GetResult()
   em Microsoft.AspNet.Identity.TaskExtensions.CultureAwaiter`1.GetResult()
   em Microsoft.AspNet.Identity.Owin.SignInManager`2.<SignInAsync>d__2.MoveNext()
--- Fim do rastreamento de pilha do local anterior onde a exceção foi gerada ---
   em System.Runtime.CompilerServices.TaskAwaiter.ThrowForNonSuccess(Task task)
   em System.Runtime.CompilerServices.TaskAwaiter.HandleNonSuccessAndDebuggerNotification(Task task)
   em System.Runtime.CompilerServices.TaskAwaiter.GetResult()
   em SGOM.Client.Web.WebApp.Controllers.AccountController.<ClientLogin>d__13.MoveNext() na C:UsersAdaltoDocumentsVisual Studio 2015ProjectsMonitoraCarSGOMClientWebWebAppControllersAccountController.cs:linha 195

客户端登录屏幕

按照Sam Farajpour Guamari通过的链接,我想出了这个解决方案:

public ActionResult ClientLogin(ClientLoginViewModel model)
{
        if (!ModelState.IsValid)
        {
            return View(model);
        }
        var serviceOrder = Repository.ServiceOrders
            .Where(so => so.IsActive && so.Vehicle.LicensePlate == model.LicensePlate &&
            so.Client.Document.Replace(".", "").Replace("-", "").Replace("/", "").Substring(0, 6) == model.Password)
            .OrderByDescending(so => so.CreatedAt).FirstOrDefault();
        if (serviceOrder != null)
        {
            try
            {
                var identity = new ClaimsIdentity(
                    new[]
                    {
                        // adding following 2 claims just for supporting default antiforgery provider
                        new Claim(ClaimTypes.NameIdentifier, "AnonymousUserID"),
                        new Claim("http://schemas.microsoft.com/accesscontrolservice/2010/07/claims/identityprovider", "ASP.NET Identity", "http://www.w3.org/2001/XMLSchema#string"),
                        new Claim(ClaimTypes.Name, serviceOrder.Client.Name),
                        new Claim(ClaimTypes.Role, AppRoleClaims.Client),
                        new Claim(AppAccessClaims.ClientScreenAccess, AppAccessClaimsValues.Visualize) 
                    },
                    DefaultAuthenticationTypes.ApplicationCookie);
                HttpContext.GetOwinContext().Authentication.SignIn(
                   new AuthenticationProperties { IsPersistent = model.RememberMe }, identity);
                return Redirect("/cliente/consultarveiculo");
            }
            catch (Exception ex)
            {
                ModelState.AddModelError("", "Tentativa de login inválida. - " + ex.Message);
                return View(model);
            }
        }
        ModelState.AddModelError("", "Tentativa de login inválida. - Nenhum cliente com a placa e a senha informada.");
        return View(model);
  }

这非常有效:动态创建声明并使用它们进行身份验证。

链接到原始帖子:

MVC 5 标识 (v2) 身份验证,无需创建应用程序用户

相关内容

  • 没有找到相关文章

最新更新