Search code examples
vb.netopenid-connectidentitymodel

Using IdentityModel in VB.NET for OpenID Connect Authentication


I am creating an application in VB.NET 4.7.2 with Visual Studio 2019. The user must authenticate himself with OpenID Connect.

I already downloaded the IdentityModel Package with the NuGet Package Manager and tried to code the authentication method.

Before First Step: Import libraries

Imports System.Net
Imports IdentityModel.Client
Imports System.Threading.Tasks

First Step: Token Request Data

Function Get_Token As String()

Dim request As TokenRequest = New TokenRequest
request.Address = "https://demo.identityserver.io/connect/token"
request.GrantType = "custom"
request.ClientId = "ClientID"
request.Parameters.Add("parameter1", "value1")
request.Parameters.Add("parameter2", "value2") 

Second Step: Call an asynchronous function for the request for the token. I must use an asynchronous function, because the response of the function RequestTokenAsync has Task(Of TokenResponse) as type. My problem here: Is this the right way? How do I call the async. function, so that the return variable response can be evaluated in the calling function?

Call AsyncCall(request)

The asynchronous function: Does not work and gives the error NullReferenceException

Async Function AsyncCall(rqst As TokenRequest) As Task(Of TokenResponse)
Dim client As Http.HttpClient = New Http.HttpClient()
Dim response As TokenResponse = Await client.RequestTokenAsync(rqst)
Return response
End Function

The asynchronous function returns the variable response to the function Get_Token and the variable is evaluated further:

Third Step: Evaluation of response Even though the asynchronous function had "Return response" in order to return the variable response to the calling function, the calling function does not recognize response, how can I return the variable response properly?

Get_Token = response.AccessToken
End Function

Can you please help me, or show me any direction?


Solution

  • The IdentityModel coding model changed a while back as follows:

    • Don't use TokenClient - use HttpClient instead
    • Use the RequestTokenAsync extension method --> You are doing this already
    • Also use the TokenRequest object --> You are doing this already

    Here is the expected usage