in this post I would like to show you the most simple example about Token Authentication with Asp.Net WebAPI.
The sense behind this is:
- We ask the Server for a token
- We receive the token, store it client side and…
- …send it in the header on every request
The “problem” is that we do want to use all build in things Asp.Net WebAPI provides us. Microsoft serves us everything we need. So lets do this
First of all we configure our WebAPI to create a “controller” which is taking our requests. Here is the first unusual thing: The controller we create is kind of a virtual controller. We only provide it as a string.
The “TokenEndpointPath” can be treated like a controller without really having one in your project. You will not find such a class there, so stop looking Other Properties speak for themselves. Well, now we have to take a look at the ApplicationOAuthProvider, we mentioned in the code, because this is a class which consumes the token request and gives us the token in the end.
Lets have a look at this.
ATTENTION: I am only comparing username and password here for equality. Normally you yould take your own User-Repository or the Asp.Net-Identity thing.
If everything is alright we can create a new identity and add claims to it.
Thats it! For server side.
But how to consume it?
So we have created the enpoint…lets request it with a POST-Request. (I am using Postman here)So send a post request to the token enpoint we created. Take a look at the “x-www-form-urlencoded” which is very important! Also see the “grant_type” which is set to “password”. Without this you will not reach the token endpoint. username and password are equal due to the fact we check it for equality in your OAuthProvider we introduced before.
Also Check that in the Headers-Section we set the content-type to “application/x-www-form-encoded”. Firing this request reaches the endpoint and is giving us a valid token:
There you go. if we now copy this token and send it to a controller we tagged with the [authorize]-Attribute like this:
Note that we added the “Authorization”.Header with the “Bearer” and the token we just received. We can send it and receive the protected resource.
Thats it
You can also check the roles you added in the claims by just mentioning the roles in your Autorize-Attribute:
The roles are added via claims in your OAuthProvider.
coding
No comments:
Post a Comment