c# - 在 Controller 中生成 token

标签 c# asp.net-web-api asp.net-identity

我使用 Owin 和 ASP.NET Identity 来使用 OAuth token 来保护我的 Web API 方法。 token 子系统设置如下:

var oauthOptions = new OAuthAuthorizationServerOptions()
{
    TokenEndpointPath = new PathString("/Token"),
    Provider = new SimpleAuthorizationServerProvider(),
    AccessTokenFormat = new TicketDataFormat(app.CreateDataProtector(typeof(OAuthAuthorizationServerMiddleware).Namespace, "Access_Token", "v1")),
    RefreshTokenFormat = new TicketDataFormat(app.CreateDataProtector(typeof(OAuthAuthorizationServerMiddleware).Namespace, "Refresh_Token", "v1")),
    AccessTokenProvider = new AuthenticationTokenProvider(),
    RefreshTokenProvider = new AuthenticationTokenProvider(),
    AccessTokenExpireTimeSpan = TimeSpan.FromDays(14),
    AllowInsecureHttp = true
};

app.UseOAuthAuthorizationServer(oauthOptions);
app.UseOAuthBearerAuthentication(new OAuthBearerAuthenticationOptions());

它非常适合根据用户名/密码请求 token ,然后使用这些 token 。但是,由于用户在点击呈现 SPA 的 Controller 时已经通过身份验证,因此我想在我的 View 中生成 token 并将其传递给 Javascript 代码,而不必在 SPA 中再次登录。

所以我的问题是:如何手动生成我的 token 以便将其包含在我的 SPA View 中?

最佳答案

您可以通过调用 OAuthBearerOptions.AccessTokenFormat.Protect(ticket) 在 Controller 内生成访问 token ,代码如下所示:

       private JObject GenerateLocalAccessTokenResponse(string userName)
    {

        var tokenExpiration = TimeSpan.FromDays(1);

        ClaimsIdentity identity = new ClaimsIdentity(OAuthDefaults.AuthenticationType);

        identity.AddClaim(new Claim(ClaimTypes.Name, userName));

        var props = new AuthenticationProperties()
        {
            IssuedUtc = DateTime.UtcNow,
            ExpiresUtc = DateTime.UtcNow.Add(tokenExpiration),
        };

        var ticket = new AuthenticationTicket(identity, props);

        var accessToken = Startup.OAuthBearerOptions.AccessTokenFormat.Protect(ticket);

        JObject tokenResponse = new JObject(
                                    new JProperty("userName", userName),
                                    new JProperty("access_token", accessToken),
                                    new JProperty("token_type", "bearer"),
                                    new JProperty("expires_in", tokenExpiration.TotalSeconds.ToString()),
                                    new JProperty(".issued", ticket.Properties.IssuedUtc.ToString()),
                                    new JProperty(".expires", ticket.Properties.ExpiresUtc.ToString())
    );

        return tokenResponse;
    }

并且您需要在 Startup.cs 类中将 OAuthBearerOptions 声明为 static 属性

但是,如果您希望在不请求用户再次登录的情况下实现访问 token 的静默刷新,那么您应该考虑实现刷新 token 授权,不要按照您建议的方式进行。你可以看我的详细blog post关于如何在使用 AngularJS 构建的 SPA 中生成刷新 token 。

希望这能回答您的问题。

关于c# - 在 Controller 中生成 token ,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/26969817/

相关文章:

c# - 如何让服务器在客户端连接到它时立即打印通知?

c# - oAuth 2.0 API 使用 C#

c# - LINQ 错误 : "<object> has no parameterless constructor."

c# - OnPaint 在调整大小时留下痕迹

c# - Asp.net WebAPI 启用对特定 SSL/https 源的 Cors

ASP.NET Core 身份 - UserManager 和 UserStore 问题

asp.net-identity - 交易/Database.BeginTransaction 和 IdentityManager

c# - 具有 2FA : List of Trusted Browsers 的 Asp.Net 身份

c# - 在 Silverlight 中重用自定义样式

performance - WebAPI 在同一台服务器上,即使在其上应用了 SSL,也可以通过 http 而不是 https 访问它吗?