[英]Generate bearer token using c#
我有一個網絡應用程序。 我的要求是我需要在每次登錄時生成 oauth2 不記名令牌。 目前我們使用thinktecture來生成token,但是這個過程每次生成token都需要將近7秒的時間。 有什么方法可以不使用 thinktecture 生成令牌?
如果您創建了一個新的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);
這意味着您可以發送訪問令牌請求,示例請求:
然后,您可以驗證訪問令牌是否有效:
使用此令牌,您現在可以訪問用戶有權訪問的所有受保護資源。
Asp.net默認實現將在您的授權服務器中使用 DPAPI ,因此它將使用存儲在 machine.config 文件中的 machineKey 節點中的“validationKey”值來發布訪問令牌並保護它。 當您將訪問令牌發送到資源服務器時,同樣的情況適用,它將使用相同的 machineKey 來解密訪問令牌並從中提取身份驗證票。
ASP.NET
如果要生成 JWT 編碼的 Bearer Token ,則應覆蓋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
輔助方法創建令牌服務器和中間件,以驗證同一應用程序中請求的令牌。
如果這是一個授權服務器(生成令牌),你應該在最后一行使用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 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/
下載了他們的源代碼並檢查了它。 他們有關於如何創建令牌的好例子。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.