When we want to configure the identity server, we can start from the quickstart template and make the changes there. This quickstart provides all the interactions that we need, and sometimes more then we need. But we need to inject our data and this usually comes from the database.
You can get the quickstart from the following link “quickstart” and added it to your project.
For this article i downloaded the full IdentityServer4 solution and i run the rebuild script found inside of the folder. In this solution there is a copy of the quickstart in the Host project.
In the Host project under the Account Controller you can see that the IClientStore is used to get the registered clients (or to check the client against the store).The IClientStore has a default implementation in IS4 and that is an InMemoryClientStore. This gets test data that is used by the QuickStart.
We can replace this method with another extension method that IS4 provides :
The IClientStore has only one method and it’s responsability is to get the client from the repository:
C. The client project
To test our api we defined another web api project.
As you can see, I added the Authentication and JwtBearer dependencies. This has some built-in functionality out of the box.
To protect our api we need to use the Authorize attribute and describe the schema:
And now in the start up file of our consuming client, we need to specify that we want t0 authorize our application using the JwtBearer scheme (Client Credentials flow). Here you can see that we will provide the audience “api1” (the api resource this belongs to) and the authority (the IdentityServer EndPoint)
If you see the properties of our identity server, you can see that the local uri it uses it’s the authority we passed in the consuming app:
D. Testing using a console app
In this part, we will try to access the api of our consuming app, that is protected using oauth2. From the console app we need to
- get the token end point location from the identity server uri
- exchange the client id and secret for a token from the Identity Server Token Endpoint
- send a request to our consuming api with the bearer token as the Authorization Header
We can make all the requests manually using the HttpClient and adding headers and body as needed, or we can use another handy package called IdentityModel (which does this for us)
I have written all the above steps in one method, it’s pretty easy to follow and I will not describe it more then the code does: