1. 概述
在本教程中,我們將繼續我們的 Spring Security OAuth 系列,通過構建 Authorization Code 流的簡單前端來完成。
請注意,這裏重點在於客户端;請參考 Spring REST API + OAuth2 + AngularJS 的文章,以瞭解 Authorization 和 Resource Server 的詳細配置。
2. 授權服務器
在深入瞭解我們的前端之前,我們需要在授權服務器配置中添加客户端詳細信息:
@Configuration
@EnableAuthorizationServer
public class OAuth2AuthorizationServerConfig extends AuthorizationServerConfigurerAdapter {
@Override
public void configure(ClientDetailsServiceConfigurer clients) throws Exception {
clients.inMemory()
.withClient("fooClientId")
.secret(passwordEncoder().encode("secret"))
.authorizedGrantTypes("authorization_code")
.scopes("foo", "read", "write")
.redirectUris("http://localhost:8089/")
...請注意我們現在啓用了 Authorization Code 授權類型,以下是一些簡單的配置詳情:
- 我們的客户端 ID 是 fooClientId
- 我們的權限範圍包括 foo, read和 write
- 重定向 URI 是 http://localhost:8089/ (我們將使用端口 8089 用於我們的前端應用)
3. 前端
現在,讓我們開始構建我們的簡單前端應用程序。
由於我們將使用 Angular 6 作為我們的應用程序,因此我們需要在我們的 Spring Boot 應用程序中使用 frontend-maven-plugin 插件:
<plugin>
<groupId>com.github.eirslett</groupId>
<artifactId>frontend-maven-plugin</artifactId>
<version>1.6</version>
<configuration>
<nodeVersion>v8.11.3</nodeVersion>
<npmVersion>6.1.0</npmVersion>
<workingDirectory>src/main/resources</workingDirectory>
</configuration>
<executions>
<execution>
<id>install node and npm</id>
<goals>
<goal>install-node-and-npm</goal>
</goals>
</execution>
<execution>
<id>npm install</id>
<goals>
<goal>npm</goal>
</goals>
</execution>
<execution>
<id>npm run build</id>
<goals>
<goal>npm</goal>
</goals>
<configuration>
<arguments>run build</arguments>
</configuration>
</execution>
</executions>
</plugin>請注意,首先需要在我們的環境中安裝 Node.js ;我們將使用 Angular CLI 為我們的應用程序生成基礎:
ng new authCode
4. Angular 模塊
現在,我們來詳細討論我們的 Angular 模塊。
以下是我們的簡單 AppModule:
import { BrowserModule } from '@angular/platform-browser';
import { NgModule } from '@angular/core';
import { HttpClientModule } from '@angular/common/http';
import { RouterModule } from '@angular/router';
import { AppComponent } from './app.component';
import { HomeComponent } from './home.component';
import { FooComponent } from './foo.component';
@NgModule({
declarations: [
AppComponent,
HomeComponent,
FooComponent
],
imports: [
BrowserModule,
HttpClientModule,
RouterModule.forRoot([
{ path: '', component: HomeComponent, pathMatch: 'full' }], {onSameUrlNavigation: 'reload'})
],
providers: [],
bootstrap: [AppComponent]
})
export class AppModule { }我們的模塊由三個組件和一個服務組成,將在後續部分進行詳細討論。
4.1. App 組件
讓我們從我們的 AppComponent 開始,它是根組件:
import {Component} from '@angular/core';
@Component({
selector: 'app-root',
template: `<nav class="navbar navbar-default">
<div class="container-fluid">
<div class="navbar-header">
<a class="navbar-brand" href="/">Spring Security Oauth - Authorization Code</a>
</div>
</div>
</nav>
<router-outlet></router-outlet>`
})
export class AppComponent {}4.2. 主組件
接下來是我們的主組件,HomeComponent:
import {Component} from '@angular/core';
import {AppService} from './app.service'
@Component({
selector: 'home-header',
providers: [AppService],
template: `<div class="container" >
<button *ngIf="!isLoggedIn" class="btn btn-primary" (click)="login()" type="submit">Login</button>
<div *ngIf="isLoggedIn" class="content">
<span>Welcome !!</span>
<a class="btn btn-default pull-right"(click)="logout()" href="#">Logout</a>
<br/>
<foo-details></foo-details>
</div>
</div>`
})
export class HomeComponent {
public isLoggedIn = false;
constructor(
private _service:AppService){}
ngOnInit(){
this.isLoggedIn = this._service.checkCredentials();
let i = window.location.href.indexOf('code');
if(!this.isLoggedIn && i != -1){
this._service.retrieveToken(window.location.href.substring(i + 5));
}
}
login() {
window.location.href = 'http://localhost:8081/spring-security-oauth-server/oauth/authorize?response_type=code&client_id=' + this._service.clientId + '&redirect_uri='+ this._service.redirectUri;
}
logout() {
this._service.logout();
}
}請注意:
- 如果用户未登錄,只會顯示登錄按鈕
- 登錄按鈕會將用户重定向到授權 URL
- 當用户被重定向迴帶有授權碼時,我們使用該碼檢索訪問令牌
4.3. Foo 組件
我們的第三個也是最後一個組件是 FooComponent;它顯示了從資源服務器獲取的 Foo 資源:
import { Component } from '@angular/core';
import {AppService, Foo} from './app.service'
@Component({
selector: 'foo-details',
providers: [AppService],
template: `<div class="container">
<h1 class="col-sm-12">Foo Details</h1>
<div class="col-sm-12">
<label class="col-sm-3">ID</label> <span>{{foo.id}}</span>
</div>
<div class="col-sm-12">
<label class="col-sm-3">Name</label> <span>{{foo.name}}</span>
</div>
<div class="col-sm-12">
<button class="btn btn-primary" (click)="getFoo()" type="submit">New Foo</button>
</div>
</div>`
})
export class FooComponent {
public foo = new Foo(1,'sample foo');
private foosUrl = 'http://localhost:8082/spring-security-oauth-resource/foos/';
constructor(private _service:AppService) {}
getFoo(){
this._service.getResource(this.foosUrl+this.foo.id)
.subscribe(
data => this.foo = data,
error => this.foo.name = 'Error');
}
}4.4. 應用服務
現在,讓我們來查看 AppService:
import {Injectable} from '@angular/core';
import { Cookie } from 'ng2-cookies';
import { HttpClient, HttpHeaders } from '@angular/common/http';
import { Observable } from 'rxjs/Observable';
import 'rxjs/add/operator/catch';
import 'rxjs/add/operator/map';
export class Foo {
constructor(
public id: number,
public name: string) { }
}
@Injectable()
export class AppService {
public clientId = 'fooClientId';
public redirectUri = 'http://localhost:8089/';
constructor(
private _http: HttpClient){}
retrieveToken(code){
let params = new URLSearchParams();
params.append('grant_type','authorization_code');
params.append('client_id', this.clientId);
params.append('redirect_uri', this.redirectUri);
params.append('code',code);
let headers = new HttpHeaders({'Content-type': 'application/x-www-form-urlencoded; charset=utf-8', 'Authorization': 'Basic '+btoa(this.clientId+":secret")});
this._http.post('http://localhost:8081/spring-security-oauth-server/oauth/token', params.toString(), { headers: headers })
.subscribe(
data => this.saveToken(data),
err => alert('Invalid Credentials')
);
}
saveToken(token){
var expireDate = new Date().getTime() + (1000 * token.expires_in);
Cookie.set("access_token", token.access_token, expireDate);
console.log('Obtained Access token');
window.location.href = 'http://localhost:8089';
}
getResource(resourceUrl) : Observable<any>{
var headers = new HttpHeaders({'Content-type': 'application/x-www-form-urlencoded; charset=utf-8', 'Authorization': 'Bearer '+Cookie.get('access_token')});
return this._http.get(resourceUrl,{ headers: headers })
.catch((error:any) => Observable.throw(error.json().error || 'Server error'));
}
checkCredentials(){
return Cookie.check('access_token');
}
logout() {
Cookie.delete('access_token');
window.location.reload();
}
}我們這裏快速回顧一下實現過程:
- checkCredentials(): 檢查用户是否已登錄
- retrieveToken(): 使用授權碼獲取訪問令牌
- saveToken(): 將訪問令牌保存到 cookie 中
- getResource(): 使用其 ID 獲取 Foo 詳情
- logout(): 刪除訪問令牌 cookie
5. 運行應用程序
為了運行我們的應用程序並確保一切正常工作,我們需要執行以下步驟:
- 首先,在 8081 端口運行 Authorization Server
- 然後,在 8082 端口運行 Resource Server
- 最後,運行 Front End
我們需要先構建我們的應用程序:
mvn clean install然後更改目錄到 src/main/resources:
cd src/main/resources然後,在端口 8089 上運行我們的應用程序:
npm start6. 結論
我們學習瞭如何使用 Spring 和 Angular 6 構建一個簡單的 Authorization Code 流客户端。