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.
- Microsoft.AspNet.Identity.Core
- Microsoft.AspNet.Identity.Owin
- ASP.NET MVC 5
- Microsoft.Owin.Host.SystemWeb
- Microsoft.Owin.Security
- Microsoft.Owin.Security.Cookies
- Microsoft.Owin.Security.OAuth
- 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的更多相关文章
- 【记录】ASP.NET MVC 4/5 Authentication 身份验证无效
在 ASP.NET MVC 4/5 应用程序发布的时候,遇到一个问题,在本应用程序中进行身份验证是可以,但不能和其他"二级域名"共享,在其他应用程序身份验证,不能和本应用程序共享, ...
- Forms Authentication in ASP.NET MVC 4
原文:Forms Authentication in ASP.NET MVC 4 Contents: Introduction Implement a custom membership provid ...
- [转]Implementing User Authentication in ASP.NET MVC 6
本文转自:http://www.dotnetcurry.com/aspnet-mvc/1229/user-authentication-aspnet-mvc-6-identity In this ar ...
- ASP.NET MVC:Form Authentication 相关的学习资源
看完此图就懂了 看完下面文章必须精通 Form authentication and authorization in ASP.NET Explained: Forms Authentication ...
- ASP.NET MVC with Entity Framework and CSS一书翻译系列文章之目录导航
ASP.NET MVC with Entity Framework and CSS是2016年出版的一本比较新的.关于ASP.NET MVC.EF以及CSS技术的图书,我将尝试着翻译本书以供日后查阅. ...
- 【第三篇】ASP.NET MVC快速入门之安全策略(MVC5+EF6)
目录 [第一篇]ASP.NET MVC快速入门之数据库操作(MVC5+EF6) [第二篇]ASP.NET MVC快速入门之数据注解(MVC5+EF6) [第三篇]ASP.NET MVC快速入门之安全策 ...
- ASP.NET MVC View 和 Web API 的基本权限验证
ASP.NET MVC 5.0已经发布一段时间了,适应了一段时间,准备把原来的MVC项目重构了一遍,先把基本权限验证这块记录一下. 环境:Windows 7 Professional SP1 + Mi ...
- ASP.NET MVC项目演练:用户登录
ASP.NET MVC 基础入门 http://www.cnblogs.com/liunlls/p/aspnetmvc_gettingstarted.html 设置默认启动页面 public clas ...
- asp.net mvc 各版本区别
MVC 6 ASP.NET MVC and Web API has been merged in to one. Dependency injection is inbuilt and part of ...
随机推荐
- playframework 一步一步来 之 日志 (二)
带着之前的疑问,我们先回顾一下日志相关的知识: 首先是SL4J,SL4J是个什么东西来着?官方解释为:“The Simple Logging Facade for Java (SLF4J) serve ...
- 让.net core 支持静态文件
想不到默认的.net core竟然不支持静态文件,还需要额外配置中间件来支持 1.Nuget安装 Microsoft.aspnetcore.staticfiles 2.在Startup.cs中使用服 ...
- 《C#从现象到本质》读书笔记(八)第10章反射
<C#从现象到本质>读书笔记(八)第10章反射 个人感觉,反射其实就是为了能够在程序运行期间动态的加载一个外部的DLL集合,然后通过某种办法找到这个DLL集合中的某个空间下的某个类的某个成 ...
- javascript字符串方法总结
一.单引号字符串内部可以使用双引号,双引号字符串内部也可以使用单引号 "hello 'world'" 'welcome "to" js' 二.多行和转义 如果要 ...
- Memcache cpu占用过高
分析应该是memcache的内存大小还是默认配置,已经满足不了当前的大数据量的需要了,大量的新缓存需要进入,同时大量的旧缓存又需要被淘汰出来,一进一出导致CPU占用过多.进入注册表,找到:HKEY_L ...
- python_day1_变量
一.变量 定义: 通俗来讲可变化的量称之为变量,专业的解释为:把程序运算的中间结果临时存到内存里,以备后面的代码继续调用,这几个名字的学名就叫做“变量” 用法: name = 'zzx' 其中name ...
- ASP.NET对大文件上传的解决方案
在ASP.NET 开发的过程中,最大的问题就在于上传大文件时让开发者尤为的头疼,而且,上传时无法方便的做到多线程的操控和上传进度的显示.笔者在此给大家推荐一款简单易用的上传组件,从而快速便捷得解决了 ...
- JMeter 教程汇总链接
http://www.360doc.com/content/14/0318/23/16361380_361732630.shtml 可以作为入门系列教程. 尽管网页也给出了视频链接,但是我不建议看视频 ...
- shell 文件操作
序 在linux平台下开发,我们经常会接触到一些任务性质的工作,而处理方式多样化.现积累各个案例. 从远程服务器拉取文件到本地服务器 scp work@cp01-xx-dev.com: ...
- 「LOJ2000~2023」各省省选题选做
「LOJ2000~2023」各省省选题选做 「SDOI2017」数字表格 莫比乌斯反演. 「SDOI2017」树点涂色 咕咕咕. 「SDOI2017」序列计数 多项式快速幂. 我们将超过 \(p\) ...