在 Angular 和 ASP.NET CORE Web API 5.0 中使用 Okta 进行身份验证

作者 : 慕源网 本文共5165个字,预计阅读时间需要13分钟 发布时间: 2021-10-29 共592人阅读

先决条件

  • 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}

import { Component, OnInit } from '@angular/core';
import { OktaAuthService } from '@okta/okta-angular';
import { HttpClient } from '@angular/common/http';
import sampleConfig from '../app.config';
interface Message {
    date: string;
    text: string;
}
@Component({
    selector: 'app-messages',
    templateUrl: './messages.component.html',
    styleUrls: ['./messages.component.css']
})
export class MessagesComponent implements OnInit {
    failed: Boolean;
    messages: Array < Message > [];
    constructor(public oktaAuth: OktaAuthService, private http: HttpClient) {
        this.messages = [];
    }
    async ngOnInit() {
        const accessToken = this.oktaAuth.getAccessToken();
        this.http.get(sampleConfig.resourceServer.backEndUlr, {
            headers: {
                Authorization: 'Bearer ' + accessToken,
            }
        }).subscribe((data: any) => {
            this.messages = data;
        }, (err) => {
            console.error(err);
            this.failed = true;
        });
    }
}

Web API 更改

然后重定向到 Okta 登录页面并单击登录按钮。用户将被重定向到 Okta 小部件登录页面。您需要输入您的凭据并点击登录按钮。

成功登录后,用户将被重定向到主应用程序页面。在这里您需要注意,根据您在 okta 中的设置,您将仅被重定向到该页面。

现在身份验证将成功进行。现在您需要与后端 API 进行通信,因为您必须在启动文件中进行一些更改。

创建具有授权属性的测试控制器以验证用户后,请按照以下设置进行操作。

概括

借助所有设置,您可以使用 Okta 保护您的应用程序。


慕源网 » 在 Angular 和 ASP.NET CORE Web API 5.0 中使用 Okta 进行身份验证

常见问题FAQ

程序仅供学习研究,请勿用于非法用途,不得违反国家法律,否则后果自负,一切法律责任与本站无关。
请仔细阅读以上条款再购买,拍下即代表同意条款并遵守约定,谢谢大家支持理解!

发表评论

开通VIP 享更多特权,建议使用QQ登录