npm package discovery and stats viewer.

Discover Tips

  • General search

    [free text search, go nuts!]

  • Package details

    pkg:[package-name]

  • User packages

    @[username]

Sponsor

Optimize Toolset

I’ve always been into building performant and accessible sites, but lately I’ve been taking it extremely seriously. So much so that I’ve been building a tool to help me optimize and monitor the sites that I build to make sure that I’m making an attempt to offer the best experience to those who visit them. If you’re into performant, accessible and SEO friendly sites, you might like it too! You can check it out at Optimize Toolset.

About

Hi, 👋, I’m Ryan Hefner  and I built this site for me, and you! The goal of this site was to provide an easy way for me to check the stats on my npm packages, both for prioritizing issues and updates, and to give me a little kick in the pants to keep up on stuff.

As I was building it, I realized that I was actually using the tool to build the tool, and figured I might as well put this out there and hopefully others will find it to be a fast and useful way to search and browse npm packages as I have.

If you’re interested in other things I’m working on, follow me on Twitter or check out the open source projects I’ve been publishing on GitHub.

I am also working on a Twitter bot for this site to tweet the most popular, newest, random packages from npm. Please follow that account now and it will start sending out packages soon–ish.

Open Software & Tools

This site wouldn’t be possible without the immense generosity and tireless efforts from the people who make contributions to the world and share their work via open source initiatives. Thank you 🙏

© 2024 – Pkg Stats / Ryan Hefner

angular-oidc

v1.1.2

Published

OAuth 2 and OIDC-Lib for AngularJS

Downloads

93

Readme

Simple Lib for using OAuth2 and OIDC in Angular

Installation

npm install angular-oidc

Getting Started

The easiest way to get stared is to include the provided bundle:

<script src="node_modules/angular-oidc/bundle/oauth.js"></script>

Dependencies

  • angular-base64
  • sha256
  • angular-ui-router (not part of the bundle)
  • angular (not part of the bundle)

License

MIT, see https://opensource.org/licenses/MIT

Authorization-Server

The provided sample uses a hosted version of IdentityServer3 (https://github.com/IdentityServer/IdentityServer3), but it is aimed to work also with other OAuth2/OIDC-Authorization-Servers. You can login with any Facebook-Account or with max/geheim.

Configuration

Just configure oauthService and call setup to let it hook into UI-Router. Users that require to log in are redirected to the mentioned loginState and after logging in and receiving a token, onTokenReceived is called. There you can grab the requested token.

app.constant("config", { 
    apiUrl: "https://steyer-api.azurewebsites.net",
    loginUrl: "https://steyer-identity-server.azurewebsites.net/identity/connect/authorize",
    issuerUri: "https://steyer-identity-server.azurewebsites.net/identity"
});

app.run(function (oauthService, $http, userService, config) {

    oauthService.loginUrl =  config.loginUrl;
    oauthService.redirectUri = location.origin + "/index.html";
    oauthService.clientId = "spa-demo";
    oauthService.scope = "openid profile email voucher";
    oauthService.issuer = config.issuerUri;
    oauthService.oidc = true;
    
    oauthService.setup({
        loginState: 'login',
        onTokenReceived: function(context) {
            $http.defaults.headers.common['Authorization'] = 'Bearer ' + context.accessToken;
            userService.userName = context.idClaims['given_name'];
        }
    });

});

UI-Router-Route that needs a logged-in user can be marked with restricted: true. This is just about user experience and not about security. Security is done by validating the token at server-side.

app.config(function ($stateProvider, $urlRouterProvider, $locationProvider) {
    $locationProvider.html5Mode(false);

    $urlRouterProvider.otherwise('/home');

    $stateProvider.state('home', {
        url: '/home',
        templateUrl: '/app/demo/home.html',
    }).state('voucher', {
        url: '/voucher',
        templateUrl: '/app/demo/voucher.html',
        controller: 'VoucherCtrl',
        restricted: true
    }).state('login', {
        url: '/login?requestedUrl',
        templateUrl: '/app/demo/login.html',
        controller: 'LoginCtrl'
    }).state('logout', {
        url: '/logout',
        templateUrl: '/app/demo/logout.html',
        controller: 'LogoutCtrl'
    });

});

More Configuration-Options

You can also register the URL of an web-api that creates a random string when called via GET. This is to create a nonce-using preventing some attacks. Otherwise it uses some simple java-script-fallback for this. In addition to this, you could use the validationHandler-callback to validate the received tokens. The next sample uses this to send the token to a service that checks the signature of it. The validationHandler should return a promise that informs about the validity of the token by it's state.

app.run(function (oauthService, $http, userService, config) {

    oauthService.loginUrl =  config.loginUrl;
    oauthService.redirectUri = location.origin + "/index.html";
    oauthService.clientId = "spa-demo";
    oauthService.scope = "openid profile email voucher";
    oauthService.issuer = config.issuerUri;
    oauthService.oidc = true;
    oauthService.rngUrl = config.rngUrl;
    
    oauthService.setup({
        loginState: 'login',
        onTokenReceived: function(context) {
            $http.defaults.headers.common['Authorization'] = 'Bearer ' + context.accessToken;
            userService.userName = context.idClaims['given_name'];
        },
        validationHandler: function(context) {
            var params = {token: context.idToken, client_id: oauthService.clientId};
            return $http.get(config.validationUrl, { params: params});
        }
    });

});

Redirect User

To create the redirect-url that points the user to the Authorization-Server, just call createLoginUrl. You can pass an optionState that denotes the UI-Router state the user should be redirected to after logging in.

oauthService.createLoginUrl(optinalState).then(function (url) {
   // do stuff with url
});

To directly redirect the user to the Authorization-Server, you can call initImplicitFlow:

oauthService.initImplicitFlow(optionalState);

There is also an oauthLoginButton-Directive you could use to create a login-button, that redirects the user to the Authorization-Server:

<input 
  oauth-login-button
  type="button" 
  value="Login" 
  state="model.requestedUrl" 
  class="btn" />

Refresh Token

According to the OAuth2-Spec and for security reasons, implicit flow doesn't issue a refresh-token. But if the Authorization Server remembers the current user and his or her constent, for instance by using cookies, it is quite easy to get a new token without user-interaction. Just redirect the user to the authorization server:

oauthService.initImplicitFlow(optionalState);

To prevent leaving the current single page application, this library can try to get an new token using an hidden iframe. Call tryRefresh for this purpose. If that works out, the callback onTokenReceived (see above) is called. In addition to that, this method returns a promise that tells you, whether the refresh succeeded or failed. Please note, that the mentioned callback is called twice: once for the application-instance in the iframe and once for the calling application outside of it. Afterwards the iframe is removed.

$scope.refresh = function () {
    oauthService
        .tryRefresh()
        .then(function () {
            var token = oauthService.getAccessToken();
            $scope.model.message = "Got Token: " + token;
            $http.defaults.headers.common['Authorization'] = 'Bearer ' + token;
        })
        .catch(function () {
            $scope.model.message = "Error receiving new token!";
        });

To hide the used iframe, you can define a style for it's class oauthFrame:

<style>
    .oauthFrame {
        display: none;
    }
</style>