我似乎无法获得一个非常基本的 cookie 登录示例来使用 MVC5 和 OWIN [英] I can't seem to get a very basic cookie login example to work with MVC5 and OWIN

查看:22
本文介绍了我似乎无法获得一个非常基本的 cookie 登录示例来使用 MVC5 和 OWIN的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

2013 年,我一直在尝试使用 ASP.net MVC 5,但到目前为止,我连最基本的身份验证都无法正常工作.

过去几天我一直在阅读,我终于偶然发现(http://brockallen.com/2013/10/24/a-primer-on-owin-cookie-authentication-middleware-for-the-asp-net-developer/) 似乎给出了我能找到的最基本的简单示例.所以我试过了,但它似乎仍然无法为用户创建会话.

这是我的 cookie 配置

public void ConfigureAuth(IAppBuilder app){app.UseCookieAuthentication(new CookieAuthenticationOptions){AuthenticationType = DefaultAuthenticationTypes.ApplicationCookie,LoginPath = new PathString("/FooBar")});}

这是我的基本自定义登录.

公共类 LoginController : ApiController{私有 IAuthenticationManager 身份验证{获取 { 返回 Request.GetOwinContext().Authentication;}}//POST api/登录public void Post([FromBody]LoginInfo email){var fooBar = Authentication.User;var claim = new List{新索赔(ClaimTypes.Name,名称"),new Claim(ClaimTypes.Email, "email@email.com"),new Claim(ClaimTypes.Role, "Foo")};var identity = new ClaimsIdentity(claims, DefaultAuthenticationTypes.ApplicationCookie);Authentication.SignIn(new AuthenticationProperties() { IsPersistent = true }, 身份);}}

如果我点击登录 api 两次,我会期望第二次将 fooBar 变量设置为标记为已验证的用户,但是当我检查它时,它只是说它没有经过验证,它没有'没有任何我所期望的声明.

我还尝试创建一个基本服务来检查它是否已通过身份验证,以防我误解了它的工作原理,但这也失败了.如果我尝试访问它,它会说我没有通过身份验证,它不会像我想象的那样重定向我.

公共类 TestController : ApiController{[授权(角色 =Foo")]公共 int Get(){返回 1;}}

我确定我一定只是遗漏了一些基本的东西,但到目前为止,无论我摆弄什么,也不管我在网上看到的各种指南和建议,即使是这个简单的场景也没有任何东西能够发挥作用.关于我做错了什么的任何想法?

解决方案

在以下帖子中 http://www.khalidabuhakmeh.com/asp-net-mvc-5-authentication-breakdown 有一个有用的 OWIN 示例.

我做错了,正确的链接是:http://www.khalidabuhakmeh.com/asp-net-mvc-5-authentication-breakdown-part-deux 所以,这里我们使用 vb 方法进行基本的 cookie 登录:

a) Cookie 配置.

导入 Microsoft.AspNet.Identity导入 Microsoft.Owin导入 Microsoft.Owin.Security.Cookies进口欧文部分公开课启动Public Sub ConfigureAuth(app As IAppBuilder)app.UseCookieAuthentication(New CookieAuthenticationOptions() with {.AuthenticationType = DefaultAuthenticationTypes.ApplicationCookie,.LoginPath = New PathString("/Account/Login")})结束子结束班

b) 家庭控制器(家庭索引可供 auth 用户使用)

<授权>公共类 HomeController继承 System.Web.Mvc.Controller<HttpGet>函数 Index() 作为 ActionResult返回视图()结束函数结束班

c) 帐户控制器(登录)

导入 System.Security.Claims导入 System.Threading.Tasks导入 Microsoft.AspNet.Identity导入 Microsoft.AspNet.Identity.Owin导入 Microsoft.Owin.Security<授权>公共类 AccountController继承控制器私有函数 AuthenticationManager() 作为 IAuthenticationManager返回 HttpContext.GetOwinContext().Authentication结束函数<允许匿名>公共函数登录(returnUrl As String)作为 ActionResultViewBag.ReturnUrl = returnUrl返回视图()结束函数<HttpPost><允许匿名><ValidateAntiForgeryToken>公共函数登录(model As LoginViewModel, returnUrl As String) As ActionResult如果 ModelState.IsValid 那么If model.UsuarioValido Then 'Local authentication, this must be on Repository classDim Identidad = New ClaimsIdentity({New Claim(ClaimTypes.Name, model.UserName)},DefaultAuthenticationTypes.ApplicationCookie,ClaimTypes.Name,声明类型.角色)Identidad.AddClaim(New Claim(ClaimTypes.Role, "Invitado"))AuthenticationManager.SignIn(New AuthenticationProperties() With {.IsPersistent = model.RememberMe}, Identidad)Return RedirectToAction("index", "home")万一万一返回 RedirectToAction("登录",模型)结束函数<HttpGet>公共函数 LogOff() 作为 ActionResultAuthenticationManager.SignOut()返回 RedirectToAction("登录")结束函数结束班

d) 帐户模型

导入 System.ComponentModel.DataAnnotations公共类登录ViewModel<必需的><Display(Name:="Nombre de usuario")>公共属性用户名作为字符串<必需的><DataType(DataType.Password)><Display(Name:="Contraseña")>公共属性密码字符串<Display(Name:="¿Recordarcuenta?")>公共属性记住我为布尔值公共只读属性 UsuarioValido 作为布尔值得到Return Password = "secreto" '密码在这里!结束获取最终财产结束班

e) 索引视图

@Imports Microsoft.AspNet.Identity@代码ViewData("Title") = "Página Inicial"结束代码<h2>Bienvenido @User.Identity.GetUserName()</h2><a href="@Url.Action("LogOff", "Account")">点击 para salir!(塞拉尔塞西翁)</a>

f) 登录视图

@ModelType LoginViewModel@代码ViewBag.Title = "Iniciar sesión"结束代码<h2>@ViewBag.Title.</h2><div class="row"><div class="col-md-8"><section id="登录表单">@Using Html.BeginForm("Login", "Account", New With { .ReturnUrl = ViewBag.ReturnUrl }, FormMethod.Post, New With {.class = "form-horizo​​ntal", .role = "form"})@Html.AntiForgeryToken()@<文本><h4>使用 unacuenta local para iniciar sesión.</h4><小时/>@Html.ValidationSummary(真)<div class="form-group">@Html.LabelFor(Function(m) m.UserName, New With {.class = "col-md-2 control-label"})<div class="col-md-10">@Html.TextBoxFor(Function(m) m.UserName, New With {.class = "form-control"})@Html.ValidationMessageFor(Function(m) m.UserName)

<div class="form-group">@Html.LabelFor(Function(m) m.Password, New With {.class = "col-md-2 control-label"})<div class="col-md-10">@Html.PasswordFor(Function(m) m.Password, New With {.class = "form-control"})@Html.ValidationMessageFor(Function(m) m.Password)

<div class="form-group"><div class="col-md-offset-2 col-md-10"><div class="checkbox">@Html.CheckBoxFor(Function(m) m.RememberMe)@Html.LabelFor(Function(m) m.RememberMe)

<div class="form-group"><div class="col-md-offset-2 col-md-10"><input type="submit" value="Iniciar sesión" class="btn btn-default"/>

结束使用</节>

@Section 脚本@Scripts.Render("~/bundles/jqueryval")结束部分

I've been trying to get my feet wet with ASP.net MVC 5 for 2013, but so far I've failed to get even the most basic authentication working correctly.

I've been reading around for the last few days and I finally stumbled upon (http://brockallen.com/2013/10/24/a-primer-on-owin-cookie-authentication-middleware-for-the-asp-net-developer/) which seemed to give the most basic simple example I could find. So I tried that, but it still fails to seem to actually create a session for the user.

Here is my cookie config

public void ConfigureAuth(IAppBuilder app)
    {
        app.UseCookieAuthentication(new CookieAuthenticationOptions
        {
            AuthenticationType = DefaultAuthenticationTypes.ApplicationCookie,
            LoginPath = new PathString("/FooBar")
        });
    }

Here is my basic custom login.

public class LoginController : ApiController
    {
        private IAuthenticationManager Authentication
        {
            get { return Request.GetOwinContext().Authentication; }
        }

        // POST api/login
        public void Post([FromBody]LoginInfo email)
        {
            var fooBar = Authentication.User;
            var claims = new List<Claim>
            {
                new Claim(ClaimTypes.Name, "name")
                ,new Claim(ClaimTypes.Email, "email@email.com")
                ,new Claim(ClaimTypes.Role, "Foo")
            };
            var identity = new ClaimsIdentity(claims, DefaultAuthenticationTypes.ApplicationCookie);

            Authentication.SignIn(new AuthenticationProperties() { IsPersistent = true }, identity);
        }
    }

If I hit the the login api twice I would have expected the second time that the fooBar variable to be set to a user who is marked as authenticated, but when I check it, it just says it's not authenticated, and it doesn't have any of the claims I would have expected.

I also tried creating a basic service to just check to see if it was authenticated in case I misunderstood how it worked, but this also fails. If I try to go to it, it says I'm not authenticated, it doesn't redirect me as I thought it would.

public class TestController : ApiController
    {
        [Authorize(Roles = "Foo")]
        public int Get()
        {
            return 1;
        }
    }

I'm sure I must just be missing some basic, but so far no matter what I fiddled with and regardless of the various guides and advice I've seen online, nothing has been able to get even this simple scenario working. Any ideas on what I'm doing wrong?

解决方案

In the following post http://www.khalidabuhakmeh.com/asp-net-mvc-5-authentication-breakdown there is an helpful OWIN examples.

I did a mistake, the correct link is: http://www.khalidabuhakmeh.com/asp-net-mvc-5-authentication-breakdown-part-deux So, here we go with vb approach for basic cookie login:

a) Cookie Config.

Imports Microsoft.AspNet.Identity
Imports Microsoft.Owin
Imports Microsoft.Owin.Security.Cookies
Imports Owin

Partial Public Class Startup

    Public Sub ConfigureAuth(app As IAppBuilder)
        app.UseCookieAuthentication(New CookieAuthenticationOptions() With {
        .AuthenticationType = DefaultAuthenticationTypes.ApplicationCookie,
        .LoginPath = New PathString("/Account/Login")})
    End Sub
End Class

b) Home controller (Home index available for auth users)

<Authorize>
Public Class HomeController
    Inherits System.Web.Mvc.Controller

    <HttpGet>
    Function Index() As ActionResult
        Return View()
    End Function

End Class

c) Account controller (Login)

Imports System.Security.Claims
Imports System.Threading.Tasks
Imports Microsoft.AspNet.Identity
Imports Microsoft.AspNet.Identity.Owin
Imports Microsoft.Owin.Security

<Authorize>
Public Class AccountController
    Inherits Controller

    Private Function AuthenticationManager() As IAuthenticationManager
        Return HttpContext.GetOwinContext().Authentication
    End Function

    <AllowAnonymous>
    Public Function Login(returnUrl As String) As ActionResult
        ViewBag.ReturnUrl = returnUrl
        Return View()
    End Function

    <HttpPost>
    <AllowAnonymous>
    <ValidateAntiForgeryToken>
    Public Function Login(model As LoginViewModel, returnUrl As String) As ActionResult
        If ModelState.IsValid Then

            If model.UsuarioValido Then 'Local authentication, this must be on Repository class
                Dim Identidad = New ClaimsIdentity({New Claim(ClaimTypes.Name, model.UserName)},
                                                   DefaultAuthenticationTypes.ApplicationCookie,
                                                   ClaimTypes.Name,
                                                   ClaimTypes.Role)

                Identidad.AddClaim(New Claim(ClaimTypes.Role, "Invitado"))

                AuthenticationManager.SignIn(New AuthenticationProperties() With {.IsPersistent = model.RememberMe}, Identidad)

                Return RedirectToAction("index", "home")

            End If
        End If

        Return RedirectToAction("login", model)

    End Function

    <HttpGet>
    Public Function LogOff() As ActionResult
        AuthenticationManager.SignOut()
        Return RedirectToAction("login")
    End Function

End Class

d) Account Model

Imports System.ComponentModel.DataAnnotations

Public Class LoginViewModel
    <Required>
    <Display(Name:="Nombre de usuario")>
    Public Property UserName As String

    <Required>
    <DataType(DataType.Password)>
    <Display(Name:="Contraseña")>
    Public Property Password As String

    <Display(Name:="¿Recordar cuenta?")>
    Public Property RememberMe As Boolean

    Public ReadOnly Property UsuarioValido As Boolean
        Get
            Return Password = "secreto" 'Password Here!
        End Get
    End Property

End Class

e) Index view

@Imports Microsoft.AspNet.Identity

@Code
    ViewData("Title") = "Página Inicial"
End Code

<h2>Bienvenido @User.Identity.GetUserName()</h2>

<a href="@Url.Action("LogOff", "Account")">
    Click para salir! (Cerrar Sesión)
</a>

f) Login View

@ModelType LoginViewModel

@Code
    ViewBag.Title = "Iniciar sesión"
End Code

<h2>@ViewBag.Title.</h2>
<div class="row">
    <div class="col-md-8">
        <section id="loginForm">
            @Using Html.BeginForm("Login", "Account", New With { .ReturnUrl = ViewBag.ReturnUrl }, FormMethod.Post, New With {.class = "form-horizontal", .role = "form"})
                @Html.AntiForgeryToken()
                @<text>
                <h4>Utilice una cuenta local para iniciar sesión.</h4>
                <hr />
                @Html.ValidationSummary(True)
                <div class="form-group">
                    @Html.LabelFor(Function(m) m.UserName, New With {.class = "col-md-2 control-label"})
                    <div class="col-md-10">
                        @Html.TextBoxFor(Function(m) m.UserName, New With {.class = "form-control"})
                        @Html.ValidationMessageFor(Function(m) m.UserName)
                    </div>
                </div>
                <div class="form-group">
                    @Html.LabelFor(Function(m) m.Password, New With {.class = "col-md-2 control-label"})
                    <div class="col-md-10">
                        @Html.PasswordFor(Function(m) m.Password, New With {.class = "form-control"})
                        @Html.ValidationMessageFor(Function(m) m.Password)
                    </div>
                </div>
                <div class="form-group">
                    <div class="col-md-offset-2 col-md-10">
                        <div class="checkbox">
                            @Html.CheckBoxFor(Function(m) m.RememberMe)
                            @Html.LabelFor(Function(m) m.RememberMe)
                        </div>
                    </div>
                </div>
                <div class="form-group">
                    <div class="col-md-offset-2 col-md-10">
                        <input type="submit" value="Iniciar sesión" class="btn btn-default" />
                    </div>
                </div>
                </text>
            End Using
        </section>
    </div>

</div>
@Section Scripts
    @Scripts.Render("~/bundles/jqueryval")
End Section

这篇关于我似乎无法获得一个非常基本的 cookie 登录示例来使用 MVC5 和 OWIN的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
相关文章
C#/.NET最新文章
热门教程
热门工具
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆