本文介绍了没有ASP.NET身份的OWIN cookie身份验证的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我是ASP.NET MVC 5的新手,但对于身份验证+授权框架感到非常不舒服。我知道这是ASP.NET MVC框架的新功能,因此我想采用另一种方法在我的应用程序中实现身份验证。

I'm new to ASP.NET MVC 5 and I'm finding very uncomfortable with Identity authentication + authorization framework. I know this is a new feature of the ASP.NET MVC framework, so I'd like to apply an alternative way to implement authentication in m y application.

是否可以?我读到可以使用 FormsAuthenticationModule 。这是一个好选择吗?如何在基于MVC 5的应用程序中使用它?

Is it possible? I read I could use the FormsAuthenticationModule. Is this a good alternative? How can I use it in a MVC 5 based application?

推荐答案

在查看Identity时,我有相同的感觉。它添加了许多不必要的抽象,并且不适合我的情况,即我拥有实现自定义身份验证工作流程的旧系统。

I felt the same way when taking a look at Identity. It adds lots of unnecessary abstractions and does not suit with my case that I have legacy system which implemented customised authentication work-flow.

有关使用OWIN身份验证的大量示例默认情况下,Identity和EF使开发人员感到困惑,即OWIN必须与Identity and Entity Framework一起使用。

Tons of examples out there about OWIN authentication using Identity and EF by default which makes developers confused that OWIN has to go with Identity and Entity Framework.

但是从技术上讲,您可以剥离Identity以仅使用OWIN cookie身份验证( Microsoft.Owin.Security.Cookies )。代码非常简单,下面是我从代码中删除的示例,该示例消除了琐碎的事情:

But technically, you are able to strip out Identity to use only OWIN cookie authentication (Microsoft.Owin.Security.Cookies). The code turns out very simple, below is example I got from my code which eliminates trivial things:

[HttpPost]
public ActionResult Login(LoginViewModel model, string returnUrl)
{
    var user = _userService.GetByEmail(model.Email);

    //check username and password from database, naive checking:
    //password should be in SHA
    if (user != null && (user.Password == model.Password))
    {
        var claims = new[] {
                new Claim(ClaimTypes.Name, user.Name),
                new Claim(ClaimTypes.Email, user.Email),
                // can add more claims
            };

        var identity = new ClaimsIdentity(claims, "ApplicationCookie");

        // Add roles into claims
        var roles = _roleService.GetByUserId(user.Id);
        if (roles.Any())
        {
            var roleClaims = roles.Select(r => new Claim(ClaimTypes.Role, r.Name));
            identity.AddClaims(roleClaims);
        }

        var context = Request.GetOwinContext();
        var authManager = context.Authentication;

        authManager.SignIn(new AuthenticationProperties
               { IsPersistent = model.RememberMe }, identity);

        return RedirectToAction("Index", "Home");
    }
    // login failed.
}

public ActionResult LogOut()
{
    var ctx = Request.GetOwinContext();
    var authManager = ctx.Authentication;

    authManager.SignOut("ApplicationCookie");
    return RedirectToAction("Login");
}

这篇关于没有ASP.NET身份的OWIN cookie身份验证的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

07-30 05:32