(三)Angular2 OAuth 2.0

OAuth简述:OAuth 2.0 的一个简单解释理解OAuth 2.0

Angular引入OAuth 2.0:Angular-oauth2-oidc文档

业务逻辑:客户端请求登录 -> 跳转授权地址并登录 -> 返回客户端重定向地址 -> 返回客户端地址

1.创建Angular 2项目

2.项目创建完成后安装 angular-oauth2-oidc

npm i angular-oauth2-oidc --save

3.安装完成后打开 AppModule 引入 OAuthModule

import { HttpClientModule } from '@angular/common/http';
import { OAuthModule } from 'angular-oauth2-oidc';

@NgModule({
  imports: [ 
    HttpClientModule,
    OAuthModule.forRoot()
  ],
  declarations: [
    AppComponent,
  ],
  bootstrap: [
    AppComponent 
  ]
})
export class AppModule {
}

4.建立 OAuthConfig 简单配置文件(更多配置请链接至Angular-oauth2-oidc文档

(1)issuer:后端授权地址

(2)redirectUrl:授权后返回客户端的地址

(3)logoutUrl:用户退出地址

(4)clientId:后端设置的客户端ID

(5)scope:需要授权的权限

(6)sessionChecksEnabled:session检查

(7)requireHttps:是否https

(8)silentRefreshRedirectUri:token到期刷新

import { AuthConfig } from 'angular-oauth2-oidc';

export const authConfig: AuthConfig = {

  // Url of the Identity Provider
  issuer: 'https://steyer-identity-server.azurewebsites.net/identity',

  // URL of the SPA to redirect the user to after login
  redirectUri: 'http://127.0.0.1:3000/callback',
  // The logout url
  logoutUrl: 'http://127.0.0.1:3000/index',

  // The SPA's id. The SPA is registered with this id at the auth-server
  clientId: 'spa-demo',

  // set the scope for the permissions the client should request
  // The first three are defined by OIDC. The 4th is a usecase-specific one
  scope: 'openid profile email voucher',

  /**
  * If true, the lib will try to check whether the user
  * is still logged in on a regular basis as described
  * in http://openid.net/specs/openid-connect-session-1_0.html#ChangeNotification
  */
  sessionChecksEnabled: false,

  /**
  * Defines whether https is required.
  * The default value is remoteOnly which only allows
  * http for localhost, while every other domains need
  * to be used with https.
  */
  requireHttps: false,

  // The redirect uri used when doing silent refresh
  silentRefreshRedirectUri: 'http://127.0.0.1:3000/assets/html/silent-refresh.html'
}

5.建立 AppService 请求OAuth,并引入 OAuthConfig 配置文件

import { Injectable } from '@angular/core';
import { OAuthService } from 'angular-oauth2-oidc';
import { JwksValidationHandler } from 'angular-oauth2-oidc';
import { OAuthConfig } from './OAuthConfig';

@Injectable({
  providedIn: 'root'
})
export class AppService {

  constructor(
    private oauthSrv: OAuthService,
  ) { }

  public oauthConfig() {
    this.oauthSrv.configure(OAuthConfig.authConfig);
    this.oauthSrv.setStorage(localStorage);
    this.oauthSrv.tokenValidationHandler = new JwksValidationHandler();
    this.oauthSrv.loadDiscoveryDocumentAndTryLogin({
      onTokenReceived: url => {
        window.parent.location.href = url.state;
      }
    });
    this.oauthSrv.setupAutomaticSilentRefresh();
  }

  public identityValid() {
    if (this.oauthSrv.hasValidAccessToken()) {
      return true;
    }

    this.login();
    return false;
  }

  public login() {
    const href = window.location.href;
    this.oauthSrv.initLoginFlow(href);
  }

  public logOut() {
    this.oauthSrv.logOut();
  }
}

6.在 AppComponent 中调用 AppService 的 oauthConfig 方法

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

@Component({
  selector: 'app-root',
  templateUrl: './app.component.html',
  styleUrls: ['./app.component.scss']
})
export class AppComponent {

  constructor(
    private appSrv: AppService
  ) {
    this.appSrv.oauthConfig();
  }
}

7.创建 login 组件并引入 AppService 及调用登录

  async login() {
    await this.appSrv.login();
  }

8.创建 project 组件并引入 AppService 调用验证登录

  ngAfterViewInit(): void {
    this.init();
  }

  async init() {
    await this.appSrv.identityValid();
  }

9.创建 callback 组件,仅作为后端授权成功后的重定向地址

10.token的自动刷新,在 assets 中创建 silent-refresh.html 单页面(参考)

<html>
<body>
    <script>
    parent.postMessage(location.hash, location.origin);
    console.info('token has refreshed');
    </script>
</body>
</html>
原文地址:https://www.cnblogs.com/chendongbky/p/11576505.html