c# - 我似乎无法获得一个非常基本的 cookie 登录示例来使用 MVC5 和 OWIN

标签 c# asp.net-mvc asp.net-mvc-5 owin

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

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

这是我的cookie配置

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

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

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);
        }
    }

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

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

public class TestController : ApiController
    {
        [Authorize(Roles = "Foo")]
        public int Get()
        {
            return 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 配置。

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) 家庭 Controller (家庭索引可供授权用户使用)

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

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

End Class

c) 帐户管理员(登录)

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) 账户模型

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) 索引 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) 登录 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

关于c# - 我似乎无法获得一个非常基本的 cookie 登录示例来使用 MVC5 和 OWIN,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/20319118/

相关文章:

c# - 弹出时如何使 TabTip.exe 窗口最大化

c# - 提交后将 ActionResult 返回到模态弹出窗口

javascript - ajax发送二维数组到操作方法错误 - asp.net mvc

twitter-bootstrap - MVC5 Razor - Bootstrap 按钮类不起作用

c# - UniqueNationalId.IsValid(对象值,ValidationContext validationContext)

c# - 如何从 .wav 声音进入双 [] C#

c# - 如何通过 MVC C# Razor 使用 Google Adsense

c# - 添加一批实体。如何确定调用 SaveChanges() 时哪些实体失败

c# - NHibernate 和 Firebird 的性能问题

jquery - <div> 展开点击时失去对齐