3

I have a problem to find way to make authentication for my angular 2 app. I have API in laravel, and tried to use laravel passport(via password grant). I tested it on Postman and now I need to connect it with angular. I've started looking for some library to do it, but i find only this https://github.com/manfredsteyer/angular-oauth2-oidc

Do you have any ideas on how to connect this? I can not cope with that.

1 Answer 1

1

You can make service like this , don't forget to assign the client id and secret.

userservice.ts

import {Injectable} from '@angular/core';
import {Observable} from 'rxjs/Rx';
import {Http, Headers, Response} from '@angular/http';
import {User} from './user';


@Injectable()
export class UserService {

    constructor(private http: Http) {
    }

    private oauthUrl = "http://server.techalin.com/oauth/token";
    private usersUrl = "http://server.techalin.com/api/users";

    getAccessToken() {
        var headers = new Headers({
            "Content-Type": "application/json",
            "Accept": "application/json"
        });

        let postData = {
            grant_type: "password",
            client_id: 2,
            client_secret: "RGNmOzt7WQ8SdNiCcJKKDoYrsFqI2tudopFjOJU3",
            username: "[email protected]",
            password: "password",
            scope: ""
        }

        return this.http.post(this.oauthUrl, JSON.stringify(postData), {
            headers: headers
        })
            .map((res: Response) => res.json())
            .catch((error: any) => Observable.throw(error.json().error || 'Server error'));
    }

    getUsers(accessToken: string): Observable<User[]> {

        var headers = new Headers({
            "Accept": "application/json",
            "Authorization": "Bearer " + accessToken,
        });

        return this.http.get(this.usersUrl, {
            headers: headers
        })
            .map((res: Response) => res.json())
            .catch((error: any) => Observable.throw(error.json().error || 'Server error'));
    }
}

and use this service to other component like this

  import 'UserService' from './user.service';
  export class ExampleCompoent{
  constructor(private userService: UserService) {
        this.userService.getAccessToken()
            .subscribe(data => {
                this.getUsers(data.access_token)
            });
    }

    getUsers(accessToken: string) {
        this.userService.getUsers(accessToken)
            .subscribe(
                users => {
                    this.users = users;
                    console.log(users);
                });
    }
    }
read more on this link

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.