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.

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

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

    在 ASP.NET MVC 4/5 应用程序发布的时候,遇到一个问题,在本应用程序中进行身份验证是可以,但不能和其他"二级域名"共享,在其他应用程序身份验证,不能和本应用程序共享, ...

  2. Forms Authentication in ASP.NET MVC 4

    原文:Forms Authentication in ASP.NET MVC 4 Contents: Introduction Implement a custom membership provid ...

  3. [转]Implementing User Authentication in ASP.NET MVC 6

    本文转自:http://www.dotnetcurry.com/aspnet-mvc/1229/user-authentication-aspnet-mvc-6-identity In this ar ...

  4. ASP.NET MVC:Form Authentication 相关的学习资源

    看完此图就懂了 看完下面文章必须精通 Form authentication and authorization in ASP.NET Explained: Forms Authentication ...

  5. ASP.NET MVC with Entity Framework and CSS一书翻译系列文章之目录导航

    ASP.NET MVC with Entity Framework and CSS是2016年出版的一本比较新的.关于ASP.NET MVC.EF以及CSS技术的图书,我将尝试着翻译本书以供日后查阅. ...

  6. 【第三篇】ASP.NET MVC快速入门之安全策略(MVC5+EF6)

    目录 [第一篇]ASP.NET MVC快速入门之数据库操作(MVC5+EF6) [第二篇]ASP.NET MVC快速入门之数据注解(MVC5+EF6) [第三篇]ASP.NET MVC快速入门之安全策 ...

  7. ASP.NET MVC View 和 Web API 的基本权限验证

    ASP.NET MVC 5.0已经发布一段时间了,适应了一段时间,准备把原来的MVC项目重构了一遍,先把基本权限验证这块记录一下. 环境:Windows 7 Professional SP1 + Mi ...

  8. ASP.NET MVC项目演练:用户登录

    ASP.NET MVC 基础入门 http://www.cnblogs.com/liunlls/p/aspnetmvc_gettingstarted.html 设置默认启动页面 public clas ...

  9. asp.net mvc 各版本区别

    MVC 6 ASP.NET MVC and Web API has been merged in to one. Dependency injection is inbuilt and part of ...

随机推荐

  1. playframework 一步一步来 之 日志(一)

    日志模块是一个系统中必不可少的一部分,它可以帮助我们写程序的时候查看错误信息,利于调试和维护,在业务面,它也可以记录系统的一些关键性的操作,便于系统信息的监控和追踪. play的日志是基于logbac ...

  2. windows 性能监视器常用计数器

    转载地址:https://www.jianshu.com/p/f4406c29542a?utm_campaign=maleskine&utm_content=note&utm_medi ...

  3. 第二阶段第二次spring会议

    昨天我对39个组发表了建议以及总结了改进意见和改进方案. 今天我对便签加上了清空回收站功能 private void 清空回收站ToolStripMenuItem_Click(object sende ...

  4. 2019.02.17 spoj Query on a tree VII(链分治)

    传送门 跟QTREE6QTREE6QTREE6神似,改成了求连通块里的最大值. 于是我们对每条链开一个heapheapheap维护一下即可. MDMDMD终于1A1A1A链分治了. 代码: #incl ...

  5. MFC头文件

    AFX.H struct CRuntimeClass; // object type information class CObject; // the root of all objects cla ...

  6. Chapter5 生长因子、受体和癌症

    一.Src蛋白是一种蛋白激酶 可以磷酸化不同的底物,调节不同的通路 Src激酶主要磷酸化酪氨酸残基,而别的激酶主要磷酸化色氨酸.苏氨酸残基 二.EGF受体拥有酪氨酸激酶功能 胞内结构域有Src蛋白的同 ...

  7. Codeforces Round #541--1131F. Asya And Kittens(基础并查集)

    https://codeforces.com/contest/1131/problem/F #include<bits/stdc++.h> using namespace std; int ...

  8. (转载)Linux之虚拟机 rehl7的ip

    RHEL7最小化安装之后(桥接模式),我们查看本机IP, ip addr 我们要修改配置文件 找到目录 找到文件(每个人的ifcfg-eno16777736都不同),用vi编辑器打开修改配置文件 保存 ...

  9. IOS - 修改APP桌面名称为中文名称!

    1,修改“Display Name”为想要的中文. 2,修改“bundle display name”为想要的中文.

  10. Android开发工程师文集-1 小时学会Widget小组件开发

    前言 大家好,给大家带来Android开发工程师文集-1 小时学会Widget小组件开发的概述,希望你们喜欢 学会用Widget (小组件) Widget小组件很方便,很快捷,可以个性化,自己定制,相 ...