如何在Angular 8中使用angular-oauth2-oidc实现身份验证代码流

时间:2019-11-07 06:28:40

标签: angular typescript oauth-2.0

我目前正在为我的oAuth2跟踪此问题:

https://manfredsteyer.github.io/angular-oauth2-oidc/docs/index.html

我正在使用身份验证流程授予。

我有一个主页,用户可以在其中单击按钮,并将其重定向到身份验证服务器。 用户输入凭据后,它将被重定向到一个临时页面,在此我想使用auth代码获取访问令牌。

我目前停留在有关如何获取代码的临时页面上。

那么几个问题:

  1. 如何实现获取访问代码和获取访问令牌的方法?
  2. 获取访问令牌后如何重定向到主页?

-

这就是我希望流程像这样的方式:

预登录->身份验证服务器登录页面->登录后->应用程序主页

-

PreLoginComponent.ts:

export class PreLoginComponent implements OnInit {
  constructor(private oauthService: OAuthService) {}

  ngOnInit() {}

  public login() {
    this.oauthService.initCodeFlow();
  }
}

authConfig.ts:

export const authConfig: AuthConfig = {

  responseType: environment.authRequestType,

  loginUrl: environment.authServerUrl,

  redirectUri: environment.redirectUrl,

  clientId: environment.clientId,

  scope: environment.scope,

  requireHttps: false,

  showDebugInformation: true
};

PreLoginComponent.ts:

export class PreLoginComponent implements OnInit {
  constructor(private oauthService: OAuthService) {}

  ngOnInit() {}

  public login() {
    this.oauthService.initCodeFlow();
  }
}

AppComponent.ts:

import { OAuthService, JwksValidationHandler } from 'angular-oauth2-oidc';
import { authConfig } from './core/authentication/auth.config';

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

  constructor(
    private oauthService: OAuthService
  ) {
    this.configure();
  }

  ngOnInit() {
    }

  private configure() {
    this.oauthService.configure(authConfig);
    this.oauthService.tokenValidationHandler = new JwksValidationHandler();
  }
}

PostLoginComponent.ts:

import { Component, OnInit } from '@angular/core';
import { OAuthService, JwksValidationHandler } from 'angular-oauth2-oidc';

@Component({
  selector: 'app-post-login',
  templateUrl: './post-login.component.html',
  styleUrls: ['./post-login.component.scss']
})
export class PostLoginComponent implements OnInit {
  constructor(private oauthService: OAuthService) {

  }

  ngOnInit() {
  // how do i implement to get the code and get access token 
  // how do i redirect after success
  //this.oauthService.tryLoginCodeFlow();
  }
}

1 个答案:

答案 0 :(得分:0)

您是指授权码授予吗?如果是这样,我发现返回源(标准)对我非常有用:https://tools.ietf.org/html/rfc6749#section-4.1

要具体回答:

  
      
  1. 如何实现获取访问代码和获取访问令牌的方法?
  2.   

理论上,您重定向到的页面在您的控制之下。重定向将在URL中传递授权代码,因此您应该能够从那里读取它。请参阅上面链接中的步骤C)。

  
      
  1. 获取访问令牌后如何重定向到主页?
  2.   

同样,您重定向到的页面是“您的”,因此您可以将301重定向到您的主页...,或者仅使整个过程发生在另一个窗口中(这是一种标准做法),并在出现以下情况时将其关闭重定向页面被点击...