Giter Site home page Giter Site logo

angular2-oauth2's Introduction

angular2-oauth2

Support for OAuth 2 and OpenId Connect (OIDC) for Angular 2.

IMORTANT

This is an old version of this library. You can find the new one here:

Router

Successfully tested with the Angular 2 (RC) Component Router, PathLocationStrategy and CommonJS-Bundling via webpack.

Features

  • Logging in via OAuth2 and OpenId Connect (OIDC)
  • Using OIDC is optional
  • Validating claims of the id_token regarding the specs (aud, iss, nbf, exp, at_hash)
  • Hook for validating the signature of the received id_token
  • Single-Sign-Out by redirecting to the auth-server's logout-endpoint

Sample-Auth-Server

You can use the following OIDC-Sample-Server for Testing. It assumes, that your Web-App runns on http://localhost:8080.

Username/Password: max/geheim

Resources

Usage

Following samples use Angular 2 RC 1 with the "newest RC1-Router". For samples regarding the "BETA-Router" that has been deprecated after the BETA-phase, see the older version of this readme-file.

Setup Provider for OAuthService

import {bootstrap}    from '@angular/platform-browser-dynamic';
import {HTTP_PROVIDERS} from '@angular/http';
import {ROUTER_PROVIDERS} from '@angular/router';
import {AppComponent} from './app.component';

import { OAuthService } from 'angular2-oauth2/oauth-service';

var providers = [  
    OAuthService,   // <-- Provider for OAuthService
    HTTP_PROVIDERS,
    ROUTER_PROVIDERS
];

bootstrap(AppComponent, providers);

Top-Level-Component

import { OAuthService } from 'angular2-oauth2/oauth-service';

@Component({
    selector: 'flug-app',
    template: require("./app.component.html"),
    directives: [ROUTER_DIRECTIVES] // routerLink, router-outlet 
})
@Routes([
    { path: '/',                  component: HomeComponent },
    { path: '/flug-buchen',       component: FlugBuchen},
])
export class AppComponent { 
    
    constructor(private oauthService: OAuthService) {
        
        // Login-Url
        this.oauthService.loginUrl = "https://steyer-identity-server.azurewebsites.net/identity/connect/authorize"; //Id-Provider?
        
        // URL of the SPA to redirect the user to after login
        this.oauthService.redirectUri = window.location.origin + "/index.html";
        
        // The SPA's id. Register SPA with this id at the auth-server
        this.oauthService.clientId = "spa-demo";
        
        // The name of the auth-server that has to be mentioned within the token
        this.oauthService.issuer = "https://steyer-identity-server.azurewebsites.net/identity";

        // set the scope for the permissions the client should request
        this.oauthService.scope = "openid profile email voucher";
        
        // set to true, to receive also an id_token via OpenId Connect (OIDC) in addition to the
        // OAuth2-based access_token
        this.oauthService.oidc = true;
        
        // Use setStorage to use sessionStorage or another implementation of the TS-type Storage
        // instead of localStorage
        this.oauthService.setStorage(sessionStorage);
        
        // To also enable single-sign-out set the url for your auth-server's logout-endpoint here
        this.oauthService.logoutUrl = "https://steyer-identity-server.azurewebsites.net/identity/connect/endsession?id_token={{id_token}}";
        
        // This method just tries to parse the token within the url when
        // the auth-server redirects the user back to the web-app
        // It dosn't initiate the login
        this.oauthService.tryLogin({});
        
    }
    
}

Home-Component (for login)

import { Component } from '@angular/core';
import { OAuthService } from 'angular2-oauth2/oauth-service';

@Component({
    templateUrl: "app/home.html" 
})
export class HomeComponent {
    
    constructor(private oAuthService: OAuthService) {
    }
    
    public login() {
        this.oAuthService.initImplicitFlow();
    }
    
    public logoff() {
        this.oAuthService.logOut();
    }
    
    public get name() {
        let claims = this.oAuthService.getIdentityClaims();
        if (!claims) return null;
        return claims.given_name; 
    }
    
}
<h1 *ngIf="!name">
    Hallo
</h1>
<h1 *ngIf="name">
    Hallo, {{name}}
</h1>

<button class="btn btn-default" (click)="login()">
    Login
</button>
<button class="btn btn-default" (click)="logoff()">
    Logout
</button>

<div>
    Username/Passwort zum Testen: max/geheim
</div>

Calling a Web API with OAuth-Token

Pass this Header to the used method of the Http-Service within an Instance of the class Headers:

var headers = new Headers({
    "Authorization": "Bearer " + this.oauthService.getAccessToken()
});

Validate id_token

In cases where security relies on the id_token (e. g. in hybrid apps that use it to provide access to local resources) you could use the callback validationHandler to define the logic to validate the token's signature. The following sample uses the validation-endpoint of IdentityServer3 for this:

this.oauthService.tryLogin({
    validationHandler: context => {
        var search = new URLSearchParams();
        search.set('token', context.idToken); 
        search.set('client_id', oauthService.clientId);
        return http.get(validationUrl, { search }).toPromise();
    }
});

Callback after successful login

There is a callback onTokenReceived, that is called after a successful login. In this case, the lib received the access_token as well as the id_token, if it was requested. If there is an id_token, the lib validated it in view of it's claims (aud, iss, nbf, exp, at_hash) and - if a validationHandler has been set up - with this validationHandler, e. g. to validate the signature of the id_token.

this.oauthService.tryLogin({
    onTokenReceived: context => {
        //
        // Output just for purpose of demonstration
        // Don't try this at home ... ;-)
        // 
        console.debug("logged in");
        console.debug(context);
    },
    validationHandler: context => {
        var search = new URLSearchParams();
        search.set('token', context.idToken); 
        search.set('client_id', oauthService.clientId);
        return http.get(validationUrl, { search}).toPromise();
    }
});

angular2-oauth2's People

Contributors

benirule avatar maitreyaverma avatar manfredsteyer avatar mfazio23 avatar soviut avatar

Stargazers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

Watchers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar

angular2-oauth2's Issues

Resource Owner Flow support ?

Does this one support Resource Owner Flow ? If yes could you please provide sample. I cannot get it work. Thanks.

Still getting wrong at_hash after bug fix

Hi!

After installed 1.3.10 the problems with wrong at_hash disappearad, at least I thought so. Today the problem re-emerged again. We have a test suite with about 10 GUI tests (coypu based) that tests our login implementation. When executing the suite, now and then some tests fails with wrong at_hash.

Since it is almost impossible to reproduce the problem manually, I have not much information to give you. If I can do anything to help you finding the problem, please let me know!

Regards,

Fredrik

LocalStorage is not available on non-browser implementations

I use server side pre-rendering in my app.

With this service, I have to turn this off in order to use it as the storage provider 'local storage' is not available in node.

This could be fixed by using a shim such as https://www.npmjs.com/package/node-localstorage

if (typeof localStorage === "undefined" || localStorage === null) {
  var LocalStorage = require('node-localstorage').LocalStorage;
  localStorage = new LocalStorage('./scratch');
}

The workaround to using SystemJS to load angular2-oauth2

I've been trying to use your module with angular2-seed, and SystemJS keeps reporting errors regarding some weird path issues. It tries to look for the dependency modules under the top node_modules folder and somehow it wants to load node_modules/node_modules/package.json.

I spent a few hours on this and finally solved it by adding the following to my SystemJS config:

    packages: {
        rxjs: { defaultExtension: false },
        "angular2-oauth2": {
            //"baseURL": "/",
            //"format": "register",
            "defaultExtension": "js",
            "map": {
                "base64-js": "./node_modules/base64-js/lib/b64.js",
                "buffer": "./node_modules/buffer/index.js",
                "convert-hex": "./node_modules/sha256/node_modules/convert-hex/convert-hex.js",
                "convert-string": "./node_modules/sha256/node_modules/convert-string/convert-string.js",
                "ieee754": "./node_modules/buffer/node_modules/ieee754/index.js",
                "isarray": "./node_modules/buffer/node_modules/isarray/index.js",
                "js-base64": "./node_modules/js-base64/base64.js",
                "sha256": "./node_modules/sha256/lib/sha256.js"
            },
        }
    },

Not sure if this is the best approach, thought you might want to know this.

Thanks!

Broken function - easy fix

Mistake here:

OAuthService.prototype.hasValidIdToken = function () {
if (this.getIdToken) {

should be this.getIdToken() ?

access token and other information appends to URL

I am using using your library with my angular rc4 project. My Oauth 2 server is Spring Oauth 2.

Everything works fine but access token and other information gets appended in the redirect Uri after successful authentication.

It becomes like this :
http://localhost:3000/setup#access_token=bf7a077c-00cd-4abe-a3dc-cbf3986dec08&token_type=bearer&state=7rxsUXgchbnNU1T3A2SwmHwpmZeQCmB9EdFlotMY&expires_in=1799563032

Please help me as I have to deliver this quickly.

expose the expires_at property so that apps can setup a timer to try login again before the token expires

nice work on this library BTW, its working like a charm!

My only issue is tokens time out after about 24 hours; so rather than the app becoming unresponsive I'd like to setup a timer that if the user leaves their browser open the UI automatically redirects to the login page when the token expires. To do this I just need a public method to expose the expires_at property thats stored in the local / session storage

Real world examples

Can anybody provide an real-world example of using this lib? I tryed to authorize Steam using this, but maximum, that i achieved, was redirection after pressing "login" button on steamcomunity.com page without any sighn of authentification process. Is it possible? Steam using OpenId. Thanks!

checkAtHash error

I get the following error at this line in the checkAtHash method:
var leftMostHalf = tokenHash.slice(0, (tokenHash.length/2) );
var tokenHashBase64 = fromByteArray(leftMostHalf); --> Argument of type 'any[]' is not assignable to parameter of type 'Uint8Array'

get oauth2 token by providing username and password to backend

I'm newbie with angular2 and you angular2-oauth2 module.

I want to create login form with username and password and after user click login app send this data to my own (golang oauth2 backend, that verifies data and return some token).
What i need to do in login?

   public login() {
        this.oAuthService.initImplicitFlow();
    }

what is the initImplicitFlow ? where i can find help for module methods? Thanks!

Refresh token

It would be cool if this supported refresh tokens. They're pretty handy when accessing Google APIs.

Wrong property in console warn output

Hi!

I unintentionally found a minor glitch in the warn output written to the console when the defined issuer isn't the issuer set in the returned claims:

    if (this.issuer && claims.iss !== this.issuer) {
        console.warn("Wrong issuer: " + claims.issuer);
        return false;
    }

The property issuer in the console.warn should be iss.

Thanks for an excellent and easy way to authenticate our users!

Missing repository attribute in package.json

Without the repository attribute in package.json, NPM doesn't automatically know where to find the source. I realize that the source link is in the README but that doesn't show up in the NPM sidebar where users would normally look.

I could probably do a PR with this but can't do an npm publish.

responseType

Hi Guys,

How/Where can i assign the "responseType", currently get error of "Property 'responseType' does not exist on type 'OAuthService'"

Cheers, Rodrigo

id_token value not being stored after login

Hi!

After logging in, I am able to access some of the values stored by the service, like access_token, but not id_token ? I'm getting back both values through the url

Bear in mind I'm very new at this.

thanks!

Javier

Init implicit flow on page load

I'm trying to implement some sort of single-sign-on when the user loads the app but doesn't have a valid (access-/)identitytoken. How who we implement this?

  1. User enters page
  2. Not logged in?
  3. Redirect to token provider
  4. Check the token
  5. Access the application

We want to implement it so the user doesn't have to press the login button, they are probably already logged-in so they'll get a token instantly.

Where should I put the initImplicitFlow() call for this to happen?

Broken with Angular version 2.1.0

I tried to integrate this with angular2 (using google platform authenticate) latest release 2.1.0 but it fails at this point, there were some different options provided by google platform than given in your documentation. Can you please give an example with Google authentication?

I get many errors like:
context.idToken and oauthService.clientId is null, .toPromise(); is not a method.

this.oauthService.tryLogin({
validationHandler: context => {
var search = new URLSearchParams();
search.set('token', context.idToken);
search.set('client_id', oauthService.clientId);
return http.get(validationUrl, { search}).toPromise();
}
})

onTokenReceived() invoked twice if oidc=false and no validationHandler is provided

In the tryLogin() method, if oidc is set to false then onTokenReceived get invoked due to following code

if (!this.oidc && options.onTokenReceived) {
       options.onTokenReceived({ accessToken: accessToken });
}

Then later, in the same method, it gets invoked again due to

if (options.validationHandler) {
        var validationParams = { accessToken: accessToken, idToken: idToken };
        options
            .validationHandler(validationParams)
            .then(function () {
            _this.callEventIfExists(options);
        })
            .catch(function (reason) {
            console.error('Error validating tokens');
            console.error(reason);
        });
}
else {
        this.callEventIfExists(options);
}

Why two different base 64 libraries

Why does angular2-oauth2 needs base64-js and js-base64 which seems to fullfill the same purpose. Where's the difference and why we need to include both?

canActivate Routing

When I try to use canActivate on a route it always returns false. I am doing an implicit flow and when it redirects back it seems like it does not wait for the service to be aware of the login and it always redirects back to the login page.

`@Injectable()
export class AuthGuardService implements CanActivate {

constructor (
    private _oauthService: OAuthService,
    private _router: Router
) {

}

canActivate(route: ActivatedRouteSnapshot, state: RouterStateSnapshot) {
    if (this.loggedIn) {
        return true;
    }

    //Redirect the user before denying them access to this route
    this._router.navigate(['/welcome']);
    return false;
}

get loggedIn() {
    return this._oauthService.hasValidAccessToken();
}

}`

Recommend Projects

  • React photo React

    A declarative, efficient, and flexible JavaScript library for building user interfaces.

  • Vue.js photo Vue.js

    ๐Ÿ–– Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.

  • Typescript photo Typescript

    TypeScript is a superset of JavaScript that compiles to clean JavaScript output.

  • TensorFlow photo TensorFlow

    An Open Source Machine Learning Framework for Everyone

  • Django photo Django

    The Web framework for perfectionists with deadlines.

  • D3 photo D3

    Bring data to life with SVG, Canvas and HTML. ๐Ÿ“Š๐Ÿ“ˆ๐ŸŽ‰

Recommend Topics

  • javascript

    JavaScript (JS) is a lightweight interpreted programming language with first-class functions.

  • web

    Some thing interesting about web. New door for the world.

  • server

    A server is a program made to process requests and deliver data to clients.

  • Machine learning

    Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.

  • Game

    Some thing interesting about game, make everyone happy.

Recommend Org

  • Facebook photo Facebook

    We are working to build community through open source technology. NB: members must have two-factor auth.

  • Microsoft photo Microsoft

    Open source projects and samples from Microsoft.

  • Google photo Google

    Google โค๏ธ Open Source for everyone.

  • D3 photo D3

    Data-Driven Documents codes.