Goals
- Implement a secure API using the JSON Web Token open standard (RFC 7519).
- Consume the API from a React JS application.
-
Clone this repository. Compile and run the Spring Boot project.
-
Verify that authentication works by issuing the following command from the console:
curl -H "Content-Type: application/json" -X POST -d '{"username":"xyz","password":"password"}' http://localhost:8080/user/login
If you don't have the curl utility installed, try using the Postman application.
- Open the following url and try to understand the message you get from the server:
http://localhost:8080/api/test
Then try to locate the code fragment where the exception is thrown.
The Exception is a ''Missing or invalid Authorization header', because we did not send the authorization header with the get request in the browser
The @Bean annotation will register the filter in the api/* path, once the application is run
- Comment the line 13 @Bean on the SpringBootSecureApiApplication class. Re-run the project and go to the endpoint again:
http://localhost:8080/api/test
Why do you think it works now? Discuss your findings with your classmates.
The solution for this can be handled with a new get request using curl and sending the auth header
-
Implement the logic to verify the user's credentials on the UserController and the UserServiceImpl classes.
-
Add the TaskController and services implemented on the previous lab. Ensure the endpoints are exposed under the /api path.
-
Verify that your implementation secures all the exposed methods under the /api path in your API.
-
Add the following annotation on top of your @RequestMapping annotation on your REST controllers (to avoid the Cross-origin access restriction )
@CrossOrigin(origins = "http://localhost:3000")
-
Open the Task Planner App React JS project.
-
Install the axios node package
npm install axios --save
-
Make a first request to the API to authenticate on the method componentDidMount():
axios.post('http://localhost:8080/user/login', { username: 'xyz', password: 'password' }) .then(function (response) { console.log(response.data); }) .catch(function (error) { console.log(error); });
-
Save the returned authentication token into the local storage.
-
Implement the logic to validate if the user has a valid token. Then redirect to the Main View.
-
Create an instance of the Axios client that contains the token inside the Authorization header
this.axios = axios.create({ baseURL: 'http://localhost:8080/api/', timeout: 1000, headers: {'Authorization': 'Bearer ' + token} });
-
Make a request to the API with the Axios client instance for retrieving the Tasks List.
-
Create an additional call to Post new Tasks to the API.