ASP. NET MVC 5 authentication Breakdown

Source: Internet
Author: User

In my previous post, "ASP. NET MVC 5 authentication Breakdown", I broke down all the parts of the new ASP authentic ation scheme. That's great, but I didn ' t has a working example, 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. Follow this GUID to get it into yo UR 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'll need the following packages from NuGet in your presumably empty ASP.

    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. 5 bloated template.

Here is the main code file:

UsingMicrosoft.Owin;UsingOwin[assembly: owinstartup ( typeof (simplestauth. Startupnamespace simplestauth{ public partial class startup { span class= "n" >public void configuration ( Iappbuilder app) {configureauthentication (app} }}          /span>                

followed by the implementation of the Configureauthentication method:

    PublicPartialClassStartup{public void configureauthentication (iappbuilder app) {appusecookieauthentication (new  Cookieauthenticationoptions {authenticationtype = defaultauthenticationtypes. Applicationcookieloginpath = new pathstring ( "/login" ) } }             /span>                
Web. config settings

OWIN doesn ' t use the standard forms authentication that I ' ve grown to love, it implements something completely. For that reason, I has to remember this snippet of CONFIG.

 <system.web> <authentication mode=  "None" /> <compilation debug=  "true" targetframework= "4.5" /> targetframework= "4.5" /> Span class= "NT" ></system.web> <system.webserver> <modules> Span class= "NT" ><remove name= "FormsAuthenticationModule" / > </modules> </SYSTEM.WEBSERVER>      

The formsauthenticationmodule is removed, and additionally the authentication mode are set to None. Although, I know the site would have authentication; That authentication'll 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.

PublicClassAuthenticationcontroller:Controller{IauthenticationmanagerAuthentication{Get{ReturnHttpContext.Getowincontext().Authentication;}}[GET("Login")]PublicActionResultShow(){ReturnView();}[POST("Login")][Validateantiforgerytoken]PublicActionResultLogin(LoginmodelInput){If(Modelstate.IsValid){If(Input.Hasvalidusernameandpassword){VarIdentity=NewClaimsidentity(New[]{NewClaim(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(NewClaim(Claimtypes.Role,"Guest"));Tell OWIN the identity provider, optionalIdentity. Addclaim (New Claim (Identityprovider, "simplest Auth"));Authentication.SignIn(NewAuthenticationproperties{Ispersistent=Input.RememberMe},Identity);ReturnRedirecttoaction("Index","Home");} } return view ( " Show "input); } [get ( "logout"  )] public actionresult logout () { span class= "n" >authentication. Signout (defaultauthenticationtypes. Applicationcookie); return redirecttoaction ( "login" ); } }             /span>                

I ' ll leave out the implementation of the views, because it's pretty standard Razor syntax. The thing to take note in the code above is the creation of a claimsidentity. All yourcode needs to does is generate this class, and it doesn ' t matter from Where:database, Active Directory, We b 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 are need to does to get OWIN authentication in your ASP applications without the craziness That's comes standard in the Visual Studio templates. The standard templates in Visual Studio force you to use the Entity Framework and have a lot of ceremony for what's Essentiall Y a really simple solution. So does yourself a favor and dump that mess and just implement something this makes more sense for you and your team.

Update

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

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

Have multiple authentication methods on can leads to very strange behaviors. Good luck and I ' d love-hear how your projects is going. I also recommend you read one of my later posts on securely storing passwords.

ASP. NET MVC 5 authentication Breakdown

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.