【问题标题】:Generate bearer token using c#使用 c# 生成不记名令牌
【发布时间】:2020-03-27 01:59:14
【问题描述】:

我有一个网络应用程序。我的要求是我需要在每次登录时生成 oauth2 不记名令牌。目前我们正在使用thinktecture生成token,但是这个过程每次生成token需要将近7秒。有什么方法可以在不使用 thinktecture 的情况下生成令牌?

【问题讨论】:

    标签: c# authentication oauth-2.0 bearer-token


    【解决方案1】:

    如果您创建了一个新的ASP.NET Web Application -> Web APIIndividual 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);
    

    这意味着你可以发送一个访问令牌的请求,例如请求:

    然后您可以验证访问令牌是否有效:

    使用此令牌,您现在可以访问用户有权访问的所有受保护资源。

    【讨论】:

      【解决方案2】:

      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 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 基金会正式认证并由 .NET 基金会管理。

      OpenIddict:用于 ASP.NET Core 的易于使用的 OpenID Connect 服务器。

      【讨论】:

        【解决方案3】:

        我关注了下面的文章http://bitoftech.net/2014/06/01/token-based-authentication-asp-net-web-api-2-owin-asp-net-identity/

        下载了他们的源代码并进行了检查。他们有如何创建令牌的好例子。

        【讨论】:

        • 请不要只发布解决方案的 URL,而是在您的答案中描述它。该 URL 可能会过时,而您的答案不再有价值。
        猜你喜欢
        • 2017-10-06
        • 1970-01-01
        • 2020-11-15
        • 2015-11-30
        • 1970-01-01
        • 2019-08-11
        • 2014-10-08
        • 1970-01-01
        • 2022-01-19
        相关资源
        最近更新 更多