在客户端实现JWT刷新令牌的通用方法

时间:2020-04-07 14:39:42

标签: vb.net asp.net-web-api bearer-token apiclient

我有WebApi生成JWT令牌以授予对控制器方法的访问权限。我希望在客户端上创建一个通用方法,该方法发送请求并检查令牌是否经过验证,而不是去刷新令牌,然后调用该方法

以下是我的客户端代码

    Public Function SendOrderNotification(ByVal orderNumber As String, ByVal sendingStoreID As String, ByVal receivingStoreID As String) As Boolean
        Try
            If String.IsNullOrEmpty(SMSAPIToken)
                SMSAPIToken = GetTokenFromSMSAPI()
            End If
            If String.IsNullOrEmpty(SMSAPIToken)
                Throw New Exception("Unauthorized: Invalid username password. Source : SMS Web API")
            End If
            Dim hwr As HttpWebRequest
            Dim endPoint As String = ConfigurationManager.AppSettings("SMSWebAPIURL")
            endPoint = endPoint + "orders/SendOrderNotification?orderNumber=" + orderNumber + "&senderStoreId=" + sendingStoreID + "&recipientStoreId=" + receivingStoreID
            hwr = WebRequest.Create(endPoint)
            hwr.Headers.Add("Authorization", "Bearer " + SMSAPIToken)
            hwr.Method = "POST"
            hwr.ContentLength = 0
            hwr.ContentType = "application/json"
            Dim wr As WebResponse
            wr = hwr.GetResponse()
            If Not CType(wr, HttpWebResponse).StatusCode = HttpStatusCode.Unauthorized Then

            End If
            If Not CType(wr, HttpWebResponse).StatusCode = HttpStatusCode.OK Then
                Return False
            End If
            Return True
        Catch ex As WebException
            If ex.Response.GetType() Is GetType(System.Net.HttpWebResponse)
                If DirectCast(ex.Response , HttpWebResponse).StatusCode = HttpStatusCode.Unauthorized
'I can call method here to get refresh token,but this is not the professional way
                End If
            End If
        Catch ex As Exception
            ErrorLog.Add(ex)
            Return False
        End Try
    End Function

API返回HttpStatusCode。令牌过期时未经授权。因此,我需要调用刷新令牌,这很简单,只需放入代码,然后再次调用SendOrderNotification方法。但是我正在寻找一种可以在所有客户端方法中使用的通用方法

0 个答案:

没有答案