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

£可爱£侵袭症+ 提交于 2019-12-03 00:51:22

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;

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
        };
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!