Skip to content

A primer on OWIN cookie authentication middleware for the ASP.NET developer

October 24, 2013

There have been many changes to how authentication is performed for web applications in Visual Studio 2013. For one, there’s a new “Change Authentication” wizard to configure the various ways an application can authenticate users. The approach to authentication that’s undergone the most changes in this version is local cookie-based authentication and external login providers based upon OAuth2 and OpenID (social logins). This style of logins is now collectively known as the “Individual User Accounts” and it’s one option in the new authentication wizard. This purpose of this post (and followup posts) is to explain the new authentication plumbing for this option.

Individual

OWIN authentication middleware

With .NET 4.5.1, for ASP.NET applications, all the underlying code that handles “Individual User Accounts” (as well as the templates in Visual Studio 2013) is new. This means for cookie based authentication we no longer use Forms authentication and for external identity providers we no longer use DotNetOpenAuth.

The replacement is a framework called OWIN authentication middleware and it’s targeting the OWIN API. I don’t plan to motivate OWIN here (this a good article on the subject), but in short it’s an abstraction API for the web host. Many frameworks such as Web API and SignalR (as well as other non-Microsoft frameworks) are coded to this abstraction so they do not require any particular web host (such as IIS).

So this OWIN authentication middleware is the new framework for authenticating users. The two main options we have is local authentication where the users enter credentials into the application itself, and external logins where the user is redirected to the various social login providers that are supported by Microsoft.

This post will only cover the cookie approach. Subsequent posts will describe the others.

OWIN cookie authentication middleware

Previously, for local authentication we used to use Forms authentication and its job was to issue a cookie to represent the current logged in user. Upon subsequent requests from the user, Forms authentication would validate the cookie and make a principal object available that represents the user’s identity.

Now, the new cookie-based implementation is called the OWIN cookie authentication middleware. This performs the same task — it can issue a cookie and then validates the cookie on subsequent requests. One improvement the OWIN cookie authentication middleware has over the previous Forms authentication is that it is claims-aware.

Another function of Forms authentication was that when the application issued a 401 unauthorized HTTP status code, Forms authentication would convert the response into a 302 redirect to the application’s login page. Well, the new cookie authentication middleware does that too.

Configuration

The new OWIN cookie authentication middleware is configured in App_Start/Startup.Auth.cs and consists of these lines of code:

public void ConfigureAuth(IAppBuilder app)
{
   app.UseCookieAuthentication(new CookieAuthenticationOptions
   {
      AuthenticationType = DefaultAuthenticationTypes.ApplicationCookie,
      LoginPath = new PathString("/Account/Login")
   });
}

This API call is configuring an identifier (or name) for this authentication middleware (AuthenticationType) and this is needed since there can be different authentication middleware. Also, this name influences the name of the cookie that will be used. The LoginPath is simply the URL to the login page when unauthorized requests need to be redirected.

Redirect to login

As mentioned above, the OWIN cookie middleware will redirect unauthorized requests to the login page. This is only performed if the LoginPath is set. If it’s not set, then this feature is disabled.

Login

On the login page once the user’s credentials have been validated, we can call into OWIN to authenticate the user. We don’t call the cookie middleware directly, instead we call into the “OWIN Authentication Manager”, which is an abstraction for all of the possible OWIN authentication middleware that’s being used. This call can be seen in the new templates and here’s the code if you wanted to invoke it yourself:

var claims = new List<Claim>();
claims.Add(new Claim(ClaimTypes.Name, "Brock"));
claims.Add(new Claim(ClaimTypes.Email, "brockallen@gmail.com"));
var id = new ClaimsIdentity(claims,
                            DefaultAuthenticationTypes.ApplicationCookie);

var ctx = Request.GetOwinContext();
var authenticationManager = ctx.Authentication;
authenticationManager.SignIn(id);

The above code creates the set of claims to represent the identity of the user and creates a ClaimsIdentity from the claims. Note the second parameter to the ClaimsIdentity constructor — this indicates the type of authentication. In the OWIN authentication middleware, this authentication type must match that of the middleware being targeted. So since this code is presumably trying to issue a cookie, then this value must be the same as the name we assigned to the cookie middleware from the ConfigureAuth initialization code from above.

Once the ClaimsIdentity is created, we then access the OwinContext which has the AuthenticationManager. We use its SignIn API passing the ClaimsIdentity. This then matches the authentication type to the corresponding authentication middleware and since we match the cookie authentication middleware, a cookie is issued that contains the claims of the ClaimsIdentity.

An additional option on the SignIn API is to pass a AuthenticationProperties object. This has an IsPersistent property that indicates if the cookie is to be persistent.

Visual Studio 2013 templates and ASP.NET Identity

The VS2013 templates use the new ASP.NET Identity system to obtain the claims for the user. In the templates you will see this being performed by the UserManager’s CreateIdentityAsync API. Additionally, the MVC and WebForms templates provide many helper methods that encapsulate accessing and calling into the authentication manager.

Protecting the cookie

As a side note, the contents of the cookie are protected as you’d expect (signed and encrypted). This protection is by default, which is good. There is yet another security setting, though, that requires attention: SSL. By default (presumably for simplicity and ease of development) the cookie is only issued with the secure flag (i.e. require SSL) if the incoming request is SSL. This is an important setting to change when you release your application to production. This setting is configured with an enum:

public enum CookieSecureOption
{
   SameAsRequest,
   Never,
   Always
}

and would be done with this configuration change (notice the CookieSecure flag):

public void ConfigureAuth(IAppBuilder app)
{
   app.UseCookieAuthentication(new CookieAuthenticationOptions
   {
      AuthenticationType = DefaultAuthenticationTypes.ApplicationCookie,
      LoginPath = new PathString("/Account/Login"),
      CookieSecure = CookieSecureOption.Always
   });
}

Other cookie configuration

There are two other settings of particular interest on the CookieAuthenticationOptions that might be familiar: ExpireTimeSpan and SlidingExpiration. The expiration allows the application to indicate how long the cookie is valid, and the sliding flag allows the expiration to be renewed as the user remains active within the application. The default for the expiration is 14 days and the default for the sliding flag is true.

Cookie authentication

So now that we have a cookie issued to the browser, upon subsequent requests the cookie will be sent and the cookie middleware must authenticate the request. The cookie middlware looks for the cookie name it issued (again from the name we assigned to the cookie middleware). If the cookie is absent, then it does nothing. If the cookie is present, then the cookie middleware reads and validates the cookie, and then if validated unpacks the claims contained therein and creates a ClaimsIdentity and sets this object into the OWIN context. Any downstream code could then use this OWIN API to determine the caller’s identity:

OwinContext ctx = Request.GetOwinContext();
ClaimsPrincipal user = ctx.Authentication.User;
IEnumerable<Claim> claims = user.Claims;

Of course, the ASP.NET APIs also work (Page.User, Controller.User) as well as the IIS host approaches (HttpContext.User, Thread.CurrentPrincipal and ClaimsPrincipal.Current).

Logout

Logging a user out is quite simple — there’s an API on the OWIN authentication manager called SignOut, which removes the cookie:

var ctx = Request.GetOwinContext();
var authenticationManager = ctx.Authentication;
authenticationManager.SignOut();

Fin

I hope this helps to understand the new OWIN cookie authentication middleware in .NET 4.5.1 and Visual Studio 2013.

101 Comments leave one →
  1. October 25, 2013 1:11 am

    Reblogged this on http://www.leastprivilege.com.

  2. November 5, 2013 4:40 pm

    Thanks. This article has helped me understand how the OWIN authentication works. I have a question. So if we get a claim from specifying scopes like “user_birthday” from “facebook” where do we hook that into the claims?

  3. Venki permalink
    November 7, 2013 9:35 am

    Thank You Very Much .. This helped me a lot ..

  4. November 8, 2013 10:25 am

    Actually, this helped a lot. I notice though that after the SignIn step. The code immediately shows the user is Authenticated.

    However, after I then redirect another page; the the Authenticated flag becomes false — appears the entire context gets lost.

    • Cesar Pastor permalink
      July 20, 2015 5:21 am

      Same problem I’m facing

  5. Dmitrij permalink
    November 29, 2013 10:24 am

    Hi Brock,
    I am using Google and Facebook authentication providers from the sample project from VS 2013 and have found a problem when I have successfully logged-in with Google or Facebook account and after that I choose log off, and try to log-in again with the same provider no Username and Password from another Google or Facebook account is asked.
    I am remaining in the same previous logged-in account.

    Could you help how to show the google/facebook sign-in page every time when I select Google/Facebook login?

    • December 7, 2013 3:32 pm

      This is because those providers are using OAuth2 and that’s not an authentication protocol and as such there’s no concept of forcing re-authentication. Now, those providers might have customized their implementations to allow this sort of feature, but that’s provider specific. You’d have to go read their docs to see if they support it and then configure the middleware to pass the custom param.

  6. Max permalink
    December 5, 2013 7:25 pm

    This was very helpful to implement cookie auth for the webapp version of a WebApi project, thank you so much!

  7. January 2, 2014 11:50 am

    Is it possible to share the Owin Forms Authentication across different virtual directories/applications?

    • January 4, 2014 10:51 am

      Sure, you just need to make sure you have the same verification logic and key. In OWIN this component is normally provided by the host, and in IIS this uses the machine key. In other hosts you’d need to configure it.

      • May 9, 2014 6:30 pm

        Hi Brock,

        Would you be able to provide a bit more detail on what is needed to accomplish this. I’ve been unable to get two apps on the same domain in visual studio 2013 running locally to use the same cookie. The identity project issues the cookie without problems, but it’s not accepted by the other app, the cookie domain is localhost and the path ‘/’.

        Thanks,

        • May 11, 2014 9:48 am

          Did you sync the <machineKey> values in web.config?

        • February 13, 2015 7:31 pm

          You also have to make sure the config for both Startup.cs files match in your resource and authentication project.

  8. G.bes permalink
    January 6, 2014 2:28 pm

    Great article! Thanks.

    I’m wodering if there’s a way to run a piece of code and signout the user automatically after a predefined timeout?

    • January 6, 2014 3:29 pm

      From the server you can’t just reach out to the browser to revoke a cookie. So no, there’s nothing like this built in.

      • G.bes permalink
        January 7, 2014 1:49 am

        Thanks for your reply. If i want to implement a home made time-out mechanism wich starting point would you suggest? Which approch is suitable for this scenario?

  9. January 16, 2014 4:31 am

    This article is great. I have been so confused coming back to .NET and expecting the old Forms Auth logic.

    Is there a way to change the LoginPath that is set to the cookie after it has been created?

    • January 16, 2014 8:17 am

      There’s a property on the CookieAuthenticationOptions called CookiePath — is this what you’re looking for?

  10. Tai permalink
    February 22, 2014 12:42 am

    Brock,

    I would be lost if it wasn’t for all your posts on this subject. So here is a point of some confusion. Does this replace WIF’s session authentication module? Was it like we got a new tech for auth with WIF and now this is new new?

    Also, I can’t find info ANYWHERE on how you secure a resource (like a webpage) with a claim. Is there some equivalent in OWIN to but for claims. Is it some combination with WIF and OWIN? Or is this stuff just so new its only good for authentication, in which case… REALLY?? Who makes web pages without authorization?

    Thanks!

    • February 22, 2014 8:58 am

      Yes, the new Katana cookie MW is a SAM replacement. Also, there’s a new WS-Fed MW that was just released (as beta) this week. Katana is the way forward for anything that used to be done as a HttpModule in IIS.

      As for “securing a resource” not sure what you mean. Each framework (SignalR, Web API, etc) has their own helpers for authorization. And ultimately, since we’re working over HTTP, the way you restrict access is to issue a 401 status code from your code.

      • Tai permalink
        February 22, 2014 1:39 pm

        Thanks for the reply. By securing a resource I mean how do I lock down something like a web page or folder by claim (I would think role is dead). Say I have an admin area only for admins, there used to be simple web.config configuration to say the admin folder is only for role admin.

        I can’t find the equivalent with OWIN. Thanks

        • February 22, 2014 1:45 pm

          Let me respond by asking how you did it with roles?

          • Tai permalink
            February 23, 2014 2:52 am

            Sure. So using forms authentication and the roles membership provider I simply add this configuration to the web.config:

            This has always been straight forward. I would expect that we could now lock down a page or directory by a claim instead of a role. Or maybe I’m just thinking that claims replaces roles and that I can create a claim for a permission like Admin add it to my claims list and then indicate that this directory only allows access if you have that claim. Or am crazy and claims have nothing to do with permissions and we still need roles and the above just works, although who would make the cookie for the roles? Thanks!

          • Tai permalink
            February 23, 2014 2:56 am

            The blog stripped my config example here is another try:

            location path=”administration”
            system.webServer
            security
            authorization
            clear
            add accessType=”Allow” roles=”admin”
            authorization
            security
            system.webServer
            location

          • February 23, 2014 9:21 am

            Well, my point in asking was to illustrate that these still exits. You can also build your own infrastructure to do claims-based checks and when the user fails authorization you can return 401 status code. Also, .NET has some built in with its ClaimsAuthorizationManager and we have some helpers with IdentityModel: https://github.com/thinktecture/Thinktecture.IdentityModel

          • Tai permalink
            February 23, 2014 12:41 pm

            Ok, so then i’m not going completely crazy. OWIN is half of the solution, authentication. So MS is really leaving authorization out and I’m now falling back to an HTTP Module again with ClaimsAuthorizationManager. So at this point I’m OWIN for authentication and WIF for Authorization. What’s the benefit of using OWIN at all, why don’t I just also use WIF’s SessionAuthenticationModule and ClaimsAuthorizationModule and have a full solution. Is OWIN providing any functionality that I’m not just getting already with WIF?

          • February 23, 2014 2:32 pm

            OWIN is a tough sell if you don’t care about host independence since it’s a new stack to learn. But eventually it will allow for faster apps. Also, it’s for Microsoft’s benefit so that they can build one library (security for example) that works across all their frameworks (Web API, ASP.NET, SignalR, etc).

  11. March 10, 2014 1:39 pm

    Good stuff – I’m fairly new to the new .NET Identity model (I know only the basics). I have a scenario where every user is associated to possibly many organizations. Instead of querying for this every time (a lot), I feel this might be a good place to associate a users organizations with the user (using a claim). Is there a certain claim type I should use? Should I just add these claims in the registration pipeline? Does this scenario even make sense for adding claims?

    • March 10, 2014 2:38 pm

      Yes, this sounds like a claim — it’s identity info about the user.

  12. valdis permalink
    April 17, 2014 1:06 am

    Great

  13. Zen permalink
    April 25, 2014 11:12 am

    Hi Brock,

    Thanks for blogging about the OWIN Cookie Authentication Middleware.

    I have a quick question for you. Is there a way to intercept the events before and after the OWIN Cookie Middlewear reads the cookie and creates the ClaimsIdentity object?

    Thanks!

    Zen

    • April 25, 2014 2:17 pm

      Yes, the CookieAuthenticationOptions class has a Provider property — it’s an instance of the CookieAuthenticationProvider class: http://msdn.microsoft.com/en-us/library/microsoft.owin.security.cookies.cookieauthenticationprovider%28v=vs.113%29.aspx and it has properties which are delegates you can subscribe to. This allows you to validate the cookie as it comes into the application (OnValidateIdentity). In this callback you can reject or replace the identity.

      • Zen permalink
        April 25, 2014 11:18 pm

        Thanks Brock for your prompt reply. I might be wrong, but I think that OnValidateIdentity runs on only predefined intervals specified by validateInterval argument.

        What I am interested to know is, the code that runs on every request and reads the authentication cookie, deserializes, creates an instance of ClaimsIdentity (if it is found to be valid) and attaches it to the HttpContext.

        Any ideas?

        Thank!

        Zen

        • April 29, 2014 9:36 pm

          Umm, no, as far as I can tell the validate event runs on each request, assuming the cookie is valid (decrypts and is not expired).

  14. May 27, 2014 3:00 am

    For single sign on there is a bug in asp.net mvc templates available. For signle sign on to work using machine key, One need to add two MVC project with web APi option checked . Then hosted the projects on iis and try single sign on by using the authorize attribute on WEBAPi functions. It is working with me . But i am not able to attain the same behavior with only WEB API based project selection. I am of view that there are bugs in the project selection and they should be address .

  15. June 4, 2014 6:00 am

    Very informative ..thanks. I think there is a small typo that you might want to fix. “By default (presumably for simplicity and ease of development) the cookie is only issued with the secure flag (i.e. require SSL)***is*** the incoming request is SSL” ..’is’ needs to be replaced with “if”. Thanks.

  16. KARTHIKEYAN N R permalink
    July 5, 2014 3:07 am

    Dear Brockallen,

    I switched over from SAMs to the new OWIN authentication.. I love the OWIN features and your article guided me to implement the same in my project without any trouble. Thanks for sharing and will add your name and blog in my thanks page as gratitude.

    • KARTHIKEYAN N R permalink
      July 8, 2014 5:27 am

      One problem I am facing… After logout using browser back button I can retain the previous session.. I used the following code to clear the session and all folks..

      Dim ctx2 = Request.GetOwinContext()
      Dim authenticationManager = ctx2.Authentication
      authenticationManager.SignOut()

      Session.Clear() ‘clear session
      Session.Abandon() ‘//Abandon session
      Response.Cache.SetExpires(DateTime.UtcNow.AddMinutes(-1))
      Response.Cache.SetCacheability(HttpCacheability.NoCache)
      Response.Cache.SetNoStore()
      Response.Redirect(“Login”)
      Return (Nothing)

      But Logout is possible only if close the browser. Also request you to provide a solution to get rid of back button as in gmail.com

  17. europlayers permalink
    September 4, 2014 11:48 am

    Thanks for the article. How do you retreive the values stored in the claims once the user is logged in. For example you wrote:

    claims.Add(new Claim(ClaimTypes.Email, “brockallen@gmail.com”));

    How do you retrieve the email address later on? I’m probably missing something obvious but I don’t see how to do it.

    • September 4, 2014 11:51 am

      Downcast the User to a ClaimsPrincipal.

      • europlayers permalink
        September 4, 2014 12:09 pm

        Thanks. This works:

        OwinContext ctx = Request.GetOwinContext();
        ClaimsPrincipal user = ctx.Authentication.User;
        IEnumerable claims = user.Claims;
        string email= claims.FirstOrDefault(x => x.Type == ClaimTypes.Email).Value;

        Is the above code what you meant?

        It’s just I was expecting to be able to do something like this:
        string email= claims[ClaimTypes.Email];

        • September 4, 2014 12:11 pm

          Yep — You need to query the claims collection. It’s very LINQ friendly. Normally I create extension methods to encapsulate those queries.

          • europlayers permalink
            September 4, 2014 12:14 pm

            Thanks. Makes sense!

  18. europlayers permalink
    September 6, 2014 5:19 am

    Assuming you do this:

    OwinContext ctx = Request.GetOwinContext();
    ClaimsPrincipal user = ctx.Authentication.User;

    To retrieve the value of a claim is there any difference between doing this:
    string email= user.claims.FirstOrDefault(x => x.Type == ClaimTypes.Email).Value;

    and this:
    string email= user.FindFirst(ClaimTypes.Email).Value;

    The 2nd one seems cleaner but FindFirst is a function that doesn’t seem to be used in code examples I’ve seen. Is there a reason for this or is it just being overlooked?

    • September 6, 2014 1:38 pm

      They’re essentially the same except FindFirst does a case insensitive comparision for the type. But as I said before, I normally created my own extension methods.

  19. David permalink
    September 13, 2014 6:30 am

    Where is Asp.Identity storing the information about the claims referring to a cookie?

    • September 13, 2014 5:26 pm

      The claims are cached in the cookie itself.

      • David permalink
        September 13, 2014 6:27 pm

        Would that not be rather insecure? I am aware that these supposed to be encrypted but how secure this encryption is? It does not appear that one sets any encryption keys anywhere, does that mean that anyone who has an installation of VS with ASP.Identity in it can find a way to decrypt a cookie and then create a rogue one with any claims that they please?

        • September 13, 2014 6:31 pm

          They’re signed and encrypted with the ASP.NET machineKey and the assumption is that you’re using SSL. All of these factors make it safe.

  20. David permalink
    September 14, 2014 4:49 am

    What would be the best way to link an application user object to the identity object?

    • September 17, 2014 11:49 am

      with a foreign key? maybe i don’t understand the question.

      • David permalink
        September 19, 2014 4:39 pm

        For example, I have a database that contains application user objects. It is easy to find which object to retrieve during the login process: we can use their username, or email, or whatever + password.

        However, once the user has logged in, how do we keep track of him navigating through the controller calls using the method described in the post?

        • September 20, 2014 3:07 pm

          You put a claim into the cookie that identifiers who the user is, such as the NameIdentifier claim type.

  21. roatin permalink
    September 18, 2014 2:48 am

    Great article, really tied a lot of things together for me. Only thing, I did not understand what key is used for cookie signing until the comment section (btw thanks for your diligent and prompt responses!), which for iis hosted apps means the machine key (as expected). Thanks for clearing that up.

    Really appreciate your and Dominick’s contributions to this space.

  22. Karthick permalink
    March 13, 2015 1:47 am

    How to solve the back button problem ?. After logging out, if the end user press the back button the previous window is displaying but if they click any link its redirected to login page. I just want to show the login page again if the user press the back button after logout. Please guide.

  23. breakskater permalink
    April 22, 2015 12:37 pm

    Hi Brock, great article for explaining the new OWIN Authentication API. I have a quick question. How can one authentication across a MVC 4 (non-OWIN) and MVC 5 (OWIN) app. We have set the CookieName to the same in both apps, however looking at Fiddler the cookie is not present in the MVC 5 app both are localhost but different ports. Thanks in advance for your help

    • May 1, 2015 9:53 pm

      Yea, that prolly won’t work. You can still use forms or WIF’s SAM from new MVC 5 apps.

  24. April 26, 2015 10:44 am

    Reblogged this on E-commerce y algo mas..

  25. sumanth permalink
    April 28, 2015 5:37 am

    Thanks a lot man

  26. Karthikeyan permalink
    May 27, 2015 2:44 pm

    Hi… Great article and I am successfully using this in vs 2013… But things are changed now and asp.net is refactoring.,could u guide me how to include this authentication in the brand new asp.net vnext pipeline… Thanks in advance

    • May 28, 2015 9:04 am

      Once the ASP.NET 5 bits are settled down, we’ll do more posts on it.

      • Karthikeyan permalink
        June 2, 2015 3:33 am

        Thanks brock, Actually we(team) have migrated a project from vs2013 to vs2015 CTP 6, but we cant figure out, how to use the same in IApplicationBuilder in the configuration class. If you have any temporary solution, it will be helpful …

  27. August 18, 2015 5:14 am

    I’m curious tto find out what blog syste yoou happen tto be
    working with? I’m experiecing some small secjrity problems with
    my latest website and I’d like to fin something more safeguarded.
    Do you have any solutions?

  28. September 29, 2015 9:35 am

    Thank you for this article. I am still looking for a way to destroy the cookie when the user close the browser. can you help with this issue?

  29. November 8, 2015 4:51 am

    Any insight on sharing the authentication cookie across sub domains using a MVC project and a WebAPI project?

    I’ve tried everything and simply cannot get it working.
    I’ve tried MachineKeys, cookie-domain, startup-attributes, updating nuget packages etc. nothing seems to be working.

  30. January 9, 2016 12:49 pm

    Very nice article. Can you please refer me to the source code in .NET framework to where the Cookie Authentication Middleware is being invoked and where cookie is created? Also, where in the source code, the Cookie Authentication Middleware jumps in to check the cookie? I’ve been searching for this info without any luck. Thank you

    • January 12, 2016 4:22 pm

      The Kanata code is here: https://katanaproject.codeplex.com/

      • January 25, 2016 10:45 am

        Thanks a lot!

        I have a question please, I am trying to create a pluggable architecture by using Areas. I would then create a separate MVC Project for each Area (store it inside Areas folder of the main app & redirect the DLLs to the bin folder of the main App). How can I Authorize inside those Modules (sub projects) using the configuration of ASP.NET Identity in the main app?

  31. March 10, 2016 4:07 pm

    This works perfectly fine with the template Asp.net 4.5 template, but as soon as I create a project in MVC6 i do not get 2 references i.e. DefaultAuthenticationTypes and GetOwinContext()

    I found that DefaultAuthenticationTypes is part of “Microsoft.AspNet.Identity.Core”. If I install this package from Nuget – then I get many other conflicting error from the namespace Microsoft.AspNet.Identity, because many classes exists in both.

    again I tried installing “Microsoft.Owin.Host.SystemWeb, Version=3.0.1.0” to resolve the error for GetOwinContext, but still facing same issue.

    var id = new ClaimsIdentity(claims,
    DefaultAuthenticationTypes.ApplicationCookie);

    var ctx = Request.GetOwinContext();

    Is this feature supported in MVC6. If yes what am I missing. Please suggest, I am badly stuck.

    PS: I am not using default aspnet authentication because we are migrating an old .net project to MVC6 and all login/permission related tables are already in place, so we don’t want to go default aspnet authentication way.

    • March 17, 2016 10:44 am

      MVC 6 (aka MVC Core 1) is built on a new HTTP framework called ASP.NET Core 1 (aka ASP.NET 5) and it will all look different. There’s no more OWIN/Katana at the core.

  32. March 10, 2016 4:34 pm

    I am migrating an old .net web application to MVC6. The old code already has the database designed with roles/permissions and it is working fine, so I do not want to use default MVC6 authentication.

    I am trying to do owin implementation to store claims and use for authorization in controller actions. I followed this post for implementation,but I can’t get reference of DefaultAuthenticationTypes and GetOwinContext() from the below line.

    var claims = new List();

    claims.Add(new Claim(ClaimTypes.Name, “Brock”)); claims.Add(new Claim(ClaimTypes.Email, “brockallen@gmail.com”)); var id = new ClaimsIdentity(claims, DefaultAuthenticationTypes.ApplicationCookie); var ctx = Request.GetOwinContext(); var authenticationManager = ctx.Authentication; authenticationManager.SignIn(id);

    To get reference of DefaultAuthenticationTypes, I installed Microsoft.AspNet.Identity.core from Nuget, but this resulted in lot of other conflicting errors because many methods are matching with the methods of Microsoft.AspNet.Identity (which is by default referenced in project).

    Similarly I installed “Microsoft.Owin.Host.SystemWeb” for the reference of “GetOwinContext” but it is also not working.

    This code woks perfectly fine in MVC5. Please guide how I can solve this, I am badly stuck.

    • March 24, 2016 10:18 am

      MVC6 is not built on OWIN/Katana, so those APIs will not be available.

  33. March 29, 2016 7:55 am

    Hi Brock,
    Can I combine this OWIN authentication with Single-Sign-On (Windows Authentication)?
    If yes, would you mind pointing me in the right direction for primer or other reference material on how.

  34. srikat permalink
    July 1, 2016 1:47 am

    I have issue with deleting cookie

    I am adding cookie to IOWinContext

    owinContext.Response.Cookies.Append(“session”, “SomeValue”,new CookieOptions()
    {
    HttpOnly = true
    });

    During the cleanup I call
    owinContext.Response.Cookies.Delete(“session”);

    When the request comes back I see same cookie again. The owinContext.Request,Cookies is just dictionary of strings,

    Is there anyway to check if the cookie expired ?.
    .
    comes with dictionary

    • August 12, 2016 3:25 pm

      To delete a cookie you need to add it with an expiration in the past.

  35. Mark Baer permalink
    July 28, 2016 6:59 pm

    Brock, I’m trying to use your example here, but with the new Core…How does your code here change? Some of the options are missing like “AuthenticationType = DefaultAuthenticationTypes.ApplicationCookie”. Thanks, hope to join your 2 day seminar in Vegas in a few months…

  36. peter permalink
    September 21, 2016 11:39 am

    my app now is using asp.net identity for authentication & role for authorization. In order to SSO w/another partner, I need to trust their claim, while other users still use asp.net identity.
    my question, is it possible to still use role authorization for claim?

    Thx

    • October 14, 2016 7:50 pm

      Yes, but you need to design for that. IdentityServer is a useful framework for helping with that.

  37. Danny Scheelings permalink
    September 26, 2016 5:46 am

    Hi, I am developing a simple authentication webapp to test OWIN, but on my IIS8.5 the cookie authentication does not work after restarting IIS. Do you have any idea what the problem is?
    You can also take a look at my StackOverflow post: http://stackoverflow.com/questions/39661593/owin-cookie-authentication-not-working-on-iis-8-5
    Thx,
    Danny

  38. VINAE BIJEA permalink
    January 19, 2017 7:38 pm

    Superbly explained! Thanks.

  39. May 16, 2017 4:50 am

    Reblogged this on Nuwave eSolutions Development Team.

    • December 5, 2017 5:09 pm

      I just tried and the link works for me.

      • lewis permalink
        January 27, 2018 11:40 pm

        Hey Brock, awesome post from 5 years ago. Still relevant as ever!!!

Trackbacks

  1. Decaying Code | Community Update November 28th 2013 – Custom OAuth, WebAPI, and more
  2. A primer on external login providers (social logins) with OWIN/Katana authentication middleware | brockallen
  3. Hilfreiche Owin Links | Norbert Eder
  4. Decaying Code | Community Update 2014-05-06 – #backbonejs, #microsoftazure, #webapi, #elasticsearch
  5. Using OWIN Authentication Middleware WITH VS2012 And ASP.NET MVC-4 | Prerak Kaushik
  6. L’authentification WS-Federation avec Azure Windows Active Directory | Nouvelles Chroniques d'Amethyste
  7. How to use Identity in a .NET Web Application | Secure by Default
  8. Mint forms auth cookie using owin | Peter's ruminations
  9. La nueva era de la autentificación: Claims | itblogsogeti
  10. MVC5 – ASP.NET Identity登录原理 – Claims-based认证和OWIN [转载] | Engineer for life

Leave a reply to breakskater Cancel reply