Thursday 5 May 2016

Token Authentication with Claims and Asp.Net WebAPI (Simple Example … also on GitHub)

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:
  1. We ask the Server for a token
  2. We receive the token, store it client side and…
  3. …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.

The first line is a CORS-Line. You can get information about CORS looking here or here.
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)1So 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.
2Also 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:
3There you go. if we now copy this token and send it to a controller we tagged with the [authorize]-Attribute like this:


4
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

Angular Tutorial (Update to Angular 7)

As Angular 7 has just been released a few days ago. This tutorial is updated to show you how to create an Angular 7 project and the new fe...