Skip to content

Protecting your API

Jan Hajek edited this page May 30, 2016 · 1 revision

This library's purpose isn't just authentication, but it can also protect your API with Azure Active Directory authentication. The Provider now also exposes validateToken(string $token) which lets you pass it an access token which you for example received in the Authorization header of the request on your API. You can use the function like so (in vanilla PHP):

// Provider initialization
$provider = new TheNetworg\OAuth2\Client\Provider\Azure([
    'clientId' => "clientId",
    'clientSecret' => "clientSecret",
    'redirectUri' => 'https://redirectUri',
    'audience' => 'https://api_application_id', // Audience parameter forces validation of audience in the token (so we know the token was meant for our application)
    'isApi' => true // isApi forces the verification of token signature - this is important so that we know that the token passed has been generated by AAD
]);

// Obtain the accessToken - in this case, we are getting it from Authorization header
$headers = getallheaders();
// Assuming you got the value of Authorization header as "Bearer [the_access_token]" we parse it
$authorization = explode(' ', $headers['Authorization']);
$token = $authorization[1];

try {
    $claims = $provider->validateToken($token);
} catch (Exception $e) {
    // Something happened, handle the error
}

// The access token is valid, you can now proceed with your code. You can also access the $claims as defined in JWT - for example roles, group memberships etc.

You may also need to access some other resource from the API like the Microsoft Graph to get some additional information. In order to do that, there is urn:ietf:params:oauth:grant-type:jwt-bearer grant available (RFC). An example (assuming you have the code above working and you have the required permissions configured correctly in the Azure AD application):

$graphAccessToken = $provider->getAccessToken('jwt_bearer', [
    'resource' => 'https://graph.microsoft.com/',
    'assertion' => $accessToken,
    'requested_token_use' => 'on_behalf_of'
]);

$me = $provider->get('https://graph.microsoft.com/v1.0/me', $graphAccessToken);
print_r($me);

Just to make it easier so you don't have to remember entire name for grant_type (urn:ietf:params:oauth:grant-type:jwt-bearer), you just use short jwt_bearer instead.

Clone this wiki locally