AngularJS OAuth2
This is an Angular directive and HTTP interceptor available as a Bower package for adding OAuth 2 authentication support to AngularJS. In addition to this documentation a couple of samples and tutorials are available:
Authenticating AngularJS Against OAuth 2.0 / OpenID Connect Sample of IdentityServer3 and AngularJS-OAuth2
The package is versioned using the semantic versioning policy.
Feedback is very welcome. Please leave it in the Issues area or over on my blog.
Installing the Package
The preferred approach is to sse the Bower package manager to install the package into your AngularJS project:
bower install --save angularjs-oauth2
However you can also use npm:
npm install angularjs-oauth2 --save
Basic Usage
To authenticate an application running on localhost using Google's OAuth2 endpoint add the following HTML to, typically, your index.html page:
<oauth2 authorization-url="https://accounts.google.com/o/oauth2/auth"
sign-out-url="https://accounts.google.com/o/oauth2/revoke?token="
sign-out-append-token="true"
client-id="*** get a client ID from the Google Developer Console ***"
redirect-url="http://localhost"
response-type="token"
scope="openid">
</oauth2>
However the plugin is fully compatible with any Open ID Connect / OAuth 2 provider and the example below demonstrates authenticating against IdentityServer3 running on localhost, using a custom sign in button, and supporting silent token renewal:
<oauth2 authorization-url="https://localhost:44300/identity/connect/authorize"
sign-out-url="https://localhost:44300/identity/connect/endsession"
sign-out-append-token="true"
sign-out-redirect-url="http://localhost:9000/#/landing"
client-id="portal"
redirect-url="http://localhost:9000"
silent-token-redirect-url="http://localhost:9000/#/silent-renew"
response-type="id_token token"
scope="openid portaldashboard"
template='views/templates/signInButton.html'
auto-generate-nonce="true">
</oauth2>
Options
The directive supports the following options specified as attributes on the oauth2 element:
Option | Description |
---|---|
auto-generate-nonce | (Optional) Should a nonce be autogenerated if none is supplied. Defaults to true. |
authorization-url | The identity servers authorization endpoint. |
button-class | (Optional) The class to assign to the sign in / out button. Defaults to btn btn-primary. |
client-id | The authorization server client ID. For social providers such as Google and Facebook this is typically generated in the developer portal. |
nonce | (Optonal) The nonce to supply to the identity server. If not specified and auto-generate-nonce is set to true then one will be autogenerated. |
redirectUrl | The redirect URL to supply to the identity server. If this doesn't match a URL registered in your identity server this will generally cause an error. |
responseType | The response type required from the identity server. Typically this is a combination of token and id_token. For example "id_token token". |
scope | The scopes requested from the authorization server. |
sign-in-text | (Optional) The text to apply to the sign in button. Defaults to "Sign in". |
sign-out-append-token | (Optional) Set this to true to append the ID token to the signout URL - a response_type of id_token must be used for this to wokr. Defaults to false. |
sign-out-text | (Optional) The text to apply to the sign out button. Defaults to "Sign out". |
sign-out-redirect-url | (Optional) The url to redirect the user to after sign out on the STS has completed. |
sign-out-url | (Optional) The identity servers sign out endpoint. If not specified then the local token will be deleted on sign out but the user will remain signed in to the identity server. |
silent-token-redirect-url | (Optional) If specified this will enable silent token renewal and the identity server will redirect to this URL. See section below for further details. |
state | (Optional) The value to use for CSRF protection. If not specified then a value will be autogenerated. |
template | (Optional) The Angular template to use for the sign in and out buttons. |
token-storage-handler | (Optional) Allows a custom token storage strategy to be used. See Token Storage below. |
Token Storage / State Management
By default the directive stores tokens in the browsers session storage however this behaviour can be changed by passing an object into the token-storage-handler attribute that supports the following methods:
Method | Description |
---|---|
clear($window) | Clears the token from storage |
get($window) | Retrieves the token from storage, should return the token as a serialized string |
set(token,$window) | Is passed a token as a serializes string and should store it |
An example Angular controller implementing memory based token storage is shown below:
angular.module('uiApp').controller('IndexCtrl', function ($scope) {
var memoryToken;
$scope.memoryTokenHandler = {
get: function() { return memoryToken; },
set: function($window, token) { memoryToken = token; },
clear: function() { memoryToken = undefined; }
};
});
As a contrast the default session storage handler (with full method parameters) is shown below:
var tokenStorage = {
get: function($window) { return $window.sessionStorage.getItem('token') },
set: function(token, $window) { $window.sessionStorage.setItem('token', token); },
clear: function($window) { $window.sessionStorage.removeItem('token'); }
};
Data that is required over page refreshes is stored within session storage:
Data | Description |
---|---|
oauthRedirectRoute | Used to store the application route to navigate to following a redirect from an identity server. It is set to null once that flow is complete. |
token | An object containing the tokens requested along with scopes and expiry date. |
verifyState | Used to verify the CSRF state across the identity server redirect chain. It is set to null once used. |
Http Request Interception
Once a valid token is obtained all http requests will be intercepted and have a Authorization header added in the format
Bearer accesstoken
If the token has expired then an oauth2:authExpired will be raised.
Silent Token Renewal
(Thanks to Ciaran Jessup for contributing this feature)
Silent token renewal uses a hidden iframe to contact the identity server and recieve a token 1 minute before it is expected to expire keeping a user logged in until they leave the web app. This does require them to have instructed the identity server to remember them when they logged in.
To set this up within your Angular app set the silent-token-redirect-url attribute on the oauth2 element. This will register a route of silent-renew and so your attribute should redirect to that location. So for example if your app is running on localhost then the directive should be set as follows:
<oauth2 ... silent-token-redirect-url="http://localhost/#/silent-renew" ...></oauth2>
You will need to ensure your identity server supports a redirect back to this URL. If anything is misconfigured in the server you are likely to recieve an error similar to the below:
Refused to display 'your-identityserver-url' in a frame because it set 'X-Frame-Options' to 'SAMEORIGIN'.
This is generally caused because your identity server is attempting to display content.
For full details of the underlying implementation see these commit notes.
Styling
By default the directive comes configured for use within a Bootstrap 3 navigation bar. Basic styling can be undertaken using the button-class, sign-in-text and sign-out-text attributes but the appearance can be completely customized by providing a new template via the template attribute. The default template is defined as follows:
<p class="navbar-btn">
<a class="{{buttonClass}}">
<span href="#" ng-hide="signedIn" ng-click="signIn()" >{{signInText}}</span>
<span href="#" ng-show="signedIn" ng-click="signOut()">{{signOutText}}</span>
</a>
</p>
Events
A variety of events are raised to indicate a change in state or communicate important information.
Event | Description |
---|---|
oauth2:authError | An error occurred in the authentication process. The error is supplied as the event payload. |
oauth2:authExpired | The token has expired. The token is supplied as the event payload. |
oauth2:authSuccess | Indicates authorization has succeeded and a token returned. The token is supplied as the event payload. |
Thanks
Thanks to the many people who have helped to improve this code either through direct contributions or through discussion and raising issues.
License
The MIT License (MIT)
Copyright (c) 2016 James Randall
Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions:
The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.