├── .gitignore ├── gruntfile.js ├── tests └── accessToken.spec.js ├── karma-unit.js ├── bower.json ├── LICENSE ├── package.json ├── README.md └── dist └── angularJsOAuth2.js /.gitignore: -------------------------------------------------------------------------------- 1 | node_modules -------------------------------------------------------------------------------- /gruntfile.js: -------------------------------------------------------------------------------- 1 | module.exports = function(grunt) { 2 | 3 | grunt.initConfig({ 4 | pkg: grunt.file.readJSON('package.json'), 5 | karma: { 6 | unit: { 7 | configFile: 'karma-unit.js' 8 | } 9 | } 10 | }); 11 | 12 | 13 | grunt.loadNpmTasks('grunt-karma'); 14 | 15 | grunt.registerTask('default', ['karma']); 16 | }; -------------------------------------------------------------------------------- /tests/accessToken.spec.js: -------------------------------------------------------------------------------- 1 | // a test suite (group of tests) 2 | describe('oauth2.accessToken tests', function() { 3 | beforeEach(module('oauth2.accessToken')); 4 | 5 | it ('can I get an instance of my factory', inject(function(AccessToken) { 6 | expect(AccessToken).toBeDefined(); 7 | })); 8 | 9 | it ('does the token start as null', inject(function(AccessToken) { 10 | expect(AccessToken.get()).toBeNull(); 11 | })); 12 | }); -------------------------------------------------------------------------------- /karma-unit.js: -------------------------------------------------------------------------------- 1 | var grunt = require('grunt'); 2 | module.exports = function ( karma ) { 3 | karma.set({ 4 | 5 | basePath: '.', 6 | 7 | files: [ 8 | "http://code.angularjs.org/1.4.1/angular.js", 9 | "http://code.angularjs.org/1.4.1/angular-mocks.js", 10 | "dist/angularJsOAuth2.js", 11 | "tests/*.spec.js", 12 | ], 13 | 14 | frameworks: [ 'jasmine' ], 15 | 16 | logLevel: karma.LOG_INFO, 17 | 18 | reporters: ['progress'], 19 | 20 | port: 7019, 21 | 22 | autoWatch: true, 23 | 24 | browsers: [ 25 | 'PhantomJS' 26 | ], 27 | 28 | singleRun: false 29 | }); 30 | }; -------------------------------------------------------------------------------- /bower.json: -------------------------------------------------------------------------------- 1 | { 2 | "name": "AngularJS-OAuth2", 3 | "version": "1.2.3", 4 | "homepage": "https://github.com/JamesRandall/AngularJS-OAuth2", 5 | "authors": [ 6 | "James Randall" 7 | ], 8 | "description": "Adds OAuth 2 authentication support to AngularJS", 9 | "keywords": [ 10 | "angularjs", 11 | "oauth2", 12 | "identity", 13 | "openid", 14 | "openidconnect", 15 | "directive", 16 | "authentication", 17 | "authorization" 18 | ], 19 | "license": "MIT", 20 | "ignore": [ 21 | "**/.*", 22 | "node_modules", 23 | "bower_components", 24 | "test", 25 | "tests" 26 | ], 27 | "dependencies": { 28 | "angular-md5": ">=0.1.7" 29 | }, 30 | "main": "dist/angularJsOAuth2.js" 31 | } 32 | -------------------------------------------------------------------------------- /LICENSE: -------------------------------------------------------------------------------- 1 | The MIT License (MIT) 2 | 3 | Copyright (c) 2016 James Randall 4 | 5 | Permission is hereby granted, free of charge, to any person obtaining a copy 6 | of this software and associated documentation files (the "Software"), to deal 7 | in the Software without restriction, including without limitation the rights 8 | to use, copy, modify, merge, publish, distribute, sublicense, and/or sell 9 | copies of the Software, and to permit persons to whom the Software is 10 | furnished to do so, subject to the following conditions: 11 | 12 | The above copyright notice and this permission notice shall be included in all 13 | copies or substantial portions of the Software. 14 | 15 | THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR 16 | IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, 17 | FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE 18 | AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER 19 | LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, 20 | OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE 21 | SOFTWARE. 22 | 23 | -------------------------------------------------------------------------------- /package.json: -------------------------------------------------------------------------------- 1 | { 2 | "name": "angularjs-oauth2", 3 | "version": "1.2.3", 4 | "description": "Bower and npm package for allowing an AngularJS application to authenticate with an OAuth 2 / Open ID Connect identity provider using the implicit flow.", 5 | "main": "dist/angularJsOAuth2.js", 6 | "scripts": { 7 | "test": "echo \"Error: no test specified\" && exit 1" 8 | }, 9 | "repository": { 10 | "type": "git", 11 | "url": "https://github.com/JamesRandall/AngularJS-OAuth2.git" 12 | }, 13 | "keywords": [ 14 | "angularjs", 15 | "oauth2", 16 | "identity", 17 | "openid", 18 | "openidconnect", 19 | "directive", 20 | "authentication", 21 | "authorization" 22 | ], 23 | "author": "James Randall", 24 | "license": "MIT", 25 | "bugs": { 26 | "url": "https://github.com/JamesRandall/AngularJS-OAuth2/issues" 27 | }, 28 | "homepage": "https://github.com/JamesRandall/AngularJS-OAuth2", 29 | "devDependencies": { 30 | "grunt": "^0.4.5", 31 | "karma-script-launcher": "^0.1.0", 32 | "karma-chrome-launcher": "^0.2.0", 33 | "karma-jasmine": "^0.3.5", 34 | "karma-phantomjs-launcher": "^0.2.0", 35 | "karma": "^0.12.37", 36 | "karma-story-reporter": "^0.3.1", 37 | "grunt-karma": "^0.11.1", 38 | "grunt-cli": "^0.1.13", 39 | "karma-sauce-launcher": "~0.1.8" 40 | }, 41 | "dependencies": { 42 | "angular-md5": "^0.1.10" 43 | } 44 | } 45 | -------------------------------------------------------------------------------- /README.md: -------------------------------------------------------------------------------- 1 | # AngularJS OAuth2 2 | 3 | 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: 4 | 5 | [Authenticating AngularJS Against OAuth 2.0 / OpenID Connect](http://www.azurefromthetrenches.com/authenticating-angularjs-against-oauth-2-0-openid-connect/) 6 | [Sample of IdentityServer3 and AngularJS-OAuth2](https://github.com/JamesRandall/AngularJS-OAuth2-IdentityServer3-Sample) 7 | 8 | The package is versioned using the [semantic versioning policy](http://semver.org). 9 | 10 | Feedback is very welcome. Please leave it in the [Issues](https://github.com/JamesRandall/AngularJS-OAuth2/issues) area or over on my [blog](https://www.azurefromthetrenches.com). 11 | 12 | ## Installing the Package 13 | 14 | The preferred approach is to sse the Bower package manager to install the package into your AngularJS project: 15 | 16 | bower install --save angularjs-oauth2 17 | 18 | However you can also use npm: 19 | 20 | npm install angularjs-oauth2 --save 21 | 22 | ## Basic Usage 23 | 24 | To authenticate an application running on localhost using Google's OAuth2 endpoint add the following HTML to, typically, your index.html page: 25 | 26 | 33 | 34 | 35 | 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: 36 | 37 | 48 | 49 | 50 | ## Options 51 | 52 | The directive supports the following options specified as attributes on the oauth2 element: 53 | 54 | **Option** |**Description** 55 | -------------------------|----------------------------------------- 56 | auto-generate-nonce |*(Optional)* Should a nonce be autogenerated if none is supplied. Defaults to true. 57 | authorization-url |The identity servers authorization endpoint. 58 | button-class |*(Optional)* The class to assign to the sign in / out button. Defaults to btn btn-primary. 59 | client-id |The authorization server client ID. For social providers such as Google and Facebook this is typically generated in the developer portal. 60 | 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. 61 | 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. 62 | responseType |The response type required from the identity server. Typically this is a combination of token and id_token. For example "id_token token". 63 | scope |The scopes requested from the authorization server. 64 | sign-in-text |*(Optional)* The text to apply to the sign in button. Defaults to "Sign in". 65 | 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. 66 | sign-out-text |*(Optional)* The text to apply to the sign out button. Defaults to "Sign out". 67 | sign-out-redirect-url |*(Optional)* The url to redirect the user to after sign out on the STS has completed. 68 | 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. 69 | 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. 70 | state |*(Optional)* The value to use for CSRF protection. If not specified then a value will be autogenerated. 71 | template |*(Optional)* The Angular template to use for the sign in and out buttons. 72 | token-storage-handler |*(Optional)* Allows a custom token storage strategy to be used. See Token Storage below. 73 | 74 | ## Token Storage / State Management 75 | 76 | 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: 77 | 78 | **Method** |**Description** 79 | ------------------|--------------- 80 | clear($window) |Clears the token from storage 81 | get($window) |Retrieves the token from storage, should return the token as a serialized string 82 | set(token,$window)|Is passed a token as a serializes string and should store it 83 | 84 | An example Angular controller implementing memory based token storage is shown below: 85 | 86 | angular.module('uiApp').controller('IndexCtrl', function ($scope) { 87 | var memoryToken; 88 | $scope.memoryTokenHandler = { 89 | get: function() { return memoryToken; }, 90 | set: function($window, token) { memoryToken = token; }, 91 | clear: function() { memoryToken = undefined; } 92 | }; 93 | }); 94 | 95 | As a contrast the default session storage handler (with full method parameters) is shown below: 96 | 97 | var tokenStorage = { 98 | get: function($window) { return $window.sessionStorage.getItem('token') }, 99 | set: function(token, $window) { $window.sessionStorage.setItem('token', token); }, 100 | clear: function($window) { $window.sessionStorage.removeItem('token'); } 101 | }; 102 | 103 | Data that is required over page refreshes is stored within [session storage](https://developer.mozilla.org/en/docs/Web/API/Window/sessionStorage): 104 | 105 | **Data** |**Description** 106 | ------------------|--------------- 107 | 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. 108 | token |An object containing the tokens requested along with scopes and expiry date. 109 | verifyState |Used to verify the CSRF state across the identity server redirect chain. It is set to null once used. 110 | 111 | ## Http Request Interception 112 | 113 | Once a valid token is obtained all http requests will be intercepted and have a Authorization header added in the format 114 | 115 | Bearer accesstoken 116 | 117 | If the token has expired then an oauth2:authExpired will be raised. 118 | 119 | ## Silent Token Renewal 120 | *(Thanks to [Ciaran Jessup](https://github.com/ciaranj) for contributing this feature)* 121 | 122 | 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. 123 | 124 | 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: 125 | 126 | 127 | 128 | 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: 129 | 130 | Refused to display 'your-identityserver-url' in a frame because it set 'X-Frame-Options' to 'SAMEORIGIN'. 131 | 132 | This is generally caused because your identity server is attempting to display content. 133 | 134 | For full details of the underlying implementation see these [commit notes](https://github.com/JamesRandall/AngularJS-OAuth2/commit/ff3e8e6825c18986c7545b75890287d3df8f8714). 135 | 136 | ## Styling 137 | 138 | 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: 139 | 140 | 146 | 147 | ## Events 148 | 149 | A variety of events are raised to indicate a change in state or communicate important information. 150 | 151 | **Event** |**Description** 152 | -------------------|--------------- 153 | oauth2:authError |An error occurred in the authentication process. The error is supplied as the event payload. 154 | oauth2:authExpired |The token has expired. The token is supplied as the event payload. 155 | oauth2:authSuccess |Indicates authorization has succeeded and a token returned. The token is supplied as the event payload. 156 | 157 | ## Thanks 158 | 159 | Thanks to the many people who have helped to improve this code either through direct contributions or through discussion and raising issues. 160 | 161 | ## License 162 | 163 | The MIT License (MIT) 164 | 165 | Copyright (c) 2016 James Randall 166 | 167 | Permission is hereby granted, free of charge, to any person obtaining a copy 168 | of this software and associated documentation files (the "Software"), to deal 169 | in the Software without restriction, including without limitation the rights 170 | to use, copy, modify, merge, publish, distribute, sublicense, and/or sell 171 | copies of the Software, and to permit persons to whom the Software is 172 | furnished to do so, subject to the following conditions: 173 | 174 | The above copyright notice and this permission notice shall be included in all 175 | copies or substantial portions of the Software. 176 | 177 | THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR 178 | IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, 179 | FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE 180 | AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER 181 | LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, 182 | OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE 183 | SOFTWARE. 184 | 185 | -------------------------------------------------------------------------------- /dist/angularJsOAuth2.js: -------------------------------------------------------------------------------- 1 | 'use strict'; 2 | 3 | (function() { 4 | var tokenStorage = { 5 | get: function($window) { return $window.sessionStorage.getItem('token') }, 6 | set: function(token, $window) { $window.sessionStorage.setItem('token', token); }, 7 | clear: function($window) { $window.sessionStorage.removeItem('token'); } 8 | }; 9 | 10 | function expired(token) { 11 | return (token && token.expires_at && new Date(token.expires_at) < new Date()); 12 | }; 13 | function getSessionToken($window) { 14 | var tokenString = tokenStorage.get($window); 15 | var token = null; 16 | if (tokenString && tokenString !== "null" ) { 17 | token = JSON.parse(tokenString); 18 | token.expires_at= new Date(token.expires_at); 19 | } 20 | return token; 21 | } 22 | 23 | angular.module('oauth2.accessToken', []).factory('AccessToken', ['$rootScope', '$location', '$window', function($rootScope, $location, $window) { 24 | var service = { 25 | token: null 26 | }; 27 | var oAuth2HashParams = ['id_token', 'access_token', 'token_type', 'expires_in', 'scope', 'state', 'error', 'error_description']; 28 | 29 | function setExpiresAt(token) { 30 | if(token){ 31 | var expires_at = new Date(); 32 | expires_at.setSeconds(expires_at.getSeconds()+parseInt(token.expires_in)-60); // 60 seconds less to secure browser and response latency 33 | token.expires_at = expires_at; 34 | } 35 | } 36 | 37 | function setTokenFromHashParams(hash) { 38 | var token = getTokenFromHashParams(hash); 39 | if (token !== null) { 40 | setExpiresAt(token); 41 | tokenStorage.set(JSON.stringify(token), $window) 42 | } 43 | return token; 44 | } 45 | 46 | function getTokenFromHashParams(hash) { 47 | var token = {}; 48 | var regex = /([^&=]+)=([^&]*)/g; 49 | var m; 50 | 51 | while (m = regex.exec(hash)) { 52 | var param = decodeURIComponent(m[1]); 53 | var value = decodeURIComponent(m[2]); 54 | 55 | if (oAuth2HashParams.indexOf(param) >= 0) { 56 | token[param] = value; 57 | } 58 | } 59 | 60 | if((token.access_token && token.expires_in) || token.error){ 61 | return token; 62 | } 63 | return null; 64 | } 65 | 66 | service.get = function() { 67 | return this.token; 68 | }; 69 | service.set = function(trustedTokenHash) { 70 | // Get and scrub the session stored state 71 | var parsedFromHash = false; 72 | var previousState = $window.sessionStorage.getItem('verifyState'); 73 | $window.sessionStorage.setItem('verifyState', null); 74 | 75 | if(trustedTokenHash) { 76 | // We 'trust' this hash as it was already 'parsed' by the child iframe before we got it as the parent 77 | // and then handed it back (not just reverifying as the sessionStorage was blanked by the child frame, so 78 | // we can't :( 79 | service.token = setTokenFromHashParams(trustedTokenHash); 80 | } 81 | else if ($location.$$html5) { 82 | if ($location.path().length > 1) { 83 | var values = $location.path().substring(1); 84 | service.token = setTokenFromHashParams(values); 85 | if (service.token) { 86 | parsedFromHash = true; 87 | } 88 | } 89 | } else { 90 | // Try and get the token from the hash params on the URL 91 | var hashValues = window.location.hash; 92 | if (hashValues.length > 0) { 93 | if (hashValues.indexOf('#/') == 0) { 94 | hashValues = hashValues.substring(2); 95 | } 96 | service.token = setTokenFromHashParams(hashValues); 97 | if (service.token) { 98 | parsedFromHash = true; 99 | } 100 | } 101 | } 102 | 103 | if (service.token === null) { 104 | service.token = getSessionToken($window); 105 | if (service.token === undefined) { 106 | service.token = null; 107 | } 108 | } 109 | 110 | if (service.token && service.token.error) { 111 | var error = service.token.error; 112 | service.destroy(); 113 | $rootScope.$broadcast('oauth2:authError', error); 114 | } 115 | 116 | if (service.token !== null) { 117 | if (!parsedFromHash || previousState == service.token.state) { 118 | $rootScope.$broadcast('oauth2:authSuccess', service.token); 119 | var oauthRedirectRoute = $window.sessionStorage.getItem('oauthRedirectRoute'); 120 | if (typeof(oauthRedirectRoute) !== 'undefined' && oauthRedirectRoute != "null") { 121 | $window.sessionStorage.setItem('oauthRedirectRoute', null); 122 | $location.path(oauthRedirectRoute); 123 | } 124 | } 125 | else { 126 | service.destroy(); 127 | $rootScope.$broadcast('oauth2:authError', 'Suspicious callback'); 128 | } 129 | } 130 | 131 | 132 | return service.token; 133 | }; 134 | service.destroy = function() { 135 | tokenStorage.clear($window) 136 | $window.sessionStorage.setItem('token', null); 137 | service.token = null; 138 | }; 139 | 140 | return service; 141 | }]); 142 | 143 | // Auth interceptor - if token is missing or has expired this broadcasts an authRequired event 144 | angular.module('oauth2.interceptor', []).factory('OAuth2Interceptor', ['$rootScope', '$q', '$window', function ($rootScope, $q, $window) { 145 | 146 | var service = { 147 | request: function(config) { 148 | var token = getSessionToken($window); 149 | if (expired(token)) { 150 | $rootScope.$broadcast('oauth2:authExpired', token); 151 | } 152 | else if (token) { 153 | config.headers.Authorization = 'Bearer ' + token.access_token; 154 | return config; 155 | } 156 | return config; 157 | }, 158 | response: function(response) { 159 | var token = getSessionToken($window); 160 | if (response.status === 401) { 161 | if (expired(token)) { 162 | $rootScope.$broadcast('oauth2:authExpired', token); 163 | } else { 164 | $rootScope.$broadcast('oauth2:unauthorized', token); 165 | } 166 | } 167 | else if (response.status === 500) { 168 | $rootScope.$broadcast('oauth2:internalservererror'); 169 | } 170 | return response; 171 | }, 172 | responseError: function(response) { 173 | var token = getSessionToken($window); 174 | if (response.status === 401) { 175 | if (expired(token)) { 176 | $rootScope.$broadcast('oauth2:authExpired', token); 177 | } else { 178 | $rootScope.$broadcast('oauth2:unauthorized', token); 179 | } 180 | } 181 | else if (response.status === 500) { 182 | $rootScope.$broadcast('oauth2:internalservererror'); 183 | } 184 | return $q.reject(response); 185 | } 186 | }; 187 | return service; 188 | }]); 189 | 190 | // Endpoint wrapper 191 | angular.module('oauth2.endpoint', ['angular-md5']).factory('Endpoint', ['AccessToken', '$window', 'md5', '$rootScope', function(accessToken, $window, md5, $rootScope) { 192 | var service = { 193 | authorize: function() { 194 | accessToken.destroy(); 195 | $window.sessionStorage.setItem('verifyState', service.state); 196 | window.location.replace(getAuthorizationUrl()); 197 | }, 198 | appendSignoutToken: false 199 | }; 200 | 201 | function getAuthorizationUrl(performSilently) { 202 | var url= service.authorizationUrl + '?' + 203 | 'client_id=' + encodeURIComponent(service.clientId) + '&' + 204 | 'redirect_uri=' + encodeURIComponent(performSilently?service.silentTokenRedirectUrl:service.redirectUrl) + '&' + 205 | 'response_type=' + encodeURIComponent(service.responseType) + '&' + 206 | 'scope=' + encodeURIComponent(service.scope); 207 | if (service.nonce) { 208 | url += '&nonce=' + encodeURIComponent(service.nonce); 209 | } 210 | url += '&state=' + encodeURIComponent(service.state); 211 | 212 | if( performSilently ) { 213 | url = url + "&prompt=none"; 214 | } 215 | return url; 216 | } 217 | 218 | service.renewTokenSilently= function() { 219 | function setupTokenSilentRenewInTheFuture() { 220 | var frame= $window.document.createElement("iframe"); 221 | frame.style.display = "none"; 222 | $window.sessionStorage.setItem('verifyState', service.state); 223 | frame.src= getAuthorizationUrl(true); 224 | function cleanup() { 225 | $window.removeEventListener("message", message, false); 226 | if( handle) { 227 | window.clearTimeout(handle); 228 | } 229 | handle= null; 230 | $window.setTimeout(function() { 231 | // Complete this on another tick of the eventloop to allow angular (in the child frame) to complete nicely. 232 | $window.document.body.removeChild(frame); 233 | }, 0); 234 | } 235 | 236 | function message(e) { 237 | if (handle && e.origin === location.protocol + "//" + location.host && e.source == frame.contentWindow) { 238 | cleanup(); 239 | if( e.data === "oauth2.silentRenewFailure" ) { 240 | $rootScope.$broadcast('oauth2:authExpired'); 241 | } 242 | else { 243 | accessToken.set(e.data); 244 | } 245 | } 246 | } 247 | 248 | var handle= window.setTimeout(function() { 249 | cleanup(); 250 | }, 5000); 251 | $window.addEventListener("message", message, false); 252 | $window.document.body.appendChild(frame); 253 | }; 254 | 255 | var now= new Date(); 256 | // Renew the token 1 minute before we expect it to expire. N.B. This code elsewhere sets the expires_at to be 60s less than the server-decided expiry time 257 | // this has the effect of reducing access token lifetimes by a mininum of 2 minutes, and restricts you to producing access tokens that are at *least* this long lived 258 | 259 | var renewTokenAt= new Date( accessToken.get().expires_at.getTime() - 60000 ); 260 | var renewTokenIn= renewTokenAt - new Date(); 261 | window.setTimeout(setupTokenSilentRenewInTheFuture, renewTokenIn); 262 | }; 263 | 264 | service.signOut = function(token) { 265 | if (service.signOutUrl && service.signOutUrl.length > 0) { 266 | var url = service.signOutUrl; 267 | if (service.appendSignoutToken) { 268 | url = url + '?id_token_hint=' + token; 269 | } 270 | if (service.signOutRedirectUrl && service.signOutRedirectUrl.length > 0) { 271 | url = url + (service.appendSignoutToken ? '&' : '?'); 272 | url = url + 'post_logout_redirect_uri=' + encodeURIComponent(service.signOutRedirectUrl); 273 | } 274 | window.location.replace(url); 275 | } 276 | }; 277 | 278 | service.init = function(params) { 279 | function generateState() { 280 | var text = ((Date.now() + Math.random()) * Math.random()).toString().replace(".",""); 281 | return md5.createHash(text); 282 | } 283 | 284 | if (!params.nonce && params.autoGenerateNonce) { 285 | params.nonce = generateState(); 286 | } 287 | service.nonce = params.nonce; 288 | service.clientId= params.clientId; 289 | service.redirectUrl= params.redirectUrl; 290 | service.scope= params.scope; 291 | service.responseType= params.responseType; 292 | service.authorizationUrl= params.authorizationUrl; 293 | service.signOutUrl = params.signOutUrl; 294 | service.silentTokenRedirectUrl= params.silentTokenRedirectUrl; 295 | service.signOutRedirectUrl = params.signOutRedirectUrl; 296 | service.state = params.state || generateState(); 297 | if (params.signOutAppendToken == 'true') { 298 | service.appendSignoutToken = true; 299 | } 300 | }; 301 | 302 | return service; 303 | }]); 304 | 305 | // Open ID directive 306 | angular.module('oauth2.directive', []) 307 | .config(['$routeProvider', function ($routeProvider) { 308 | $routeProvider 309 | .when('/silent-renew', { 310 | template: "" 311 | }) 312 | }]) 313 | .directive('oauth2', ['$rootScope', '$http', '$window', '$location', '$templateCache', '$compile', 'AccessToken', 'Endpoint', function($rootScope, $http, $window, $location, $templateCache, $compile, accessToken, endpoint) { 314 | var definition = { 315 | restrict: 'E', 316 | replace: true, 317 | scope: { 318 | authorizationUrl: '@', // authorization server url 319 | clientId: '@', // client ID 320 | redirectUrl: '@', // uri th auth server should redirect to (cannot contain #) 321 | responseType: '@', // defaults to token 322 | scope: '@', // scopes required (not the Angular scope - the auth server scopes) 323 | state: '@', // state to use for CSRF protection 324 | template: '@', // path to a replace template for the button, defaults to the one supplied by bower 325 | buttonClass: '@', // the class to use for the sign in / out button - defaults to btn btn-primary 326 | signInText: '@', // text for the sign in button 327 | signOutText: '@', // text for the sign out button 328 | signOutUrl: '@', // url on the authorization server for logging out. Local token is deleted even if no URL is given but that will leave user logged in against STS 329 | signOutAppendToken: '@', // defaults to 'false', set to 'true' to append the token to the sign out url 330 | signOutRedirectUrl: '@', // url to redirect to after sign out on the STS has completed 331 | silentTokenRedirectUrl: '@', // url to use for silently renewing access tokens, default behaviour is not to do 332 | nonce: '@?', // nonce value, optional. If unspecified or an empty string and autoGenerateNonce is true then a nonce will be auto-generated 333 | autoGenerateNonce: '=?', // Should a nonce be autogenerated if not supplied. Optional and defaults to true. 334 | tokenStorageHandler: '=' 335 | } 336 | }; 337 | 338 | definition.link = function(scope, element, attrs) { 339 | function compile() { 340 | var tpl = ''; 341 | if (scope.template) { 342 | $http.get(scope.template, { cache: $templateCache }).then(function(templateResult) { 343 | element.html(templateResult.data); 344 | $compile(element.contents())(scope); 345 | }); 346 | } else { 347 | element.html(tpl); 348 | $compile(element.contents())(scope); 349 | } 350 | }; 351 | 352 | function routeChangeHandler(event, nextRoute) { 353 | if (nextRoute.$$route && nextRoute.$$route.requireToken) { 354 | if (!accessToken.get() || expired(accessToken.get())) { 355 | event.preventDefault(); 356 | $window.sessionStorage.setItem('oauthRedirectRoute', $location.path()); 357 | endpoint.authorize(); 358 | } 359 | } 360 | }; 361 | 362 | 363 | function init() { 364 | if (scope.tokenStorageHandler) { 365 | tokenStorage = scope.tokenStorageHandler 366 | } 367 | scope.buttonClass = scope.buttonClass || 'btn btn-primary'; 368 | scope.signInText = scope.signInText || 'Sign In'; 369 | scope.signOutText = scope.signOutText || 'Sign Out'; 370 | scope.responseType = scope.responseType || 'token'; 371 | scope.signOutUrl = scope.signOutUrl || ''; 372 | scope.signOutRedirectUrl = scope.signOutRedirectUrl || ''; 373 | scope.unauthorizedAccessUrl = scope.unauthorizedAccessUrl || ''; 374 | scope.silentTokenRedirectUrl = scope.silentTokenRedirectUrl || ''; 375 | if (scope.autoGenerateNonce === undefined) { 376 | scope.autoGenerateNonce = true; 377 | } 378 | compile(); 379 | 380 | endpoint.init(scope); 381 | scope.$on('oauth2:authRequired', function() { 382 | endpoint.authorize(); 383 | }); 384 | scope.$on('oauth2:authSuccess', function() { 385 | if (scope.silentTokenRedirectUrl.length > 0) { 386 | if( $location.path().indexOf("/silent-renew") == 0 ) { 387 | // A 'child' frame has successfully authorised an access token. 388 | if (window.top && window.parent && window !== window.top) { 389 | var hash = hash || window.location.hash; 390 | if (hash) { 391 | window.parent.postMessage(hash, location.protocol + "//" + location.host); 392 | } 393 | } 394 | } else { 395 | // An 'owning' frame has successfully authorised an access token. 396 | endpoint.renewTokenSilently(); 397 | } 398 | } 399 | }); 400 | scope.$on('oauth2:authError', function() { 401 | if( $location.path().indexOf("/silent-renew") == 0 && window.top && window.parent && window !== window.top) { 402 | // A 'child' frame failed to authorize. 403 | window.parent.postMessage("oauth2.silentRenewFailure", location.protocol + "//" + location.host); 404 | } 405 | else { 406 | if (scope.unauthorizedAccessUrl.length > 0) { 407 | $location.path(scope.unauthorizedAccessUrl); 408 | } 409 | } 410 | }); 411 | scope.$on('oauth2:authExpired', function() { 412 | scope.signedIn = false; 413 | accessToken.destroy(); 414 | }); 415 | scope.signedIn = accessToken.set() !== null; 416 | $rootScope.$on('$routeChangeStart', routeChangeHandler); 417 | } 418 | 419 | scope.$watch('clientId', function(value) { init(); }); 420 | 421 | scope.signedIn = false; 422 | 423 | scope.signIn = function() { 424 | $window.sessionStorage.setItem('oauthRedirectRoute', $location.path()); 425 | endpoint.authorize(); 426 | } 427 | 428 | scope.signOut = function() { 429 | var token = accessToken.get().id_token; 430 | accessToken.destroy(); 431 | endpoint.signOut(token); 432 | }; 433 | }; 434 | 435 | return definition; 436 | }]); 437 | 438 | // App libraries 439 | angular.module('afOAuth2', [ 440 | 'oauth2.directive', // login directive 441 | 'oauth2.accessToken', // access token service 442 | 'oauth2.endpoint', // oauth endpoint service 443 | 'oauth2.interceptor' // bearer token interceptor 444 | ]).config(['$locationProvider','$httpProvider', 445 | function($locationProvider, $httpProvider) { 446 | $httpProvider.interceptors.push('OAuth2Interceptor'); 447 | } 448 | ]); 449 | })(); 450 | --------------------------------------------------------------------------------