# Secure REST API with Amazon Cognito
[Amazon Cognito](https://aws.amazon.com/cognito/) is a user identity and access management service that I will be using to secure the [Languages API RESTful web service](https://github.com/mike-osu/languages-api). This involves two high-level steps:
1. Cognito setup with Amazon
2. Spring Security configuration in the application
## Amazon Cognito
First step is to create a user pool in Cognito. This is essentially a user directory and provides sign-up and sign-in functionality for web and mobile apps.

Next, we add a user that we can use to login to the REST service and get a JSON web token with which our endpoints will be secured. The username is `mike` (password is hidden).

Next step is to create and configure an app client. This will generate a unique app client ID that the REST service will use to access the user pool and generate authentication tokens for authorizing service requests.

With this setup, we can login as the user `mike` that we created. Cognito verifies the login credentials, and if successful, it returns an ID, access and refresh JSON web tokens (JWT) for the authenticated user. A JWT is a Base64-encoded JSON string that contains information about the user (called claims).
There are various ways to login. In this case, we'll use the AWS CLI:
```
aws cognito-idp initiate-auth \
--auth-flow USER_PASSWORD_AUTH \
--client-id <app client id> \
--auth-parameters USERNAME=mike,PASSWORD=<password>
```
The (partially obscured) response looks like this:

The ID token contains claims about the identity of the authenticated user, such as name and email. The Access token contains claims about the authenticated user, a list of the user's groups, and a list of scopes. The refresh token can be used to retrieve new ID and access tokens when those expire.
## Spring Security
The next step will be to secure the REST API endpoints by configuring the service with Spring Security and integrating with the Cognito user pool. This will require any REST service requests to include a valid ID token (JWT) in the request header. Not including a valid JWT will result in a "401 unauthorized" response from the service.
GET request without JWT

GET request with JWT
