我使用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