Coder Social home page Coder Social logo

ng2-ui-auth's Introduction

An angular2 repository for authentication based on angular1's satellizer (https://satellizer.herokuapp.com/#/ https://github.com/sahat/satellizer) library. To use this run npm install ng2-ui-auth --save.

If you are migrating from version 7 or below, look at the changelog

for a full client + server-side example: ronzeidman/ng2-ui-auth-example. for a Go Server and extended client example: pcdummy/ng2-ui-auth-example. Just modify your main app module:

import {Ng2UiAuthModule} from 'ng2-ui-auth';

const GOOGLE_CLIENT_ID = '******\*\*******\*\*******\*\*******.apps.googleusercontent.com';

@NgModule({
imports: [
BrowserModule,
HttpClientModule,
Ng2UiAuthModule.forRoot({providers: {google: { clientId: GOOGLE_CLIENT_ID}}}),
...
]
...
})
AppModule {}

I will update https://github.com/ronzeidman/ng2-ui-auth-example with a more current and simpler example soon. If someone wishes to update it and send a pull request, he is more than welcome to do so.

If something doesn't work, feel free to issue a pull request and/or create a new issue, I'm not sure I'll be responsive though since I use it internally for my project and will only update and fix the repository if it affects my work.

If someone thinks that some of my code can be written better I encourage you to inform me.

ng2-ui-auth's People

Contributors

aegyed91 avatar aitboudad avatar chad-autry avatar dependabot[bot] avatar jochumdev avatar ronzeidman avatar royipr avatar royipressburger 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  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  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

ng2-ui-auth's Issues

authorization for custom authentication provider

hi ronzeidman,

Thanks for your effort first. I'm trying to use your library for a project. I'm trying to use it with a custom jwt authentication provider .previously I have used the custom jwt authentication provider with satellizer successfully.

Here is how I used it with satellizer.

$authProvider.oauth2({
name: 'customauthprovider',
url: '/auth/custom',
clientId: 'abc',
redirectUri: window.location.origin,
authorizationEndpoint: CONFIGS.imsmartBaseUrl + 'oauth/authorize'
});

jwt authentication is developed with asp.net mvc and oauth2.

My feeling is ng2-ui-auth should support with custom authentication providers as well. But when I try it use it I face some issues.

import {NG2_UI_AUTH_PROVIDERS} from 'ng2-ui-auth';

bootstrap(AppComponent, [
HTTP_PROVIDERS,
appRouterProviders,
NG2_UI_AUTH_PROVIDERS({
providers: {
oauth2: {
name: 'customauthprovider',
url: '/auth/custom',
clientId: 'abc',
redirectUri: window.location.origin,
authorizationEndpoint: CONFIGS.imsmartBaseUrl + 'oauth/authorize'
}
}
}),
]);

and my login component is

import {Component, OnInit, AfterContentInit, ElementRef, Renderer} from '@angular/core';
import {Auth} from 'ng2-ui-auth';
import {ROUTER_DIRECTIVES, Router} from '@angular/router';

@component({
selector: 'login-view',
templateUrl: 'app/login/login.component.html',
styleUrls: ['app/login/login.component.css']
})
export class LoginComponent implements OnInit, AfterContentInit {

constructor(
    private router: Router,
    private auth: Auth,
    private element: ElementRef,
    private renderer: Renderer ) {}

ngOnInit(){

}

ngAfterContentInit(){
    this.renderer.setElementClass(this.element.nativeElement, 'app', true);
    if (this.auth.isAuthenticated()) {
        this.navigateToSegments();
    }
}

authenticate(provider: string) {
  alert(provider);
    this.auth.authenticate(provider)
        .subscribe(() => this.navigateToSegments());
}

navigateToSegments() {
    let link = ['/segment'];
    this.router.navigate(link);
}

}

When I try it I got the following error
ng2-ui

And then I have tried to import the import {Oauth} from 'ng2-ui-auth';
but it give the following error on compile.

node_modules/ng2-ui-auth/dist/ng2-ui-auth"' has no exported member 'Oauth'.

I also try to change the ng2-ui-auth.d.ts file as well . but couldn't make it.

Can you help me to use it or customize it for a custom authentication provider. Thanks in advanced.

Twitter login tries to open local route of '/auth/twitter' instead of their api.twitter.com page

Whenever I call authenticate('twitter') it opens a popup window and tries to redirect to a local route of '/auth/twitter'. Is there some config I need to do for Twitter to work? I created an app on Twitter but am not sure where to connect it.

My Config file

import { CustomConfig } from 'ng2-ui-auth';

export class AuthConfig extends CustomConfig {
    defaultHeaders = {'Content-Type': 'application/json'};
    providers = {
    	google: {
    		clientId: '<replace me>'
    	},
    	facebook: {
    		clientId: '1675283336115039',
    		responseType: 'token'
    	}
    };
}

And then my call, where provider = 'twitter'

this.Auth.authenticate(provider).subscribe({
        error:(err: any) => {
        	console.log(err);
        },
        complete:() => {
        	console.log(this.Auth.getToken());
        	console.log(this.Auth.getPayload());
        }
    });

Change full url

How I can change the url to make the request with Twitter?

I use the URL param but just replace the path and keep the domain :( i need to make a request to other domain.

for example in the config:
twitter: { clientId: "XXXXX", redirectUri: "XXXX", url:"EXAMPLE.com" }

I get: localhost:3000/example.com

Using this library with AOT compiler

I'm trying to make my library AOT compatible without much success.
Currently you import my library like this:

NgModule({
    imports: [...],
    providers: [NG2_UI_AUTH_PROVIDERS(...)],
    declarations: [...],
    bootstrap: [...]
})
export class ClientModule {
}

But then I get: "Error encountered resolving symbol values statically. Function calls are not supported. Consider replacing the function or lambda with a reference to an exported function..."
I've tried doing something like this:

//in the library
@NgModule({
    imports: [HttpModule]
})
export class Ng2UiAuthModule {
    static getProviders(config: ICustomConfig): ModuleWithProviders {
        return {
            ngModule: Ng2UiAuthModule,
            providers: [{provide: Config, useValue: new Config(config)},
                Storage, Shared, JwtHttp, Oauth, Popup, Oauth1, Oauth2, Local, Auth
            ]
        };
    }
}
//in a different file
export const authModule = Ng2UiAuthModule.getProviders(...);
//in the main file
NgModule({
    imports: [..., authModule , ...],
    providers: [...],
    declarations: [...],
    bootstrap: [...]
})
export class ClientModule {}

But I get the same issue. What am I doing wrong here?

Question: userInfo object

Hi Ron,

Freaking LOVING your library mate, its great

I have a question for you. I could not find any implementation of a userInfo object that holds the signed in user's info.

by userInfo I mean globally avaliable object which has things like FirstName, lastName, Role, Email and stuff like that.

What would be good is so a dev could call this.auth.userInfo(); and get returned all that nice info.

Does this exist somewhere and I have missed it, or is it required to roll your own?

Add link to other social

Is it possible to link another social to a given profile ?
Let's imagine I logged with facebook.
Then later I would like to associate a linkedin or twitter to my profile. Is there a way ?

property missing in ICustomConfig?

Should ICustomConfig in ng2-ui-auth/declerations/config.d.ts define authHeader? It's implemeted in Config and the code uses it, but it's not in the interface and is causing errors for me. Thanks.

backend.createConnection is not a function

Hi again :)

I am trying to extend the JwtHttp class becuase I want to able to add some headers to all my requests + doSomething if any request fails. aswell I have added an overload to get and post methods that allow object as body and parameters instade of string

export class MyJwtHttp extends JwtHttp {
  constructor(private backend: ConnectionBackend, defaultOptions: RequestOptions, shared: Shared, config: Config) {
    super(backend, defaultOptions, shared, config);
  }

  request(url: string | Request, options?: RequestOptionsArgs): Observable<Response> {
    options = options || {};
    if (!options.headers) {
      options.headers = new Headers();
    }

    // TODO: expected error for
    options.headers.set('Content-Type', 'application/json;charset=UTF-8');
    return super.request(url, options)
    .catch((err, source, caught) => {
      return Observable.empty();
    })
  }

  post(url: string, data, options?: RequestOptionsArgs):Observable<Response>  {
    return super.post(url, (typeof(data) === 'string' ? data : JSON.stringify(data)), options);
  }

  get(url: string, params?: Object) : Observable<Response> {
    var args: URLSearchParams;
    if (params) {
      args = new URLSearchParams();
      for (let key in params) {
        args.set(key, params[key]);
      }
    }

    return super.get(url, args);
  }
}

Im my bootstrap:

export const MY_HTTP_PROVIDER = [
  ConnectionBackend,
  MyJwtHttp,
  provide(JwtHttp,{
      useFactory:
      (xhrBackend, requestOptions, shared, config, router) =>
      new MyJwtHttp(xhrBackend, requestOptions, shared, config),
      deps: [XHRBackend, RequestOptions, Shared, Config],
    }),
  BrowserXhr,
  provide(RequestOptions, {useClass: BaseRequestOptions}),
  provide(ResponseOptions, {useClass: BaseResponseOptions}),
  XHRBackend
];

Now when im doing some random request to my server I get
browser_adapter.js:76 ORIGINAL EXCEPTION: TypeError: backend.createConnection is not a function

any idea?

Thanks ahead!

Need some help, Getting Error : Response with status: 404 Not Found for URL: null

Hi,

i try to integrate this library and use in simple angular2 sample project

Tried facebook as provider, google as provider but same error

Error :Response with status: 404 Not Found for URL: null

  • Error happens when popup open and get authorized and redirect to
    localhost:3000 with code and other parameters and then popup get closed after that this error happened
  • i think this error is coming when exchangeForToken function is performed
    my data input for that functions is
exchangeForTokenUrl :/auth/facebook

data :{"name":"facebook","url":"/auth/facebook","authorizationEndpoint":"https://www.facebook.com/v2.5/dialog/oauth","redirectUri":"http://localhost:3000/","requiredUrlParams":["display","scope"],"scope":["email"],"scopeDelimiter":",","display":"popup","oauthType":"2.0","popupOptions":{"width":580,"height":400},"clientId":"31858675345345163593","defaultUrlParams":["response_type","client_id","redirect_uri"],"responseType":"code","responseParams":{"code":"code","clientId":"clientId","redirectUri":"redirectUri"},"code":"AQAtEQd-1C1i5PakhyPVbQhavKscKWF2Ba8WxDrMG7AiTBol0drimJr30nLfArAHVq9ogdfgdf0vOH1VtploWz29_derz-_Gn6T5EHmJWAoT_Gox756vs98GfH6KLYE2FvWmY-gif5JePO_9bTOAk1xBTO_iE8jR-ldn6PM4gsxUKIJMYmckolmWWqNSKXLosm-cxLM292-RRUG3OAcRqON7Pkg6uRU7ZE_yqqYzG1ecHpaoShTkc40xIHm3PMLJNJc4eAbSwM4atmUu9QC6BEitf9GIb8qTtJ9poyOfVkGK8eHuMHESZqSzNlHap5mKca-ghWEsad1WsMvgKm8BnqRJofyiq9","_":"_"}

i guess http post call in exchangeForToken function return this error.

i any idea

client app custom config

export class MyAuthConfig extends CustomConfig {
    defaultHeaders = {'Content-Type': 'application/json'};
    providers = {
      google: {
        clientId: GOOGLE_CLIENT_ID,
        url: '/auth/google',
        //redirectUri: 'http://localhost:3000'
      },
      facebook: {
        clientId: '318586755163593',
        url: '/auth/facebook',
        //redirectUri: 'http://localhost:3000'
      }
    };
}

onserver side i have /auth/google and /auth/facebook as post request which are going to do the rest stuff but i guess the whole process doesn't even reaching that part

for node server side i used the sample from (https://github.com/sahat/satellizer/tree/master/examples/server/node)

Refresh token when the request fails

When a request fails with a 401 ( user configurable maybe ? ) status, pause and / or remember all incoming failed responses and do a token refresh, after which redo all the request with a authorization header

This solves a problem that happens due to slight time differences between the server and the client ( a few seconds ).
The token can appear valid to the client, but the token is invalid to the server.

Authentication flow help

Hi guys,

This is not an issue but I really need help understanding how everything works with Github or any other provider..

Actually I installed the plugin and I did as mentionned in the README, so here is my code so far, which is only client-side :

import { Component, AfterContentInit } from '@angular/core';
import { ControlGroup, FormBuilder, Validators } from '@angular/common';
import { Router, ROUTER_DIRECTIVES } from '@angular/router';

import { Auth, NG2_UI_AUTH_PROVIDERS } from 'ng2-ui-auth';
import { AuthService } from '../../services/auth.service';
import { FormStateModel } from '../../models/form/form-state.model';
import { LoginRequestModel } from '../../models/auth/login-request.model';
import { FormInputTextComponent } from '../+shared/index';
import { FocusableDirective } from '../../directives/focusable.directive';

const DEFAULT_POST_HEADER: { [name: string]: string } = {
'Content-Type': 'application/json'
};
const GITHUB_CLIENT_ID = '##MY_GITHUB_ID##';

@component({
selector: 'login',
templateUrl: 'src/components/login/login.component.html',
providers: [
NG2_UI_AUTH_PROVIDERS({
defaultHeaders: DEFAULT_POST_HEADER,
providers: {
github: { clientId: GITHUB_CLIENT_ID }
}
})],
directives: [ROUTER_DIRECTIVES, FormInputTextComponent, FocusableDirective],
pipes: []
})

export class LoginComponent implements AfterContentInit {
formState: FormStateModel;
loginForm: ControlGroup;

private _loginRequest: LoginRequestModel;

constructor(private auth: Auth, private _formBuilder: FormBuilder, private _router: Router, private _authService: AuthService) {
    if (this._authService.isUserAuthorized()) {
        this._router.navigate(['/dashboard']);
    }

    this.formState = new FormStateModel();

    this.loginForm = this._formBuilder.group({
        'username': ['', Validators.required],
        'password': ['', Validators.required]
    });

    this.loginForm.valueChanges.subscribe(() => {
        this.formState.submitError = false;
    });
}

goToMain() {
    this._router.navigate(['/dashboard']);
}

authenticate(provider: string) {
    this.auth.authenticate(provider)
        .subscribe(() => () => this.goToMain(),
        (errorMessage: string) => {
            this.formState.submitting = false;
            this.formState.submitError = true;
            this.formState.submitErrorMessage = errorMessage;
        });
}

}

Github popup is shown but when I click on authorize application, I'm getting an error on my login page :

'SyntaxError: Unexpected token < in JSON at position 0'

So my questions are :

  • Why am i getting this error?
  • Do I have to implement a server-side and why, is it not possible to have only a client-side authentication ? Because I just want the user email from the provider and play with it after.

Thanks !

No error but not working

Hi,
I am using angular2.beta2 with this yeoman generator : https://github.com/dsebastien/modernWebDevGenerator

Then, I just add the import
import {JwtHttp} from "ng2-ui-auth";

From this point, without any other modification to the bootstrap app, I get this error in my js console:
GET http://localhost:3000/core/boot.js 404 (Not Found)fetchTextFromURL @ system.src.js:1068(anonymous function) @ system.src.js:1649lib$es6$promise$$internal$$initializePromise @ angular2-polyfills.js:1558lib$es6$promise$promise$$Promise @ angular2-polyfills.js:1849(anonymous function) @ system.src.js:1648(anonymous function) @ system.src.js:2670(anonymous function) @ system.src.js:3234(anonymous function) @ system.src.js:3501(anonymous function) @ system.src.js:4117(anonymous function) @ system.src.js:4325(anonymous function) @ system.src.js:4565(anonymous function) @ system.src.js:326run @ angular2-polyfills.js:138zoneBoundFn @ angular2-polyfills.js:111lib$es6$promise$$internal$$tryCatch @ angular2-polyfills.js:1511lib$es6$promise$$internal$$invokeCallback @ angular2-polyfills.js:1523lib$es6$promise$$internal$$publish @ angular2-polyfills.js:1494(anonymous function) @ angular2-polyfills.js:243run @ angular2-polyfills.js:138zoneBoundFn @ angular2-polyfills.js:111lib$es6$promise$asap$$flush @ angular2-polyfills.js:1305 angular2-polyfills.js:138 Error: XHR error (404 Not Found) loading http://localhost:3000/core/boot.js(…)

I don't have any error in my npm console. It looks like that when I add the import, something goes wrong and my app doesn't even start (as it does not find boot.js for some reason)
Any idea where this comes from?

Only text/plain ?

Hey !

Firstly Thanks for your work !

However, i have got an issue:
My server receives only request with Content-Type: 'text/plain'.

This is my code :

const DEFAULT_POST_HEADER: {[name: string]: string} = {
  'Content-Type': 'application/json',
  'Accept': 'application/json'
};

bootstrap(AppComponent, [
  provide(APP_BASE_HREF, {useValue : '/' }),
  APP_ROUTER_PROVIDERS,
  HTTP_PROVIDERS,
  ANGULAR2_GOOGLE_MAPS_PROVIDERS,
  NG2_UI_AUTH_PROVIDERS({
    providers: {
      facebook: {
        clientId: FACEBOOK_CLIENT_ID,
        url: 'http://localhost:8080/auth/facebook'
      },
      defaultHeaders: DEFAULT_POST_HEADER
  }})
]);

Do you know where am i wrong ?

Thanking in advance.

Set `authenticate` post headers to use 'application/json'

I've added support to my API for plain/text in order to handle requests from the oAuth2 class in the library. I'd like to send my requests as 'application/json'. With the login and signup methods, I'm able to pass headers into the options parameter, which is how I was working with those methods. I looked through the code, but it didn't look like this is possible with the authenticate method. Is there a way to set the post headers to 'application/json', or is it currently not possible?

Fix for JwtHttp class

Hi, this is fix for JwtHttp class, when your url var it not a String objects

if (url instanceof Request) {
    url.headers = url.headers || new Headers();
    url.headers.set(this._config.authHeader, this._config.authToken + ' ' + this._shared.getToken());
} else {
    options.headers = options.headers || new Headers();
    options.headers.set(this._config.authHeader, this._config.authToken + ' ' + this._shared.getToken());
}

like here

return this.jwtHttp.request(new Request({
    method: RequestMethod.Get,
    url: '/api',
    search: this._getUrlParams(params)
})).toPromise();

I do not make a "Pull Request" because my fork https://github.com/davintoo/ng2-ui-auth was heavily modified

Add state to optionalUrlParams

Add 'state' to the default config.ts. e.g. The default google provider should be

google: {
            name: 'google',
            url: '/auth/google',
            authorizationEndpoint: 'https://accounts.google.com/o/oauth2/auth',
            redirectUri: window.location.origin,
            requiredUrlParams: ['scope'],
            optionalUrlParams: ['display', 'state'],
            scope: ['profile', 'email'],
            scopePrefix: 'openid',
            scopeDelimiter: ' ',
            display: 'popup',
            type: '2.0',
            popupOptions: {width: 452, height: 633}
}

Facebook clientId is not returned to local server

Doing Oauth2 with Facebook. I've verified through the debugger that the Oauth2 class is starting the exchange w/Facebook correctly and passing my clientId to them.

However, when the popup window receives the Facebook response and sends it to my server, the clientId is not sent to my server, so it fails to get a token.

The server is working w/Satellizer and our existing Angluar 1 app. Having a hard time debugging the code that is running inside the pop up window, so this is as far as I got.

Sorry I can't be much more help, but am happy to help out in any way I can ... I think I might need some direction w/this one.

Pass additional parameters for different authentications

Is there a way to pass additional parameters for different authentications? e.g.:

// default
return this.auth.authenticate(provider)
// authenticate with different parameters
return this.auth.authenticate(provider, {}, { state: 'different parameters' })

ng2-ui-auth.js not found

Hey there,

First of all thanks for converting this library. I'm having some troubles where system.js isn't loading ng2-ui-auth.

In my login.ts I have,

import {Component, View, AfterContentInit, ElementRef, Renderer} from 'angular2/core';
import {Router, ROUTER_DIRECTIVES} from 'angular2/router';
import {FormBuilder, ControlGroup, Validators} from 'angular2/common';

import {Auth} from 'ng2-ui-auth';

and in my bootstrap.ts I have,

import {NG2_UI_AUTH_PROVIDERS, JwtHttp} from 'ng2-ui-auth';

bootstrap(App, [
   ...
    NG2_UI_AUTH_PROVIDERS({
        providers: {
            google: {
                clientId: GOOGLE_CLIENT_ID
            },
            facebook: {
                clientId: FACEBOOK_CLIENT_ID
            }
        }
    }),
    JwtHttp,
    ...
]);

It's also in my dependencies,

  "dependencies": {
    "angular2": "2.0.0-beta.1",
   ...
    "systemjs": "0.19.6",
    "ng2-ui-auth": "~1.0.12"
  },

I'm using Typescript as my compiler. Am I suppose to somehow manually include the library in my index.html?

Thanks in advance,
H.

ng2-ui-auth cant be found

Hi Rod,

I went through the process of doing a 'clean as possible' install of ng2-ui-auth but browser console complains that ng2-ui-auth cannot be found.

Here is what I did. I cloned a fresh copy of the angular starter from Angular.io which includes all the up to date goodies.

I installed, and run, worked great.

I did an npm install ng2-ui-auth --save, all looks well, package came down sweet.

In my main.ts I setup like so

import { bootstrap } from '@angular/platform-browser-dynamic';
import {provide} from '@angular/core';
import {HTTP_PROVIDERS} from '@angular/http';
import {NG2_UI_AUTH_PROVIDERS, JwtHttp} from 'ng2-ui-auth';
import { AppComponent } from './app.component';

const DEFAULT_POST_HEADER: {[name: string]: string} = {
'Content-Type': 'application/json'
};
const GOOGLE_CLIENT_ID = '******************************.apps.googleusercontent.com';

bootstrap(AppComponent, [
HTTP_PROVIDERS,
NG2_UI_AUTH_PROVIDERS({defaultHeaders: DEFAULT_POST_HEADER, providers: {google: {clientId: GOOGLE_CLIENT_ID}}}),
]);

tried to run and bang this is where I hit trouble,

Failed to load resource: the server responded with a status of 404 (Not Found) http://localhost:3000/ng2-ui-auth

Any ideas?

Cheers

How to specify the scope

Hello.
Just a question. Is there a way to specify easily the scope for the facebook access.
Here from what I can see in the code we have scope email and public profile.
Can we specify more by overriding something like friend list photos etc ?
Thanks for your project. I was fastly able to implement connection to facebook LinkedIn :)

Documentation

There needs to be more documentation on how to use this library as the libs themselves and the example/sample seem to be out of sync in terms of usage meaning that it's not clear on how everything ties together.

Error - No provider for Auth !

Hi,

An error occurred while authenticating and I have no idea why... It is the same code as you use on your ng2-ui-auth-example :

sans titre

Here is my DashboardComponent :

`import { Auth, JwtHttp } from 'ng2-ui-auth';
import { ROUTER_DIRECTIVES, Router } from '@angular/router';
import { Component } from '@angular/core';
import { Observable } from 'rxjs/Rx';
import { TranslatePipe } from 'ng2-translate';

@component({
selector: 'app-overview',
templateUrl: '../views/dashboard.html',
directives: [ROUTER_DIRECTIVES],
pipes: [TranslatePipe]
})

export class DashboardComponent {
userName: Observable;

constructor(private _auth: Auth,
    private _router: Router,
    private _jwtHttp: JwtHttp) {
    this.userName = _jwtHttp.get('/api/userName').map((response) => response.text());
}

goToLogin() {
    this._router.navigate(['/login']);
}

logout() {
    this._auth.logout().subscribe(() => {
        this.goToLogin();
    })
}

}`

Unable to overwrite default vars in Customconfig

I'm trying to overwrite loginUrl var in the CustomConfig object with no success. I've followed the example in the demo app but it's not working. Below my code:

export class MyAuthConfig extends CustomConfig {
  loginUrl: 'https://aaaaaaa';
}

Any help would be appreciated.

Thanks

Login with facebook in production with cordova app

Hi

Im trying to create a login with facebook, with my ionic app.
The thing is that everything is working good when I test it on the browser.
But when im running it on a device im having some issues with the redirect URL.

  1. I have no idea what to write there.
  2. If I write something I do not get redirect to back to the application.

I have tried to put https://www.facebook.com/connect/login_success.html as a redirect url. both in the application and in facebook console.
the thing is that I do not get redirect back the application thus in my login screen.

Any idea?

Oauth1 configuration values are all null

Line 26 in Oauth1 sets all the configuration values to null because it is copying the values from an object that has all null values.

So regardless of what I pass in as options (for Twitter), they are all null so authenticating doesn't work.

I'd submit a PR but am still getting familiar w/the code :) I assume that somehow the Oauth1.base object should be populated w/the default values for my provider, and then extend that w/my custom options?

If you don't have time to look into it, maybe you could nudge me in the right direction :)

Thanks for your awesome work in porting this to Angular2.

OAuth 1.0a help

Hi, thanks for the effort.

I've been trying to get a simple 3-legged OAuth 1.0a example up and running, and been kinda lost.

3-legged OAuth 1 requires 3 steps, first sending your oauth_consumer_key and oauth_signature to a "request" url, to get the oauth_token and oauth_token_secret back. I cant, however, figure out where to enter these parameters in the config.

I humbly ask for a simple OAuth 1 example. Maybe against twitter.

Ps. This is in the context of an Ionic 2 setup btw.

Can I call my custom OAuth2 providers?

Hi at all,

first sorry for this thread but I'm new in Angular 2.

I had with satellizer the below configuration:

$authProvider.oauth2({
        name: 'manual',
        url: '/oauth/token',
        responseType: 'code',
        responseParams: {
            data: {
                access_token: 'access_token',
                refresh_token: 'refresh_token',
                expires_in: 'expires_in',
                roles: 'roles'
            }
        }
    });
    $authProvider.loginUrl = PROVIDER.host + '/uaa/oauth/token';
    $authProvider.tokenName = 'access_token';
    $authProvider.authHeader = 'Authorization';
    $authProvider.authToken = 'Bearer';

Your work was great with this porting but I didn't understand how I could call my custom OAuth2 implementation.

Thanks in advance,
Massimiliano

config for API running on different url or port

Hi Ronz,

I was in process of doing more experimentation, and can't find any place where there is a central constant for a different backend api url or port.

Is there one? And Im just missing it. It looks to me like the library will send back to same url and port all the time 'localhost:3000'

But what if a person is using http://localhost:5000 for instance for a backend api. Is there one place I can enter this constant and API calls will go to this url?

Cheers

No provider for String!

@ronzeidman love what you've done here to port to Angular 2, but unfortunately, I cannot get things quite working. I keep running into errors with my providers. Any help would be greatly appreciated.

Here's a partial screenshot of the errors I'm seeing, with my code below:

screenshot from 2016-05-25 12-09-56

Here's what my component code looks like:

import { Component } from '@angular/core';
import {FormBuilder, ControlGroup, Validators} from '@angular/common';
import { Auth } from 'ng2-ui-auth';
import { NG2_UI_AUTH_PROVIDERS, JwtHttp } from 'ng2-ui-auth';

const DEFAULT_POST_HEADER: {[name: string]: string} = {
    'Content-Type': 'application/json'
};
const FACEBOOK_CLIENT_ID = 'XXXXXXXX';

@Component({
  selector: 'login',  // <login></login>
  providers: [ NG2_UI_AUTH_PROVIDERS({defaultHeaders: DEFAULT_POST_HEADER, providers: {facebook: {clientId: FACEBOOK_CLIENT_ID}}})

  ],
  directives: [
  ],
  pipes: [ ],
  styles: [ require('./login.css') ],
  template: `
    <button (click)="authenticate('facebook')">
      Authenticate with Facebook
    </button>
  `
})
export class Login {

  constructor(private auth: Auth, private error: string) {
    this.error = "It did not work";
  }

  authenticate(provider: string) {
    this.auth.authenticate(provider)
      .subscribe(
        () => this.itWorked(),
        () => this.itDidNotWork()
      );
  }

  itWorked() {
    alert("It worked!");
  }

  itDidNotWork() {
    alert("It did not work!");
  }
  ngOnInit() {
    console.log('hello `Login` component');
    // this.title.getData().subscribe(data => this.data = data);
  }
}

line 21 in local.ts prevent sending request with the user data in the body.

Hi, thanks for this lib, I'm trying to use for authentication but the line 21 in the local.ts file is preventing me from doing that my use case is to send a POST request to the back-end with the content-type of application/x-www-form-urlencoded and with the user data in the body, so I tried doing that by passing false instead of the user and the data in the second opts param, but the request was rejected because it was sent with false as params since the line 21 is:

opts.body = JSON.stringify(user) || opts.body;

so opts.body will be either the JSON.stringify(user) if the user is provided or JSON.stringify(false) which is not false it is the string "false" meaning the opts.body if it was passed it will never be used since JSON.stringify(false) is never false so to fix that:

opts.body = user ? JSON.stringify(user) : opts.body;

But, if I can give you a suggesting I would say make the whole function like this:

login(opts: any = {}, user: any = {}): Observable<Response> {
  let url: string;
  if (typeof opts === 'string') {
    url    = opts;
    opts = {};
  } else {
    url = opts.url ? opts.url : joinUrl(this.config.baseUrl, this.config.loginUrl);
  }
  opts.body = opts.body || JSON.stringify(user);
  opts.method = opts.method || 'POST';
  /*opts.headers = new Headers({
    'Content-Type': 'application/json'
  });*/
  return this.http.request(url, opts)
                  .map((response: Response) => {
                    this.shared.setToken(response);
                    return response;
                  });
}

this way you can call the login function in multiple cases without having to put false as the first parameter like this:

this.auth.login('/signin', user).subscribe((response) => this.goToMain(response));
// or
let options: RequestOptionsArgs = {
  method: 'POST',
  headers: headers,
  url: '/signin',
  body: user
};
this.auth.login(options).subscribe((response) => this.goToMain(response));
// or
let options: RequestOptionsArgs = {body: user};
this.auth.login(options).subscribe((response) => this.goToMain(response));
// or
let options: RequestOptionsArgs = {body: user, headers: headers};
this.auth.login('/signin', options).subscribe((response) => this.goToMain(response));

**Note:** keep in mind that all the options passed to the login function are optional since they have default values.
Sorry for a long issue, and thanks again.

Deploy JavaScript on build

First of all, thanks for sharing your conversion. I expect it to be useful to many others.

For it to be widely adopted the compiled JavaScript needs to be published, since TypeScript is not a requirement for working with Angular2.

I'd recommend TravisCI for the build, calling into a script in the package.json, and then pushing to npm. Optionally pushing back into github as well.

error with PopupService

https://github.com/ronzeidman/ng2-ui-auth/blob/master/src/oauth2.service.ts#L67 in this line you return oauthData returned from the server as it is in my case, it's throw exception because date type not observable i work around it by creating class that extend PopupService

import { PopupService } from 'ng2-ui-auth';
import { Observable } from 'rxjs/Observable';

/**
 * wrapper of Ng2UiAuthModule to handle our way in auth
 */
export class CustomPopupService extends PopupService {
    pollPopup() {
        return super.pollPopup().map(data => {
            if (data instanceof Observable) return data;
            return Observable.of(data);
        });
    };
}

here you can find the error

TypeError: unknown type returned
    at Object.subscribeToResult (http://localhost:3000/vendor.bundle.js:10490:28)
    at MergeMapSubscriber._innerSub (http://localhost:3000/vendor.bundle.js:30879:39)
    at MergeMapSubscriber._tryNext (http://localhost:3000/vendor.bundle.js:30876:15)
    at MergeMapSubscriber._next (http://localhost:3000/vendor.bundle.js:30859:19)
    at MergeMapSubscriber.Subscriber.next (http://localhost:3000/vendor.bundle.js:10221:19)
    at DoSubscriber._next (http://localhost:3000/vendor.bundle.js:58225:31)
    at DoSubscriber.Subscriber.next (http://localhost:3000/vendor.bundle.js:10221:19)
    at TakeWhileSubscriber.nextOrComplete (http://localhost:3000/vendor.bundle.js:61259:26)
    at TakeWhileSubscriber._next (http://localhost:3000/vendor.bundle.js:61254:15)
    at TakeWhileSubscriber.Subscriber.next (http://localhost:3000/vendor.bundle.js:10221:19)
    at TakeSubscriber._next (http://localhost:3000/vendor.bundle.js:61049:31)
    at TakeSubscriber.Subscriber.next (http://localhost:3000/vendor.bundle.js:10221:19)
    at MergeMapSubscriber.notifyNext (http://localhost:3000/vendor.bundle.js:30892:31)
    at InnerSubscriber._next (http://localhost:3000/vendor.bundle.js:52466:22)
    at InnerSubscriber.Subscriber.next (http://localhost:3000/vendor.bundle.js:10221:19)
    at Object.subscribeToResult (http://localhost:3000/vendor.bundle.js:10447:26)
    at MergeMapSubscriber._innerSub (http://localhost:3000/vendor.bundle.js:30879:39)
    at MergeMapSubscriber._tryNext (http://localhost:3000/vendor.bundle.js:30876:15)
    at MergeMapSubscriber._next (http://localhost:3000/vendor.bundle.js:30859:19)
    at MergeMapSubscriber.Subscriber.next (http://localhost:3000/vendor.bundle.js:10221:19)
    at AsyncAction.IntervalObservable.dispatch (http://localhost:3000/vendor.bundle.js:54953:21)
    at AsyncAction._execute (http://localhost:3000/vendor.bundle.js:29070:19)
    at AsyncAction.execute (http://localhost:3000/vendor.bundle.js:29045:27)
    at AsyncScheduler.flush (http://localhost:3000/vendor.bundle.js:29142:33)
    at ZoneDelegate.invokeTask (http://localhost:3000/polyfills.bundle.js:7477:38)
    at Object.onInvokeTask (http://localhost:3000/vendor.bundle.js:6425:42)
    at ZoneDelegate.invokeTask (http://localhost:3000/polyfills.bundle.js:7476:43)
    at Zone.runTask (http://localhost:3000/polyfills.bundle.js:7377:48)
    at ZoneTask.invoke (http://localhost:3000/polyfills.bundle.js:7545:34)

ng2-ui-auth.js not found

Hey there,

First of all thanks for converting this library.

Update

I'm now getting the error http://10.0.0.135:3000/rxjs.js 404 (Not Found) system.src... when including the library like so:

System.config({
    packages: {
        app: {
            defaultExtension: 'js'
        },
        'node_modules': {
            defaultExtension: 'js'
        }
    },
    map: {
        'angular2-jwt': 'node_modules/angular2-jwt/angular2-jwt.js',
        'ng2-ui-auth': 'node_modules/ng2-ui-auth/export.js',
    }
});

I already do have rx included

<script src="/node_modules/rxjs/bundles/Rx.js"></script>

And I only get the error when including ng2-ui-auth

Update to version 4

After update to version 4 and tried to follow the instructions to extend the CustomConfig I'm get this error message in my building process.

client/src/app/config/auth-config.service.ts(3,14): error TS2415: Class 'MyAuthConfig' incorrectly extends base class 'CustomConfig'.
  Types of property 'providers' are incompatible.
    Type '{ google: { clientId: string; }; }' is not assignable to type 'IProviders'.
      Index signature is missing in type '{ google: { clientId: string; }; }'.

This is my auth settings class

import { CustomConfig } from 'ng2-ui-auth';

export class MyAuthConfig extends CustomConfig {
    baseUrl = 'http://localhost:3000';
    defaultHeaders = { 'Content-Type': 'application/json' };
    tokenPrefix = 'locaoffice';
    loginUrl =  '/api/sessions';
    signupUrl = '/api/users';
    providers = {google: {clientId: ''}};
}

I don't know where is the problem.

injectin `Auth` require is not defined

Hi.

First of all thanks for the lib :)

So Im workign with ionic 2 and this is what i get when I inject 'Auth`:
(working with ionic 2 and webpack)

ng2-ui-auth.js:1278 Uncaught ReferenceError: require is not defined(anonymous function) @ ng2-ui-auth.js:1278(anonymous function) @ ng2-ui-auth.js:1(anonymous function) @ ng2-ui-auth.js:1277__webpack_require__ @ bootstrap 0a4995e…:19(anonymous function) @ authenticationApi.ts:2__webpack_require__ @ bootstrap 0a4995e…:19(anonymous function) @ authenticationService.ts:3__webpack_require__ @ bootstrap 0a4995e…:19(anonymous function) @ login.ts:6__webpack_require__ @ bootstrap 0a4995e…:19(anonymous function) @ app.ts:3__webpack_require__ @ bootstrap 0a4995e…:19(anonymous function) @ bootstrap 0a4995e…:39__webpack_require__ @ bootstrap 0a4995e…:19(anonymous function) @ bootstrap 0a4995e…:39(anonymous function) @ bootstrap 0a4995e…:39

tokenRoot setting

Hello!

Great job with this. But I found a problem. My server always returns....
{ "error":false, "message":"signin-ok", "data":{ "token":"*******" }, "statusCode":200 }

I also set tokenRoot in config to data (tokenRoot = 'data';)

I Always get on error, because token is not set in root response.
I think you should improve a line in setToken function to something like this:
var accessToken = response && response.json() && (response.json().access_token || response.json().token || response.json()[this.config.tokenRoot].token);

Thank you!

Google Auth Popup Window does not close

The popup window does not close for me after successful authorization.
The token response is received, and the user is authorized.

No errors seen in the console.

I know we build differently, was wondering if the popup auto-closed for you like it should.
You can see my app here http://chad-autry.github.io/ng2bp I will continue to investigate.

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.