我有一个问题是找到为我的angular 2应用程序进行身份验证的方法。我在laravel中有API,并尝试使用laravel passport(通过密码授权)。我在邮差上测试了它,现在我需要用角度连接它。我已经开始寻找一些图书馆了,但我只找到了https://github.com/manfredsteyer/angular-oauth2-oidc
您对如何连接这个有什么想法吗?我无法应付这一点。
答案 0 :(得分:1)
您可以像这样开展服务,不要忘记分配客户端ID和密码。
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: "albanafmeti@gmail.com",
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'));
}
}
&#13;
并将此服务用于此类其他组件
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);
});
}
}
&#13;