Skip to main content

React

安装 AuthOK Angular SDK

npm install @authok/authok-angular

注册/配置认证模块

  • @authok/authok-angular 包中导入 AuthModule
  • 调用 AuthModule.forRoot 给应用添加 AuthModule.
app.module.ts
import { BrowserModule } from '@angular/platform-browser';
import { NgModule } from '@angular/core';
import { AppComponent } from './app.component';

// Import the module from the SDK
import { AuthModule } from '@authok/authok-angular';

@NgModule({
declarations: [AppComponent],
imports: [
BrowserModule,

// Import the module into the application, with configuration
AuthModule.forRoot({
domain: 'YOUR_DOMAIN',
clientId: 'YOUR_CLIENT_ID'
}),
],

bootstrap: [AppComponent],
})
export class AppModule {}

添加登录

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

// Import the AuthService type from the SDK
import { AuthService } from '@authok/authok-angular';

@Component({
selector: 'app-auth-button',
template: '<button (click)="auth.loginWithRedirect()">登录</button>'
})
export class AuthButtonComponent {
// Inject the authentication service into your component through the constructor
constructor(public auth: AuthService) {}
}

添加注销

import { Component, Inject } from '@angular/core';
import { AuthService } from '@authok/authok-angular';
import { DOCUMENT } from '@angular/common';

@Component({
selector: 'app-auth-button',
template: `
<ng-container *ngIf="auth.isAuthenticated$ | async; else loggedOut">
<button (click)="auth.logout({ returnTo: document.location.origin })">
注销
</button>
</ng-container>

<ng-template #loggedOut>
<button (click)="auth.loginWithRedirect()">登录</button>
</ng-template>
`,
styles: [],
})
export class AuthButtonComponent {
constructor(@Inject(DOCUMENT) public document: Document, public auth: AuthService) {}
}

显示用户信息

import { Component } from '@angular/core';
import { AuthService } from '@authok/authok-angular';

@Component({
selector: 'app-user-profile',
template: `
<ul *ngIf="auth.user$ | async as user">
<li>{{ user.name }}</li>
<li>{{ user.email }}</li>
</ul>`
})
export class UserProfileComponent {
constructor(public auth: AuthService) {}
}