前往小程序,Get更优阅读体验!
立即前往
首页
学习
活动
专区
工具
TVP
发布
社区首页 >专栏 >ASP.NET MVC 5 Authentication Breakdown

ASP.NET MVC 5 Authentication Breakdown

作者头像
阿新
发布2018-04-12 10:37:46
9150
发布2018-04-12 10:37:46
举报
文章被收录于专栏:c#开发者c#开发者

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:

代码语言:javascript
复制
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:

代码语言:javascript
复制
    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.

代码语言:javascript
复制
<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.

代码语言:javascript
复制
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.

本文参与 腾讯云自媒体分享计划,分享自作者个人站点/博客。
原始发表:2015-05-21 ,如有侵权请联系 cloudcommunity@tencent.com 删除

本文分享自 作者个人站点/博客 前往查看

如有侵权,请联系 cloudcommunity@tencent.com 删除。

本文参与 腾讯云自媒体分享计划  ,欢迎热爱写作的你一起参与!

评论
登录后参与评论
0 条评论
热度
最新
推荐阅读
目录
  • NuGet Packages
  • Start Up Classes
  • Web.Config settings
  • Authentication Controller
  • Conclusion
  • Update
领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档