I cannot find a very simple cookie login example for working with MVC5 and OWIN

I tried to rewind ASP.NET MVC 5 for 2013, but so far I have not been able to get even the most basic authentication, which works correctly.

I read in 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 simplest simplest example I could find. So I tried this, but still cannot create a session for the user.

Here is my cookie configuration

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

Here is my main user 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 got into the login api twice, I would prefer that the second variable fooBar be configured for the user who is marked as authenticated, but when I check it, it just says that it is not authenticated, and it doesn’t There are no claims that I expected.

I also tried to create a basic service to just check if it was checked if I misunderstood how it works, but it also fails. If I try to go to it, it says that I am not authenticated, it does not redirect me, as I thought it would be.

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

I am sure that I just need to skip some basic ones, but so far, no matter what I played, and regardless of the various guides and tips that I saw on the Internet, nothing could make this simple scenario work. Any ideas on what I'm doing wrong?

+2
c # asp.net-mvc asp.net-mvc-5 owin
Dec 02 '13 at 0:36
source share
2 answers

The following post http://www.khalidabuhakmeh.com/asp-net-mvc-5-authentication-breakdown has some useful examples of OWIN.

I made a mistake, the correct link is: http://www.khalidabuhakmeh.com/asp-net-mvc-5-authentication-breakdown-part-deux So, we will move on to the vb approach for the main cookie entry:

a) Cookie configuration.

 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 is 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

 @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

 @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 
+1
Dec 06 '13 at 22:32
source share

I had similar problems

I could not understand what distinguishes my application (inherited from someone else) and the default sample code.

I found that my [Authorize] attribute was not used by the framework even when the rest of the user management stack worked.

In the end, I realized that AuthorizeAttribute is a Filter example and that by adding it explicitly to FilterConfig it started to be used as expected (although it was not added by default example code):

 public class FilterConfig { public static void RegisterGlobalFilters(GlobalFilterCollection filters) { filters.Add(new HandleErrorAttribute()); filters.Add(new AuthorizeAttribute()); } } 

and everything is as usual in the Application_Start method:

 FilterConfig.RegisterGlobalFilters(GlobalFilters.Filters); 

Edit:

Although this allows you to use the basic Authorize attribute, this leads to a problem where the infrastructure does not instantiate a method for each method with a set of Roles properties. So I had to find out what caused the problem. This was due to some Unity configuration code:

 var oldProvider = FilterProviders.Providers.Single(f => f is FilterAttributeFilterProvider); FilterProviders.Providers.Remove(oldProvider); 

Removing this (it was not actually used) fixed the problem, so I no longer needed FilterConfig.RegisterGlobalFilters(GlobalFilters.Filters); or

0
Nov 18 '16 at 15:53
source share



All Articles