Tomasz Cysewski
Tomasz Cysewski

Reputation: 661

How to implement oauth2 in angular2 with rest api?

I implement oauth2 in angular2 with rest api. Backend developer gave me these data, and login data.

private OauthLoginEndPointUrl = 'http://localhost:8000/oauth/token';  

private clientId ='2';

private clientSecret ='fsdfasdfaasdfasdfadsasdfadsfasdf';

How do I connect with backend, using password grant? He is using laravel passwort

I followed this tutorial but it seems to be outdated

my login

<h1>Login</h1>
<form role="form" (submit)="login($event, username.value, password.value)">
  <div class="form-group">
    <label for="username">Username</label>
    <input type="text" #username class="form-control" id="username" placeholder="Username">
  </div>
  <div class="form-group">
    <label for="password">Password</label>
    <input type="password" #password class="form-control" id="password" placeholder="Password">
  </div>
  <button type="submit" class="btn btn-primary btn-block btn-large">Submit</button>
</form>

logincomponent

      login(event, username, password) {

    event.preventDefault();
    this.loginService.login(username, password)
      .subscribe(
        response => {
          console.log("x");
          localStorage.setItem('token', response.access_token);
          this.router.navigate(['/home']);
        },
        error => {
          alert(error);
        }
      );
  }

login.service

import { Injectable } from '@angular/core';
import { Http , URLSearchParams , Response  } from '@angular/http';
import { Observable } from 'rxjs/Rx';


@Injectable()
export class LoginService {
  private OauthLoginEndPointUrl = 'http://localhost:8000/oauth/token';  // Oauth Login EndPointUrl to web API
  private clientId ='2';
  private clientSecret ='A4iX0neXv4LCwpWf0d4m9a8Q78RGeiCzwqfuiezn';

  constructor(public http: Http) {}

  login(username, password) : Observable {
    console.log("obs");
    let params: URLSearchParams = new URLSearchParams();
    params.set('username', username );
    params.set('password', password );
    params.set('client_id', this.clientId );
    params.set('client_secret', this.clientSecret );
    params.set('grant_type', 'password' );

    return this.http.get(this.OauthLoginEndPointUrl , {
      search: params
    }).map(this.handleData)
      .catch(this.handleError);
  }

  private handleData(res: Response) {
    let body = res.json();
    return body;
  }

  private handleError (error: any) {
    // In a real world app, we might use a remote logging infrastructure
    // We'd also dig deeper into the error to get a better message
    let errMsg = (error.message) ? error.message :
      error.status ? `${error.status} - ${error.statusText}` : 'Server error';
    console.error(errMsg); // log to console instead
    return Observable.throw(errMsg);
  }

  public logout() {
    localStorage.removeItem('token');
  }
}

Upvotes: 2

Views: 13519

Answers (2)

rgk
rgk

Reputation: 810

Try this. In Component

login() {

this
 .authService
 .login()
 .subscribe(
   (success) => {
     // do whatever you want with success response here

   },
   (error) => {
     // handle error here
   })

}

In authService:

login() : observable {

return 
   this
    .http
    .get(OauthLoginEndPointUrl, {clientId, clientSecret })
    .map((data) => {
      return data.json();
    })
    .catch(error)

}

Upvotes: 1

AngularChef
AngularChef

Reputation: 14087

Here's an outline of the steps you need to take:

  1. In your Angular app, create a "Log In" link sending the user to http://localhost:8000/oauth/token?client_id=2 (the exact syntax for the URL depends on YOUR backend...).

  2. The user sees an authorization prompt ("Allow access...?"). They can either click "Allow" or "Deny". If they click "Allow," the service redirects the user back to your site with an auth code, something like http://localhost:4200/cb?code=AUTH_CODE_HERE. Note that the URL is now the URL of your Angular app (in Angular you can access the ?code= URL param with this.route.snapshot.queryParams['code']).

  3. Finally, you HTTP POST the auth code you have received to another URL in your backend to exchange it for a token, e.g. http.post('http://localhost:8000/oauth/token', JSON.stringify({code: AUTH_CODE_HERE}))

This code should not be used verbatim, this is just an outline. Adapt it to YOUR backend and check out https://aaronparecki.com/oauth-2-simplified/ for in-depth info.

SIDE NOTE. The URLs used in #1 and #3 are usually different. The first URL is to obtain the auth code, and the other URL is to exchange the auth code for a token. Strange that your backend developer only gave you one URL.

Upvotes: 2

Related Questions