-
Notifications
You must be signed in to change notification settings - Fork 1
3.3 Rework Greeting Method
Go back to 3.2 Create Authentication Provider
Now that we have a proper User model and that we have a way to authenticate and extract identities, we can refactor our greeting()method.
View refactored lib/User.php
The first thing we are going to do is rework the greeting() method so that it greets the user by name if the user has authenticated. We do this by asking the security context if the identity has authenticated (line 43). If authentication was successful, return the identity's givenName in the Welcome message. Otherwise, return our same old message.
Then we add a new annotation (line 36):
<?php
/**
* ...
* @Authentication optional
* ...
*/The annotation instructs the REST service handler that before that method is called, it should run through its authentication providers to see if anyone has provided an identity. By using optional keyword the service handler will check if the user is authenticated but not fail if the providers never return an identity. By using required the service handler will automatically return an HTTP 401 status (Authentication Required) and never call the method.
Note that the annotation will only affect the method where it is declared. It will not have an affect on other methods on this or other objects. That means it is possible to combine authorization requires on a per-method basis.
To test our new functionality, we will leave the original testGreet() method in our UserTest class the same. The behavior should be the same.
To test the greeting once we have an identity, we create a new Cougar Identity with some test values. Then we set the required method expectations for the isAuthenticated() method and getIdentity() methods in our Security object test double. For the getIdentity() method, we return our test identity. Then we call the method and make sure we receive the identity's name.
To make testing a bit easier, we've provided a PHP login page. You can access it at http://localhost/cougar_tutorial/login.php. You can use the admin identity that is already in the system:
username: admin@example.com
password: Adm1n!
Then visit the greeting service again. You should see Welcome, Admin.
You may also make a direct call using a REST client and adding the following Authorization header:
Authorization: Basic YWRtaW5AZXhhbXBsZS5jb206QWRtMW4h
Continue to 4. Authorization