Exercise 5: Adding authentication
Expected time: 10 minutesLearning goals of this exercise
Add simple password based authentication to the LED service created in Exercise4 so only authorized users can change the LED settings remotely.
Details:
- Close any open files from previous exercises to avoid confusion and open HOLLEDController.java and WoTServer.java in Exercise5. Make Exercise5 your main project.
- HOLLEDController.java: In isAuthorized(), look for and match the authorization header against the string formed by concatenating "Basic " with the Base64 encoding of "<username>:<password>".
public boolean isAuthorized(HttpRequest req) { // if (req.getMethod().equalsIgnoreCase("PUT")) { // String auth = req.getHeader("Authorization"); // // return ((auth != null) && // auth.equalsIgnoreCase("Basic " + Base64.encode("Ali Baba:open sesame"))); // } return true; // GETs should still succeed }
Uncommenting the lines above will enforce HTTP Basic authentication for PUT requests. In this example, the authorized username is "Ali Baba" and the required password id "open sesame". Users should experiment with picking a different username and password combination.
- WoTServer.java: In the call to nas.registerApp registering an instance of HOLLEDController, replace xxxx in the realm specification with the last four hex-digits of your SPOT Id.
nas.registerApp("/leds", new HOLLEDController("n=LED control\nd=http://bit.ly/9C3rlP\nrealm=spot-xxxx"));
- Connect your SPOT to the USB port (if it isn't already) and stop any previously running applications by resetting the Sun SPOT (don't power it off). Build, deploy and run Exercise5 on to the SPOT. In NetBeans, you can accomplish this by clicking the right button on the project name to bring up a context-menu and selecting "Run".
- After some time, the SPOT will discover the gateway machine and register itself with it.
-
At that point, you should be able to access and modify the LED settings on your SPOT at the URL http://<address>:<port>/spot-xxxx/leds using any HTTP client, e.g. Firefox or curl.
PUT commands will now require knowledge of the authorized username and password.- Access LED setting
% curl --request GET "http://<address>:<port>/spot-xxxx/leds"
- Attempt to change the LED setting without authentication will fail
% curl --request PUT --data "[255,255,0]" "http://<address>:<port>/spot-xxxx/leds"
Client Error: 401 Unauthorized
- Attempt to change the LED setting with authentication will succeed
% curl --request PUT --data "[255,255,0]" --user "<username>:<password>" "http://<address>:<port>/spot-xxxx/leds"
Successful: 200 OK
Attempts to change the LED setting using an HTTP PUT from a web browser will automatically prompt for a username/password combination.
Summary
This exercise showed how to add HTTP basic authentication to an HTTP command.