我有一个网络应用程序。我的要求是我需要在每次登录时生成 oauth2 不记名令牌。目前我们正在使用thinktecture生成token,但是这个过程每次生成token需要将近7秒。有什么方法可以在不使用 thinktecture 的情况下生成令牌?
3 回答
Asp.net默认实现将在您的授权服务器中使用 DPAPI,因此它将使用存储在 machine.config 文件中的 machineKey 节点中的“validationKey”值来颁发访问令牌并保护它。当您将访问令牌发送到您的资源服务器时,同样的情况也适用,它将使用相同的 machineKey 来解密访问令牌并从中提取身份验证票证。
ASP.NET
如果要生成 JWT 编码的 Bearer Token,则应覆盖ISecureDataFormat<AuthenticationTicket>.Protect()
Method:
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 方法创建令牌服务器和中间件来验证同一应用程序中请求的令牌。
如果这是一个 Authorization server(generate token) ,你应该app.UseOAuthAuthorizationServer(OAuthServerOptions)
在最后一行使用
ASP.NET 核心
不幸的是,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 基金会正式认证并由 .NET 基金会管理。
OpenIddict:用于 ASP.NET Core 的易于使用的 OpenID Connect 服务器。
如果你创建了一个新的ASP.NET Web Application
-> Web API
with 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);
这意味着您可以发送访问令牌的请求,例如请求:
然后,您可以验证访问令牌是否有效:
使用此令牌,您现在可以访问用户有权访问的所有受保护资源。
我关注了下面的文章http://bitoftech.net/2014/06/01/token-based-authentication-asp-net-web-api-2-owin-asp-net-identity/
下载他们的源代码并检查它。他们有关于如何创建令牌的好例子。