繁体   English   中英

如何使用OWIN&身份认证注册用户?

[英]How do to authenticate a registered user using OWIN & Identity?

我有两个项目,MVC Web应用程序和Web服务。 在MVC网络应用中,我有一个名为“帐户”的控制器。 在“帐户”中,有一个名为“登录”的操作。 “登录”操作从请求中获取身份验证管理器。 “登录”操作将调用Web服务以识别用户是否存在。 如果该用户存在,则Web服务将为该特定用户返回'ClaimsIdentity'。 然后,“登录”操作将使用身份验证管理器和声明身份来登录用户。

此后,不对用户进行签名/验证。 我知道这是因为User.Identity.Name为空白,而User.Identity.IsAuthenticated为false。 需要说明这种情况的发生原因以及我可以采取的解决措施。 没有构建时或运行时错误。 我需要Web服务来执行对数据库的所有调用。

帐户登录代码

    [HttpPost]
    [AllowAnonymous]
    [ValidateAntiForgeryToken]
    public ActionResult LogIn(LoginModel model)
    {
        if (!ModelState.IsValid)
        {
            return View(model);
        }

        var authManager = GetAuthenticationManager();

        var loginFeedback = _webService.Login(model);

        if (loginFeedback.Success)
        {
            authManager.SignIn(loginFeedback.Identity);
            return RedirectToAction("Index", "Home");
        }
        else
        {
            ModelState.AddModelError("", loginFeedback.FeedbackMessage);
            return View(model);
        }
    }

GetAuthenticationManager

    private IAuthenticationManager GetAuthenticationManager()
    {
        var context = Request.GetOwinContext();
        return context.Authentication;
    }

Web服务登录

    public LoginFeedbackDto Login(LoginModel loginModel)
    {
        var userManager = GetUserManager();

        var user = userManager.Find(loginModel.Email, loginModel.Password);

        var dto = new LoginFeedbackDto();
        string status = user.Status.ToLower();

        if (status == "invalid")
        {
            dto.Success = false;
            dto.FeedbackMessage = @"This account has not been activated.";
        }
        else if (status == "rejected")
        {
            dto.Success = false;
            dto.FeedbackMessage = @"This account has been rejected.";
        }
        else if (status != "invalid" && status != "rejected" && status != "processed")
        {
            dto.Success = false;
            dto.FeedbackMessage = @"We are unable to log you in due to a technical issue.";
        }
        else
        {
            dto.Success = true;
            dto.Identity = userManager.CreateIdentity(user, DefaultAuthenticationTypes.ApplicationCookie);
        }

        userManager.Dispose();

        return dto;
    }

这里发生的是您正在创建的身份在RedirectToAction上“丢失”。
您可以使用CookieMiddleware,它可以创建代表当前用户的cookie。
您将需要一个Owin启动类,该类将需要类似于以下代码。
确保“ SelfIssue”与您的Web服务将ClaimsIdentity.AuthenticationType设置为相同的AuthenticationType。

public const string SelfIssue = "Self-Issue";

public void Configuration(IAppBuilder app)
{
    app.SetDefaultSignInAsAuthenticationType(SelfIssue);
    app.UseCookieAuthentication(new CookieAuthenticationOptions { AuthenticationType = SelfIssue });
}

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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