在生成令牌控制器 [英] Generate token in controller

查看:134
本文介绍了在生成令牌控制器的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我使用Owin和ASP.NET的身份来使用OAuth令牌保护我的Web API方法。令牌子系统设置为这样的:

I'm using Owin and ASP.NET Identity to use OAuth tokens for securing my Web API methods. The token subsystem is set up as such:

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());

它的伟大工程,请求基于用户名/密码令牌,然后消耗这些令牌。然而,由于撞击呈现的SPA控制器,当用户已经通过身份验证,我想生成在我看来令牌并把它传递给Javascript code,而不必在SPA再次登录。

It works great for requesting tokens based on username/password and then consuming those tokens. However, since the user is already authenticated when hitting the controller that renders the SPA, I would like to generate the token in my view and pass it on to the Javascript code, instead of having to log in again in the SPA.

所以我的问题是:我怎么手动生成令牌我,所以我可以将其包含在我的SPA视图

So my question is: how do I manually generate my token so I can include it in my SPA view?

推荐答案

您可以通过调用生成控制器内部的访问令牌 OAuthBearerOptions.AccessTokenFormat.Protect(门票)和code看起来为如下:

You can generate access token inside a controller by calling OAuthBearerOptions.AccessTokenFormat.Protect(ticket) and the code will look as the below:

       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;
    }

和需要声明您 OAuthBearerOptions 静态类物业Startup.cs

And you need to declare you OAuthBearerOptions as static property in class Startup.cs

但是,如果你正在寻找实现对访问令牌沉默不刷新要求用户重新登录,那么你应该考虑实现刷新令牌授予,不这样做喜欢的方式你的建议。你可以阅读我的​​详细<一个href=\"http://bitoftech.net/2014/07/16/enable-oauth-refresh-tokens-angularjs-app-using-asp-net-web-api-2-owin/\">blog帖子如何产生的SPA刷新令牌与AngularJS建造的。

But if you are looking to implement silent refresh for access token without requesting the user to login again, then you should consider implementing refresh token grant, do not do it like the way you suggested. You can read my detailed blog post on how to generate refresh tokens in SPA built with AngularJS.

希望这回答了你的问题。

Hope this answers your question.

这篇关于在生成令牌控制器的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆