具有刷新令牌的ASP.NET个人帐户

时间:2014-04-21 02:37:37

标签: asp.net security authentication asp.net-web-api owin

我试图保护我的ASP.NET web api using OWIN and ASP.NET identity,我设法完成了它。但是我将访问令牌保存在客户端的本地存储(移动)中,这违背了访问令牌的目的。所以我必须添加刷新令牌。我设法使用访问令牌的相同票证生成刷新令牌。但现在我不知道如何在客户端使用刷新令牌。

Startup.cs

   OAuthOptions = new OAuthAuthorizationServerOptions
        {
            TokenEndpointPath = new PathString("/Token"),
            Provider = new ApplicationOAuthProvider(PublicClientId, UserManagerFactory),
            AuthorizeEndpointPath = new PathString("/api/Account/ExternalLogin"),
            AccessTokenExpireTimeSpan = TimeSpan.FromMinutes(tokenExpiry),
            AllowInsecureHttp = true,
            RefreshTokenProvider = new AuthenticationTokenProvider
            {
                OnCreate = CreateRefreshToken,
                OnReceive = ReceiveRefreshToken,
            }
        };

     private static void CreateRefreshToken(AuthenticationTokenCreateContext context)
        {
            context.SetToken(context.SerializeTicket());
        }

        private static void ReceiveRefreshToken(AuthenticationTokenReceiveContext context)
        {
            context.DeserializeTicket(context.Token);
        }

AccountController.cs

 private JObject GenerateApiToken(IdentityUser user, TimeSpan tokenExpirationTimeSpan, string provider)
        {
            var identity = new ClaimsIdentity(Startup.OAuthOptions.AuthenticationType);

            identity.AddClaim(new Claim(ClaimTypes.Name, user.Id, null, provider));
            identity.AddClaim(new Claim(ClaimTypes.NameIdentifier, user.Id, null, "LOCAL_AUTHORITY"));



    var ticket = new AuthenticationTicket(identity, new AuthenticationProperties());
        var currentUtc = new Microsoft.Owin.Infrastructure.SystemClock().UtcNow;
        ticket.Properties.IssuedUtc = currentUtc;
        ticket.Properties.ExpiresUtc = currentUtc.Add(tokenExpirationTimeSpan);
        var accesstoken = Startup.OAuthOptions.AccessTokenFormat.Protect(ticket);
        var refreshtoken = Startup.OAuthOptions.RefreshTokenFormat.Protect(ticket);
        Authentication.SignIn(identity);

        // Create the response
        JObject blob = new JObject(
            new JProperty("userName", user.UserName),
            new JProperty("access_token", accesstoken),
            new JProperty("refresh_token", refreshtoken),
            new JProperty("token_type", "bearer"),
            new JProperty("expires_in", tokenExpirationTimeSpan.TotalSeconds.ToString()),
            new JProperty(".issued", ticket.Properties.IssuedUtc.ToString()),
            new JProperty(".expires", ticket.Properties.ExpiresUtc.ToString())
            );
        var json = Newtonsoft.Json.JsonConvert.SerializeObject(blob);
        return blob;
    }

客户请求承载令牌

 $.ajax({type: 'POST',
                        url: tokenUrl + "Token",
                        data: "grant_type=password&username=" + identity.userName + "&password=" + identity.password,
                        contentType: 'application/x-www-form-urlencoded',
                    }).
                    done(function(response) {

                        app.tokenManager.saveToken(response.access_token, response.refresh_token, response.expires_in, apiTokenType.BASIC);

                        deferred.resolve({
                            token: response.access_token
                        });
                    })
                    .fail(function(result, status) {
                        deferred.reject(result);
                    });

现在,我如何使用刷新令牌?

1 个答案:

答案 0 :(得分:2)

根据aouth2规范 http://tools.ietf.org/html/rfc6749#section-6

POST /token HTTP/1.1
Host: server.example.com
Authorization: Bearer czZCaGRSa3F0MzpnWDFmQmF0M2JW
Content-Type: application/x-www-form-urlencoded

grant_type=refresh_token&refresh_token=tGzv3JOkF0XG5Qx2TlKWIA