如何从Jquery Ajax调用Web Api 2 Refresh Token

时间:2018-01-12 08:42:16

标签: c# jquery ajax

我正在使用具有个人用户帐户身份验证的MVC 5 Web Api 2。我已将访问令牌设置为10秒。

TokenEndpointPath = new PathString("/Token"),
Provider = new ApplicationOAuthProvider(PublicClientId),
AuthorizeEndpointPath = new PathString("/api/Account/ExternalLogin"),
AccessTokenExpireTimeSpan = TimeSpan.FromSeconds(10),
// In production mode set AllowInsecureHttp = false
AllowInsecureHttp = true,
RefreshTokenProvider = new SimpleRefreshTokenProvider()

我想调用jquery ajax来刷新令牌“/ Token, 到期后访问令牌enter image description here

$.ajax({
    url: '/token',
    method: 'POST',
    contentType:'application/json',
    data: {
        username: $('#txtUserName').val(),
        password: $('#txtPassword').val(),
        grant_type:'password'
    },
    success: function (response) {
        sessionStorage.setItem('accessToken', response.access_token);
        window.location.href = 'Data.html';
    }
}):

1 个答案:

答案 0 :(得分:1)

您需要在成功登录请求后保存返回的refresh_token以及access_token

success: function (response) {
  sessionStorage.setItem('accessToken', response.access_token);
  sessionStorage.setItem('refreshToken', response.refresh_token);
  window.location.href = 'Data.html';
}

然后,您可以使用此/token grant_type refresh_token来呼叫$.ajax({ url: '/token', method: 'POST', contentType:'application/json', data: { refresh_token: sessionStorage.getItem('refreshToken'), grant_type: 'refresh_token' }, success: function (response) { sessionStorage.setItem('accessToken', response.access_token); sessionStorage.setItem('refreshToken', response.refresh_token); window.location.href = 'Data.html'; } }): 。像这样:

localStorage

将刷新令牌存储在比会话更长寿的内容中更有意义,例如{{1}}或cookie。