import { HttpClientModule } from '@angular/common/http';
@NgModule({
imports: [
BrowserModule,
HttpClientModule
],
...
})
export class AppModule { }
import { HttpClient, HttpHeaders } from '@angular/common/http';
@Injectable({
providedIn: 'root'
})
export class GithubAuthService {
private scopes = ['user', 'repo'];
private clientId = 'YOUR_CLIENT_ID';
private clientSecret = 'YOUR_CLIENT_SECRET';
private redirectUri = 'http://localhost:4200/auth/callback';
constructor(private http: HttpClient) {}
requestAccessToken(code: string): Observable {
const headers = new HttpHeaders({
'Content-Type': 'application/json'
});
const body = {
code,
client_id: this.clientId,
client_secret: this.clientSecret
};
return this.http.post('https://github.com/login/oauth/access_token',
JSON.stringify(body), { headers, responseType: 'text' });
}
}
在 Github 的 OAuth 应用设置中添加重定向 URI。在本例中为 'http://localhost:4200/auth/callback'。
在 Angular 应用中添加一个 callback 页面来接收 Github 返回的 code。本例中为 'http://localhost:4200/auth/callback'。
import { Component, OnInit } from '@angular/core';
import { ActivatedRoute } from '@angular/router';
import { GithubAuthService } from '../github-auth.service';
@Component({
selector: 'app-auth-callback',
template: '',
})
export class AuthCallbackComponent implements OnInit {
constructor(private route: ActivatedRoute,
private githubAuthService: GithubAuthService) {}
ngOnInit() {
this.route.queryParams.subscribe(params => {
const code = params['code'];
this.githubAuthService.requestAccessToken(code).subscribe(response => {
const token = this.extractToken(response);
localStorage.setItem('access_token', token);
});
});
}
private extractToken(body: string): string {
const matches = body.match(/access_token=(.*?)&/);
return matches ? matches[1] : null;
}
}