使用API​​访问令牌oauth 2.0 -error“远程服务器返回错误:(401)未经授权”

时间:2017-01-07 04:08:30

标签: asp.net api token jwt access

我已多次尝试过,但仍然出现错误

  

远程服务器返回'错误:(401)未经授权

请向我建议,我真的很感激。

Public Class iFormAPIMethods

'iFormBuilder API info
Private API_ClientKey As String = "xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx"
Private API_ClientSecret As String = "xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx"
Private BaseURL As String = "app.iformbuilder.com"
Private FullURL As String = "https://" & BaseURL & "/exzact/api/v60/token"

'Quotation Mark Character for substitution

Private q As Char = Chr(34)

'JWT Claim Set Parameters
Property iss As String = API_ClientKey
Property aud As String = FullURL
Property AccessToken As String

Public Sub New()

End Sub

Public Sub GetAccessToken()

    ServicePointManager.Expect100Continue = True
    'ServicePointManager.SecurityProtocol = SecurityProtocolType.Ssl3
    ServicePointManager.SecurityProtocol = SecurityProtocolType.Tls12
    'Build web request
    Dim uriAddress As New Uri(FullURL)
    Dim wRequest As HttpWebRequest = DirectCast(HttpWebRequest.Create(uriAddress), HttpWebRequest)
    Dim strPostData As String = ""
    Dim bytPostData As Byte()
    Dim stJWT As String

    'Get JWT
    stJWT = CreateJWT()

    'Post Data ---

    strPostData = "grant_type=urn%3Aietf%3Aparams%3Aoauth%3Agrant-type%3Ajwt-bearer&assertion=" & stJWT

    'Post Data --- to byte()
    bytPostData = Encoding.UTF8.GetBytes(strPostData.ToString)

    'Set Web Request Properties

    With wRequest

        .Method = "POST"

        .ContentType = "application/x-www-form-urlencoded"

        .ContentLength = bytPostData.Length

    End With

    'Post Request and Get Response
    Using postStream As Stream = wRequest.GetRequestStream()

        postStream.Write(bytPostData, 0, bytPostData.Length)

        Dim rawResponseFromServer = ""

        Try
            Using response As HttpWebResponse = wRequest.GetResponse()
                Dim reader As New StreamReader(response.GetResponseStream())
                rawResponseFromServer = reader.ReadToEnd()
                Dim o As JObject = JObject.Parse(rawResponseFromServer)
                Me.AccessToken = o.Item("access_token").Value(Of String)()
            End Using
        Catch wex As WebException
            If Not wex.Response Is Nothing Then
                MsgBox(wex.Message)
                Debug.WriteLine("Resulting Error --- " & wex.Message & vbNewLine & wex.StackTrace)
            End If
            Exit Sub
        End Try

    End Using

End Sub

区域“HelperFunctions”

Private Function CreateJWT() As String

    Dim JWT As String
    Dim EncodedJWT As Byte()

    'Build Header and Claim Set String

    Dim strHeader As String = Strings.Replace("{'alg':'HS256','typ':'JWT'}", "'", q)

    'Dim strClaimSet As String = Strings.Replace("{'iss':'" & iss & "', 'aud':'" & aud & "', 'exp':" & exp() & ", 'iat':" & iat() & "}", "'", q)

    'Build JWT String
    JWT = ToBase64URL(strHeader) & "." & ToBase64URL(strClaimSet)

    'Convert Client Secret to UTF8 Byte()

    Dim bytKey As Byte() = System.Text.Encoding.UTF8.GetBytes(API_ClientSecret)

    'Encode JWT String
    Dim hmac_encode As HMACSHA256 = New HMACSHA256(bytKey)
    EncodedJWT = hmac_encode.ComputeHash(System.Text.Encoding.UTF8.GetBytes(JWT))

    'Sign and return JWT

    Dim signature As String = ToBase64URL(EncodedJWT)
    Return JWT & "." & signature

End Function

Private Function ToBase64URL(Text As String) As String

    Dim b As Byte() = System.Text.Encoding.UTF8.GetBytes(Text)
    Return ToBase64URL(b)

End Function

Private Function ToBase64URL(byt As Byte()) As String

    Dim result As String

    'Convert to base 64 string
    result = Convert.ToBase64String(byt)

    'Make URL Friendly
    result = result.Replace("+", "-").Replace("/", "_")

    Do While result.Chars(result.Length - 1) = "="

        result = Strings.Left(result, result.Length - 1)

    Loop

    Return result

End Function

Public ReadOnly Property exp(ExpirationSeconds As Integer) As Long

    Get
        Dim iats As Long
        iats = iat() + ExpirationSeconds
        Return iats
    End Get

End Property

Public ReadOnly Property iat() As Long

    Get
        Dim StartDate As Date = CDate("09/01/2016")
        Dim EndDate As Date = CDate(Now.ToUniversalTime)
        Dim val As Long = DateDiff(DateInterval.Second, StartDate, EndDate)
        Return val
    End Get

End Property

结束地区

结束班

1 个答案:

答案 0 :(得分:0)

您的代码与我使用的代码相同。

要获取令牌,您不需要引用API版本,因此更正后的行应为:

Private FullURL As String = "https://" & BaseURL & "/exzact/api/token"

希望这有帮助。

RJ