我使用rest api在angular2中实现了oauth2。后端开发人员给了我这些数据和登录数据。如何使用rest api在angular2中实现oauth2?
private OauthLoginEndPointUrl = 'http://localhost:8000/oauth/token';
private clientId ='2';
private clientSecret ='fsdfasdfaasdfasdfadsasdfadsfasdf';
如何使用密码授权连接后端?他是用laravel passwort
我跟着this tutorial但它似乎已经过时
我登录
<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');
}
}
我需要使用“可用于访问令牌直接交换用户名和密码,密码交付式。”不是用户允许他授权的应用程序 –
在这种情况下,在步骤#1中,不是直接将用户带到URL,而是向用户显示用户名/密码表单,并将他在表单到URL。 – AngularChef