ASP.NET MVC 5 Authentication Breakdown

In my previous post, "ASP.NET MVC 5 Authentication Breakdown", I broke down all the parts of the new ASP.NET MVC authentication scheme. That‘s great, but I didn‘t have a working example that you, a curious developer, could download and play around with. So I set out today to figure out what the bare minimum code needed was. Fiddling around, I was able to get OWIN powered authentication into an ASP.NET MVC app. Follow this guid to get it into your application as well.

No fluff, just the real stuff

TL;DR go to https://github.com/khalidabuhakmeh/SimplestAuthMvc5 to clone the code.

NuGet Packages

You will need the following packages from NuGet in your presumably empty ASP.NET MVC project.

  1. Microsoft.AspNet.Identity.Core
  2. Microsoft.AspNet.Identity.Owin
  3. ASP.NET MVC 5
  4. Microsoft.Owin.Host.SystemWeb
  5. Microsoft.Owin.Security
  6. Microsoft.Owin.Security.Cookies
  7. Microsoft.Owin.Security.OAuth
  8. Owin

Notice how the majority of them center around Owin.

Start Up Classes

OWIN follows of a convention of needing a class called StartUp in your application. I followed the standard pattern of using a partial class found in the default ASP.NET MVC 5 bloated template.

Here is the main code file:

using Microsoft.Owin;
using Owin;

[assembly: OwinStartup(typeof(SimplestAuth.Startup))]

namespace SimplestAuth
{
    public partial class Startup
    {
        public void Configuration(IAppBuilder app)
        {
            ConfigureAuthentication(app);
        }
    }
}

Followed by the implementation of the ConfigureAuthentication method:

    public partial class Startup
    {
        public void ConfigureAuthentication(IAppBuilder app)
        {
            app.UseCookieAuthentication(new CookieAuthenticationOptions
            {
                AuthenticationType = DefaultAuthenticationTypes.ApplicationCookie,
                LoginPath = new PathString("/Login")
            });
        }
    }

Web.Config settings

OWIN doesn‘t use the standard forms authentication that I‘ve grown to love, it implements something completely different. For that reason, I have to remember this snippet of config.

<system.web>
    <authentication mode="None" />
    <compilation debug="true" targetFramework="4.5" />
    <httpRuntime targetFramework="4.5" />
  </system.web>
  <system.webServer>
    <modules>
      <remove name="FormsAuthenticationModule" />
    </modules>
  </system.webServer>

The FormsAuthenticationModule is removed, and additionally the authentication mode is set to None. Although, I know the site will have authentication; that authentication will be handled by OWIN.

Authentication Controller

Now it‘s business time! Now we just need a controller to authentication and create the cookie for authentication. We‘ll also implement log out, because sometimes our users want to leave (not sure why though :P).

Note: I‘m using AttributeRouting here. Giving it a try, but I love Restful Routing.

public class AuthenticationController : Controller
    {
        IAuthenticationManager Authentication
        {
            get { return HttpContext.GetOwinContext().Authentication; }
        }

        [GET("login")]
        public ActionResult Show()
        {
            return View();
        }

        [POST("login")]
        [ValidateAntiForgeryToken]
        public ActionResult Login(LoginModel input)
        {
            if (ModelState.IsValid)
            {
                if (input.HasValidUsernameAndPassword)
                {
                    var identity = new ClaimsIdentity(new [] {
                            new Claim(ClaimTypes.Name, input.Username),
                        },
                        DefaultAuthenticationTypes.ApplicationCookie,
                        ClaimTypes.Name, ClaimTypes.Role);

                    // if you want roles, just add as many as you want here (for loop maybe?)
                    identity.AddClaim(new Claim(ClaimTypes.Role, "guest"));
                    // tell OWIN the identity provider, optional
                    // identity.AddClaim(new Claim(IdentityProvider, "Simplest Auth"));

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

                    return RedirectToAction("index", "home");
                }
            }

            return View("show", input);
        }

        [GET("logout")]
        public ActionResult Logout()
        {
            Authentication.SignOut(DefaultAuthenticationTypes.ApplicationCookie);
            return RedirectToAction("login");
        }
    }

I‘ll leave out the implementation of the views, because it is pretty standard Razor syntax. The thing to take note in the code above is the creation of a ClaimsIdentity. All yourcode needs to do is generate this class, and it doesn‘t matter from where: Database, Active Directory, Web Service, etc. The rest of the code above is really just boilerplate. You‘ll just need to use the AuthenticationManager from the OWIN context to SignInand SignOut.

Conclusion

There you have it. A basic breakdown of what you need to do to get OWIN authentication in your ASP.NET MVC applications without the craziness that comes standard in the Visual Studio templates. The standard templates in Visual Studio force you to use Entity Framework and has a lot of ceremony for what is essentially a really simple solution. So do yourself a favor and dump that mess and just implement something that makes more sense for you and your team.

Update

A reader ran into a nasty redirect issue in his production environment after deploying. This was a simple IIS Setup issue. If you are experiencing the same issue, please do the following in your IIS environment:

  • Disable Windows Authentication Module
  • Disable Forms Authentication Module (should have already)
  • Enable Anonymous Authentication Module

Having multiple authentication methods on can lead to very strange behaviors. Good luck and I‘d love to hear how your projects are going. I also recommend you read one of my later posts on securely storing passwords.

时间: 2024-11-08 23:53:41

ASP.NET MVC 5 Authentication Breakdown的相关文章

【记录】ASP.NET MVC 4/5 Authentication 身份验证无效

原文:[记录]ASP.NET MVC 4/5 Authentication 身份验证无效 在 ASP.NET MVC 4/5 应用程序发布的时候,遇到一个问题,在本应用程序中进行身份验证是可以,但不能和其他"二级域名"共享,在其他应用程序身份验证,不能和本应用程序共享,示例代码: System.Web.Security.FormsAuthentication.SetAuthCookie("蟋蟀", true); webconfig 配置如下: <system.

Professional C# 6 and .NET Core 1.0 - Chapter 41 ASP.NET MVC

What's In This Chapter? Features of ASP.NET MVC 6 Routing Creating Controllers Creating Views Validating User Inputs Using Filters Working with HTML and Tag Helpers Creating Data-Driven Web Applications Implementing Authentication and Authorization W

7 天玩转 ASP.NET MVC — 第 5 天

目录 第 1 天 第 2 天 第 3 天 第 4 天 第 5 天 第 6 天 第 7 天 0. 前言 欢迎来到第五天的学习.希望第一天到第四天的学习,你都是开心的. 1. Lab 22 - 增加 Footer 在这个实验中,我们将会向 Employee 页面添加 Footer.本次实验的目标是理解分部视图(Partial Views). 什么是「Partial Views」? 逻辑上讲,分部视图(Partial Views) 是一个可重用的视图,它不会被直接显示.它会被其它视图所包含,然后作为该

ASP.Net MVC多语言

.NET MVC 多语言网站 通过浏览器语言首选项改变MVC的语言,通过浏览器语言选项,修改脚本语言. 一.添加资源文件 1.添加App_GlobalResources文件夹. 2.添加默认的资源文件和对应的语言码资源文件.如zh-cn代表中国大陆,en-us代表美制英语.详情:http://www.lingoes.cn/zh/translator/langcode.htm 3.将资源文件设置成public.新建时默认是internal,这样不能被访问. 右键点击资源文件,在其的属性中将自定义工

七天学会ASP.NET MVC (四)——用户授权认证问题

小编应各位的要求,快马加鞭,马不停蹄的最终:七天学会 Asp.Net MVC 第四篇出炉.在第四天的学习中.我们主要了学习怎样在MVC中怎样实现认证授权等问题.本节主要讲了验证错误时的错误值,client验证,授权认证及登录注销功能的实现. 系列文章 七天学会ASP.NET MVC (一)--深入理解ASP.NET MVC 七天学会ASP.NET MVC (二)--ASP.NET MVC 数据传递 七天学会ASP.NET MVC (三)--ASP.Net MVC 数据处理 七天学会ASP.NET

ASP.NET MVC下判断用户登录和授权的方法

日常开发的绝大多数系统中,都涉及到管理用户的登录和授权问题.登录功能(Authentication),针对于所有用户都开放:而授权(Authorization),则对于某种用户角色才开放. 在asp.net mvc中,微软虽然已经帮助开发者构建了ASP.NET Identity这样强大的验证授权框架,但是如果想定制更多的逻辑功能的话,还得自己动动手. 根据日常的开发经验,我总结了下面1种方法: 1 学习了很多人的代码后,发现在Controller里有一个OnActionExecuting方法,此

7 天玩转 ASP.NET MVC — 第 4 天

目录 第 1 天 第 2 天 第 3 天 第 4 天 第 5 天 第 6 天 第 7 天 0. 前言 欢迎来到第四天的 MVC 系列学习中.如果你直接开始学习今天的课程,我强烈建议你先完成之前的学习内容再来到这里. 1. Lab 15 - 认证错误的保留值 在 Lab 13 中,我们介绍了服务器端的认证,并且在 Lab 14 中,我们通过添加自定义认证的方式将其提示到一个新的层级. 我强烈建议你再回顾一下 Lab 14.再次执行应用,并且能够很好地理解代码以及输出. 在 Lab 15 中,我们将

深入理解ASP.NET MVC Day1

深入理解ASP.NET MVC ASP.NET vs MVC vs WebForms 许多ASP.NET开发人员开始接触MVC认为MVC与ASP.NET完全没有关系,是一个全新的Web开发,事实上ASP.NET是创建WEB应用的框架而MVC是能够用更好的方法来组织并管理代码的一种更高级架构体系,所以可以称之为ASP.NET MVC. 我们可将原来的ASP.NET称为 ASP.NET Webforms,新的MVC 称为ASP.NET MVC. ASP.NET Web Form ASP.NET 在过

关于ASP.NET MVC的权限认证的一些总结

最近在学ASP.NET MVC的权限认证的一些东西,上网搜索了一阵,发现网上的方法大多数是以下几类: 一.FormsAuthentication.SetAuthCookie(admin.Name, false)或者是FormsAuthenticationTicket 感受:感觉FormsAuthentication.SetAuthCookie这种方法重在检查是否有用户登录等,需要检查权限时,要调用this.User.Identity.IsAuthenticated方法来检查是否授权等,每次要检查