我有一个Web应用程序。我的要求是,我需要在每次登录时生成oauth2承载令牌。当前,我们正在使用thinktecture生成令牌,但是此过程每次花费将近7秒钟来生成令牌。不使用thinktecture,有什么方法可以生成令牌吗?
如果创建了新的ASP.NET Web Application
->用Web API
创建Individual User Accounts
。看看App_Start
-> Startup.Auth.cs
。
它应该包含这样的内容:
PublicClientId = "self";
OAuthOptions = new OAuthAuthorizationServerOptions
{
TokenEndpointPath = new PathString("/Token"),
Provider = new ApplicationOAuthProvider(PublicClientId),
AuthorizeEndpointPath = new PathString("/api/Account/ExternalLogin"),
AccessTokenExpireTimeSpan = TimeSpan.FromDays(14),
// In production mode set AllowInsecureHttp = false
AllowInsecureHttp = true
};
// Enable the application to use bearer tokens to authenticate users
app.UseOAuthBearerTokens(OAuthOptions);
这意味着您可以发送访问令牌请求,例如请求示例:
然后您可以验证访问令牌是否有效:
使用此令牌,您现在可以访问用户有权访问的所有受保护资源。
Asp.net 默认实现将使用DPAPI”,因此它将使用存储在machine.config文件中的machineKey节点中的“ validationKey”值来颁发访问令牌并对其进行保护。当您将访问令牌发送到资源服务器时,情况相同,它将使用相同的machineKey解密访问令牌并从中提取身份验证票证。
ASP.NET
如果要生成JWT编码的承载令牌,则应覆盖ISecureDataFormat<AuthenticationTicket>.Protect()
方法:
CustomJwtFormat.cs
string symmetricKeyAsBase64 = audience.Base64Secret;
var keyByteArray = TextEncodings.Base64Url.Decode(symmetricKeyAsBase64);
var signingKey = new HmacSigningCredentials(keyByteArray);
var issued = data.Properties.IssuedUtc; var expires = data.Properties.ExpiresUtc;
JwtSecurityToken token = new JwtSecurityToken(_issuer, audienceId, data.Identity.Claims, issued.Value.UtcDateTime,expires.Value.UtcDateTime, signingKey);
var handler = new JwtSecurityTokenHandler();
//serialize the JSON Web Token to a string
var jwt = handler.WriteToken(token);
return jwt;
将您的自定义JWT格式化程序添加到OAuth选项
OAuthAuthorizationServerOptions OAuthServerOptions = new
OAuthAuthorizationServerOptions()
{
//For Dev enviroment only (on production should be AllowInsecureHttp = false)
AllowInsecureHttp = true,
TokenEndpointPath = new PathString("/oauth/token"),
AccessTokenExpireTimeSpan = TimeSpan.FromMinutes(30),
AccessTokenFormat = new CustomJwtFormat("http://localhost:5001")
};
// Generation and validation
app.UseOAuthBearerTokens(OAuthServerOptions);
app.UseOAuthBearerTokens
helper方法创建令牌服务器和中间件,以验证同一应用程序中的请求令牌。
如果这是一个授权服务器(生成令牌),则应在最后一行中使用app.UseOAuthAuthorizationServer(OAuthServerOptions)
ASP.NET Core
很遗憾,ASP.NET团队只是决定不将OAuthAuthorizationServerMiddleware
移植到asp.net核心:https://github.com/aspnet/Security/issues/83
由社区提供的,ASP.NET Core的开源身份验证选项:
AspNet.Security.OpenIdConnect.Server:用于ASP.NET Core和OWIN / Katana的低级别,协议优先的OpenID Connect服务器框架。
IdentityServer:用于ASP.NET Core的OpenID Connect和OAuth 2.0框架,已由OpenID Foundation正式认证并在.NET Foundation的管理下。
OpenIddict:用于ASP.NET Core的易于使用的OpenID Connect服务器。
我关注以下文章http://bitoftech.net/2014/06/01/token-based-authentication-asp-net-web-api-2-owin-asp-net-identity/
下载了他们的源代码并进行了检查。他们有一个关于如何创建令牌的很好的例子。