先决条件
- Okta 帐户。
- 了解 Angular 的基础知识。
- 要向其添加身份验证的示例项目或应用程序。
- 了解构建 Asp.Net CORE Web API 应用程序的基础知识。
在 Okta 中注册 SPA 应用程序
您需要遵循以下详细信息,




启用可信来源
要启用可信来源,您需要在以下部分添加您的基本 URL。


从 NPM 安装 Okta 相关文件
npm install @okta/okta-angular
以下是主要设置,
您需要输入您的客户端 ID 和 Okta 域信息。对于该设置,我们使用了一个单独的文件并将所有这些详细信息放在该配置文件中。
export default {
config: {
clientId: '0oa1wt3aznmXLKmtR5d7',
issuer: 'https://dev-2209333.okta.com/oauth2/default',
redirectUri: 'https://localhost:4200/login/callback',
scopes: ['openid', 'profile', 'email'],
pkce: true,
},
resourceServer: {
backEndUlr: 'https://localhost:44313/api/Messages',
},
};
现在利用 app.Madule.ts 文件中的这些设置,并使用 Okta 守卫定义路由详细信息。
import { BrowserModule } from '@angular/platform-browser';
import { NgModule } from '@angular/core';
import { HttpClientModule } from '@angular/common/http';
import { Routes, RouterModule } from '@angular/router';
import {OKTA_CONFIG,OktaAuthGuard,OktaAuthModule,OktaCallbackComponent,} from '@okta/okta-angular';
import { AppComponent } from './app.component';
import { HomeComponent } from './home/home.component';
import { MessagesComponent } from './messages/messages.component';
import { ProfileComponent } from './profile/profile.component';
import configInfo from './app.config';
const appRoutes: Routes = [{
path: '',
component: HomeComponent,
}, {
path: 'home/login',
component: HomeComponent,
}, {
path: 'login/callback',
component: OktaCallbackComponent,
}, {
path: 'user/profile',
component: ProfileComponent,
canActivate: [OktaAuthGuard],
}, {
path: 'backEndApi/call',
component: MessagesComponent,
canActivate: [OktaAuthGuard],
}, ];
@NgModule({
declarations: [AppComponent, HomeComponent, ProfileComponent, MessagesComponent, ],
imports: [BrowserModule, HttpClientModule, OktaAuthModule,
RouterModule.forRoot(appRoutes, {
relativeLinkResolution: 'legacy'
}),
],
providers: [{
provide: OKTA_CONFIG,
useValue: configInfo.config
}, ],
bootstrap: [AppComponent],
})
export class AppModule {}
如何实现登录和注销功能?
对于登录和注销,您可以在 app.componets.html 文件中创建您的登录 HTML 并实现如下登录和注销。您检查用户是否经过身份验证。然后启动登录。
<div class="ui inverted top fixed menu">
<div class="ui container-flud">
<a class="item btn btn-primary ml-1" *ngIf="!isAuthenticated" (click)="login()">Login</a>
<a id="messages-button" class="item btn btn-secondary ml-1" *ngIf="isAuthenticated" routerLink="/backEndApi/call">
<i aria-hidden="true" class="mail outline icon"></i>Messages </a>
<a id="profile-button" class="item btn btn-warning ml-1" *ngIf="isAuthenticated" routerLink="/user/profile">Profile</a>
<a id="logout-button" class="item btn btn-success ml-1" *ngIf="isAuthenticated" (click)="logout()">Logout</a>
</div>
</div>
<div class="ui text container" style="margin-top: 7em;">
<router-outlet></router-outlet>
</div>
import { Component, OnInit } from '@angular/core';
import { Location } from '@angular/common';
import { OktaAuthService } from '@okta/okta-angular';
@Component({
selector: 'app-root',
templateUrl: './app.component.html',
styleUrls: ['./app.component.css']
})
export class AppComponent implements OnInit {
title = 'app';
isAuthenticated: boolean;
baseUri: string;
constructor(public oktaAuth: OktaAuthService) {
this.oktaAuth.$authenticationState.subscribe(isAuthenticated => this.isAuthenticated = isAuthenticated);
}
async ngOnInit() {
this.isAuthenticated = await this.oktaAuth.isAuthenticated();
}
async login() {
await this.oktaAuth.signInWithRedirect({
originalUri: '/'
});
}
async logout() {
await this.oktaAuth.signOut();
}
}
Okta 从注册应用程序回调设置
无论您在应用程序注册时设置回调 URL,您都需要在路由部分定义这些详细信息。

获取用户理赔信息
用户成功登录后,您可以调用 getUser() 方法并获取用户详细信息。

import { Component, OnInit } from '@angular/core';
import { OktaAuthService } from '@okta/okta-angular';
interface Claim {
claim: string;
value: string;
}
@Component({
selector: 'app-profile',
templateUrl: './profile.component.html',
styleUrls: ['./profile.component.css']
})
export class ProfileComponent implements OnInit {
idToken: any;
claims: Array < Claim > ;
constructor(public oktaAuth: OktaAuthService) {}
async ngOnInit() {
const userClaims = await this.oktaAuth.getUser();
this.claims = Object.entries(userClaims).map(entry => ({
claim: entry[0],
value: entry[1]
}));
}
}
<h1 class="ui header">
<i aria-hidden="true" class="drivers license outline icon"></i> My User Profile (ID Token Claims)
</h1>
<table class="ui table">
<thead>
<tr>
<th>Claim</th>
<th>Value</th>
</tr>
</thead>
<tbody>
<tr *ngFor="let claim of claims">
<td>{{claim.claim}}</td>
<td id="claim-{{claim.claim}}">{{claim.value}}</td>
</tr>
</tbody>
</table>
使用访问令牌调用后端 API。
在单页应用程序中,如果我们想与 API 通信,我们需要设置访问令牌信息。在您的前端(此 SPA)上,确保Authorization
使用以下格式将访问令牌放置在传出请求的 HTTP 标头中:
Authorization: Bearer ${token}