HttpWebRequest JSON request returning 401 Unauthorised


Sep 16, 2010
Programming Experience

I'm trying to post a JSON request to a web service. I've attached the code I'm using below, as it currently stands. It's returning a 401 - Unauthorised error from the server.

uri = the path to the service in Uri format
jsonDataBytes = the JSON request serialised into a byte array
APISecretKey = the key used to create the security token
APIHost = the site hosting the web service
APIAppID = part of my login credential, defined by the web service
APIAppName = part of my login credential, defined by the web service
I've double and triple checked these over and over to make absolutely sure none of them are wrong but they definitely aren't...

Any ideas what might be going wrong here? I've been thrashing around and googling around it for a long time, without much success. The company's tech support is shut for the holiday which doesn't help...


    Private Function SendRequest(uri As Uri, jsonDataBytes As Byte()) As String

        Dim request As HttpWebRequest
        request = WebRequest.Create(uri)
        request.ContentLength = jsonDataBytes.Length
        request.ContentType = "application/json"
        request.Method = "POST"

        request.Host = APIHost
        request.Headers.Add("Authorization", "Bearer " + CreateToken(APISecretKey, APIHost, APIAppID, APIAppName))
        request.Headers.Add("X-APP-ID", APIAppID)
        request.PreAuthenticate = True

        Dim response As String
        Using requestStream = request.GetRequestStream
            requestStream.Write(jsonDataBytes, 0, jsonDataBytes.Length)

            Using responseStream = request.GetResponse.GetResponseStream
                Using reader As New StreamReader(responseStream)
                    response = reader.ReadToEnd()
                End Using
            End Using
        End Using

        Return response

    End Function

    Private Function CreateToken(ByVal secretKey As String, ByVal host As String, ByVal appID As String, ByVal appName As String) As String

        Dim securityKey = New SymmetricSecurityKey(Encoding.UTF8.GetBytes(secretKey))
        Dim credentials = New SigningCredentials(securityKey, SecurityAlgorithms.HmacSha256Signature) 'SecurityAlgorithms.HmacSha256
        Dim header = New JwtHeader(credentials)

        Dim payload = New JwtPayload From {
            {"host", host},
            {"app_id", appID},
            {"secret_key", secretKey},
            {"app_name", appName}

        Dim secToken = New JwtSecurityToken(header, payload)
        Dim handler = New JwtSecurityTokenHandler()
        Dim tokenString = handler.WriteToken(secToken)
        Dim token = handler.ReadJwtToken(tokenString)
        Return New JwtSecurityTokenHandler().WriteToken(token)

    End Function
Last edited by a moderator:
Top Bottom