NET Core 3.1 test project for Oauth2 with new IndentityModel 4.2
I use Oauth2 in many my project, for example see this my Articles Simplest VB.NET WebApi2 client for RESTful microServices documented by Swagger/OpenAPI., but in this page I have decided to publish a simplest and clearest as possible client for testing purposes. So, this is my common solution in Clean architecture.
Also I have been transformed this project to xUnit test and uploaded it as common project template for VS2019 My public project templates
1: Imports System
2: Imports System.Net.Http
3: Imports IdentityModel.Client
4: Imports Newtonsoft.Json.Linq
5: Imports Newtonsoft.Json
6: Imports System.Text
7: Imports System.Threading.Tasks
8:
9:
10: 'https://identitymodel.readthedocs.io/en/latest/client/token.html
11: Module Program
12: Public Sub Main(ByVal args As String())
13: MainAsync().GetAwaiter().GetResult()
14: End Sub
15:
16: Private Async Function MainAsync() As Task
17:
18: 'discover all the endpoints using metaData of identity server
19: Dim httpClient As HttpClient = New HttpClient()
20: Dim disco = Await httpClient.GetDiscoveryDocumentAsync("http://localhost:5000")
21:
22: If disco.IsError Then
23: Console.WriteLine(disco.[Error])
24: Return
25: End If
26:
27: 'Grab a bearer token
28:
29: 'by clear body Like
30: 'grant_type=client_credentials&scope=bankOfDotNetApi&client_id=Login1&client_secret=Password1
31: Dim ClearBody = New ClientCredentialsTokenRequest With
32: {
33: .Address = disco.TokenEndpoint,
34: .ClientId = "Login1",
35: .ClientSecret = "Password1",
36: .Scope = "bankOfDotNetApi" '"CryptoChestNew.Microservices"
37: }
38: Dim tokenResponse = Await httpClient.RequestClientCredentialsTokenAsync(ClearBody)
39:
40:
41: 'by hashCode in header as Basic AU
42: 'Authorization: Basic TG9naW4xOlBhc3N3b3JkMQ==
43: Dim NoBody = New ClientCredentialsTokenRequest With
44: {
45: .Address = disco.TokenEndpoint,
46: .AuthorizationHeaderStyle = BasicAuthenticationHeaderStyle.Rfc6749,
47: .Scope = "bankOfDotNetApi" '"CryptoChestNew.Microservices"
48: }
49:
50: httpClient.SetBasicAuthenticationOAuth(ClearBody.ClientId, ClearBody.ClientSecret)
51: tokenResponse = Await httpClient.RequestClientCredentialsTokenAsync(NoBody)
52:
53: If tokenResponse.IsError Then
54: Console.WriteLine(tokenResponse.[Error])
55: Return
56: End If
57:
58: Console.WriteLine(tokenResponse.Json)
59: Console.WriteLine(vbLf & vbLf)
60: Dim client = New HttpClient()
61:
62: client.SetBearerToken(tokenResponse.AccessToken)
63:
64:
65: Dim newCustomerInfo = New StringContent(
66: JsonConvert.SerializeObject(
67: New With {.Id = 10, .FirstName = "Viacheslav", .LastName = "Eremin"}),
68: Encoding.UTF8, "application/json")
69:
70: Dim createCustomerResponse = Await client.PostAsync("http://localhost:59337/api/customers", newCustomerInfo)
71:
72: Dim getCustomerResponse = Await client.GetAsync("http://localhost:59337/api/customers")
73:
74: If Not getCustomerResponse.IsSuccessStatusCode Then
75: Console.WriteLine(getCustomerResponse.StatusCode)
76: Else
77: Dim content = Await getCustomerResponse.Content.ReadAsStringAsync()
78: Console.WriteLine(JArray.Parse(content))
79: End If
80:
81: Console.Read()
82: End Function
83:
84: End Module
For debugging usually I perform Fiddler, not Postman, because Fiddler more clear and upload less information from my computer to cloud. In fact, Postman spy for me and upload each my request to unknown servers.
Fiddler has more clear and raw composer and upload to unknown only common information about each new perform. Below you can see sequence of request to testing Oauth2 AU.
- First disco request http://localhost:5000/.well-known/openid-configuration HTTP/1.1
- Then in this request http://localhost:5000/.well-known/openid-configuration/jwks HTTP/1.1 client receive JWT AU Token for anonymous access
- If client set BasicAU and password in header like this Authorization: Basic TG9naW4xOlBhc3N3b3JkMQ==, client receive JWT token to NonAnonymous access. And any next request client need to send with heaader like this Authorization: Bearer xxx.yyy.zzz
If you don't understanding what is disco services, please read my ancient article from 2011 year SOAP/WSDL vs XML data exchange. and maybe you will be interesting to see a lot my posts about distributed communication ???????????? ???? ???????????????????? ?????????????????????? ???????????????????? ?????????????? JSON ???? XML. And pay attention so far SOAP/WSDL is just only one standard specification of microservices. In reality this is most spread type of project, I used it in a lot of my projects ?????????????? SOAP/WSDL ????????????. since 2008 year.
Modern specification of microservices is REST API. For example, in the screen below I have installed to this tests project most popular REST API tool SwaggerUI and examine API. In the screen below that microservices is protect by ASP.NET Core Oauth2 server.
|