Spring Security OAuthを使用したフロントエンドアプリケーション - 認証コードフロー

Spring Security OAuthを備えたフロントエンドアプリ–承認コードフロー

1. 概要

このチュートリアルでは、認証コードフローのシンプルなフロントエンドを構築して、Spring Security OAuth seriesを続行します。

ここでの焦点はクライアント側であることに注意してください。 Spring REST API + OAuth2 + AngularJSの記述を確認して、承認サーバーとリソースサーバーの両方の詳細な構成を確認してください。

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/")
...

次の簡単な詳細で、承認コード付与タイプが有効になっていることに注意してください。

  • クライアントIDはfooClientIdです

  • スコープは、fooread 、およびwriteです。

  • リダイレクトURIはhttp://localhost:8089/です(フロントエンドアプリにはポート8089を使用します)

3. フロントエンド

それでは、簡単なフロントエンドアプリケーションの構築を始めましょう。

ここではアプリにAngular6を使用するために使用するため、Spring Bootアプリケーションでfrontend-maven-pluginプラグインを使用する必要があります。


    com.github.eirslett
    frontend-maven-plugin
    1.6

    
        v8.11.3
        6.1.0
        src/main/resources
    

    
        
            install node and npm
            
                install-node-and-npm
            
        

        
            npm install
            
                npm
            
        

        
            npm run build
            
                npm
            

            
                run build
            
        
    

当然、最初にボックスにNode.jsをインストールする必要があることに注意してください。 Angular CLIを使用して、アプリのベースを生成します。

ng新しいauthCode

4. 角度モジュール

それでは、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 { }

モジュールは3つのコンポーネントと1つのサービスで構成されています。これらについては、次のセクションで説明します。

4.1. アプリコンポーネント

ルートコンポーネントであるAppComponentから始めましょう。

import {Component} from '@angular/core';

@Component({
    selector: 'app-root',
    template: `
`
})

export class AppComponent {}

4.2. ホームコンポーネント

次は、メインコンポーネントのHomeComponentです。

import {Component} from '@angular/core';
import {AppService} from './app.service'

@Component({
    selector: 'home-header',
    providers: [AppService],
  template: `
Welcome !! Logout
` }) 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コンポーネント

3番目で最後のコンポーネントはFooComponentです。これにより、Resource Serverから取得したFooリソースが表示されます。

import { Component } from '@angular/core';
import {AppService, Foo} from './app.service'

@Component({
  selector: 'foo-details',
  providers: [AppService],
  template: `

Foo Details

{{foo.id}}
{{foo.name}}
` }) 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{
    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で認証サーバーを実行します

  • 次に、ポート8082でリソースサーバーを実行します

  • 最後に、フロントエンドを実行します

最初にアプリを作成する必要があります。

mvn clean install

次に、ディレクトリをsrc / main / resourcesに変更します。

cd src/main/resources

次に、ポート8089でアプリを実行します。

npm start

6. 結論

SpringとAngular 6を使用して、承認コードフロー用のシンプルなフロントエンドクライアントを構築する方法を学びました。

そして、いつものように、完全なソースコードはover on GitHubで利用できます。