2.10: Testing Login and Authentication

We need to test that everything is working. We don't want to lock down our AuthController - because we need unauthenticated users to access it.

Let's return to our ValuesController that was added to the project on creation.

Adding Authorization

At the top of the ValuesController - add the Authorize attribute. This will require a valid token to be passed when accessing this controller.

[Authorize]
[Route("api/[controller]")]
public class ValuesController : Controller
{
    // ...

Testing Authorization

Let's try to access our values without supplying any credentials

TestAuthorization

If everything is working - you should get a 401 Unauthorized response.

Our precious values data is protected!

Testing Login

Next, let's see if we're able to login successfully.

We'll send a POST request to http://localhost:5000/api/auth/login.

The username and password should be supplied as raw text in application/json format (and, supply credentials you know are in your database):

Example:

Login

Testing Access With Token

Now, let's try to get our values again.

This time we'll add an Authorization key and a value of Bearer followed by a space and then the token string.

You should get a 200 OK response and the values returned in the body.

AuthValuees

You can delete the ValuesController.cs file now.

Extra JWT Info

Copy your token string that was returned and go to JWT.io.

In the "Encoded" section, paste your token:

EncodedToken

You can see the three sections of the JWT in different colors.

On the right you can see the JWT decoded.

DecodedToken

So, our information is accessible.

However, that's not the point of a JWT. We shouldn't be providing any secure information.

The JWT is used to validate a user. If you look at the bottom in red: "Invalid Signature." So, it's working because we didn't provide our key.

In the "VERIFY SIGNATURE" section, enter your key (that you saved in appsettings.json).

NOW it's verified.

VerifiedToken

Section Wrap-up

Nice work! We have authentication enabled and we are able to register and login with our API. However, it's not too rewarding to pass tokens around via Postman. In the next section, let's wire up our Angular project!

Last updated