app.UseOAuthBearerTokens with ASP.NET Identity 2.0's DbContext middleware?

12,078

Solution 1

If you are looking how to implement Bearer tokens for WEBAPI and MVC Cookie authentication then check out this article:

ASP.NET Identity 2.0 Cookie & Token Authentication including a sample project.

Simply put, this solution uses the OWIN Middleware components UseOAuthBearerAuthentication and UseCookieAuthentication (I know Cookie auth is not part of the question but very relevant regarding MVC projects) to support browser based authentication and WEBAPI request authentication via Cookies and Tokens, respectively.

Startup.Auth.cs

OAuthBearerOptions = new OAuthBearerAuthenticationOptions();

//This will used the HTTP header: "Authorization" Value: "Bearer 1234123412341234asdfasdfasdfasdf"
app.UseOAuthBearerAuthentication(OAuthBearerOptions);
// Enable the application to use a cookie to store information for the signed in user
app.UseCookieAuthentication(new CookieAuthenticationOptions
{
    AuthenticationType = DefaultAuthenticationTypes.ApplicationCookie,
    LoginPath = new PathString("/Account/Login")
}); 

HostAuthenticationFilter represents an authentication filter that authenticates via OWIN middleware:

WebApiConfig.cs

config.SuppressDefaultHostAuthentication();
//This will used the HTTP header: "Authorization" Value: "Bearer 1234123412341234asdfasdfasdfasdf"
config.Filters.Add(new HostAuthenticationFilter("Bearer"));

To Generate a Token:

var identity = new ClaimsIdentity(Startup.OAuthBearerOptions.AuthenticationType);
identity.AddClaim(new Claim(ClaimTypes.Name, user));
identity.AddClaim(new Claim(ClaimTypes.NameIdentifier, userIdentity.Id));
AuthenticationTicket ticket = new AuthenticationTicket(identity, new AuthenticationProperties());
var currentUtc = new SystemClock().UtcNow;
ticket.Properties.IssuedUtc = currentUtc;
ticket.Properties.ExpiresUtc = currentUtc.Add(TimeSpan.FromMinutes(30));
string AccessToken = Startup.OAuthBearerOptions.AccessTokenFormat.Protect(ticket);
return AccessToken;

Solution 2

The following is just the code from the SPA template with the provider for UserManager replaced with the stuff introduced in 2.0 Identity.

OAuthOptions = new OAuthAuthorizationServerOptions
            {
                TokenEndpointPath = new PathString("/Token"),
                Provider = new ApplicationOAuthProvider(PublicClientId, () => HttpContext.Current.GetOwinContext().Get<ApplicationUserManager>()),
                AuthorizeEndpointPath = new PathString("/api/Account/ExternalLogin"),
                AccessTokenExpireTimeSpan = TimeSpan.FromDays(14),
                AllowInsecureHttp = false
            };

Here is also a Generic ApplicationOauthProvider you can use: https://gist.github.com/s093294/9076631 (due note I haven't tested it and just put it together for you)

Example if you have:

app.CreatePerOwinContext<ApplicationUserManager>(ApplicationUserManager.Create);

you can do

        OAuthOptions = new OAuthAuthorizationServerOptions
        {
            TokenEndpointPath = new PathString("/Token"),
            Provider = new ApplicationOAuthProvider<ApplicationUserManager,ApplicationUser,Guid>(PublicClientId),
            AuthorizeEndpointPath = new PathString("/api/Account/ExternalLogin"),
            AccessTokenExpireTimeSpan = TimeSpan.FromDays(14),
            AllowInsecureHttp = false
        };
Share:
12,078
BenjiFB
Author by

BenjiFB

Updated on June 05, 2022

Comments

  • BenjiFB
    BenjiFB over 1 year

    Edit: After progressing, I can narrow the scope of the question:

    What changes should be made to startup.auth.cs and ApplicationOAuthProvider.cs in the VS2013 SPA template (using ASP.NET identity 1.0) in order to migrate it to use ASP.NET identity 2.0?

    Edit 2: I've simplified this question even further. How can one use app.UseOAuthBearerTokens with ASP.NET Identity 2.0's middleware for retrieving the DbContext?

            app.UseOAuthBearerTokens(new Microsoft.Owin.Security.OAuth.OAuthAuthorizationServerOptions()
                {
                    //What goes here??
                });
    

    (There's no example of this in the sample that's available.)

    There are significant differences from V1.0 to V2.0alpha of the Asp.net identity framework. There is an example available that shows how to use V2:

    https://aspnet.codeplex.com/SourceControl/latest (see Samples->Identity->ChangePK)

    but that example is not MVC, or SPA. That being said, I've got an app that was built from the VS2013 ASP.NET SPA app (which incorporates Identity 1.0). I've been trying to implement the code in the sample inside my MVC app, but it's unclear to me what code from the VS2013 SPA template is removed in favor of the code from the sample.

    Asked another way, does anyone have guidance for implementing ASP.NET identity 2.0 alpha inside an ASP.NET MVC app? (Ideally with steps to migrate from the VS2013 MVC SPA template which leverages identity 1.0)