Auth0을 사용하는 Angular 앱의 사용자 인증

이 보좌관의 초점은 엔지니어가 클라이언트 검증을 실행하여 Angular 애플리케이션을 얻는 방법을 알아내는 데 도움을 주는 것입니다. 함께 제공되는 보안 아이디어를 연습하기 위해 Angular 시작 애플리케이션을 개선합니다.
  • Auth0 구성
  • Auth0 Angular SDK 설치
  • 응용 프로그램에 로그인 추가
  • 응용 프로그램에 로그아웃 추가
  • 사용자 프로필 정보 표시

  • 1. Auth0 구성



    Auth0을 추구한 시점에서 다른 응용 프로그램이 만들어졌거나 다른 응용 프로그램을 만들었을 수 있습니다. Auth0과 대화하려면 해당 애플리케이션에 대한 몇 가지 통찰력이 필요합니다. Auth0 dashboard 의 "응용 프로그램 설정"영역에서 이러한 미묘함을 얻을 수 있습니다.



    다음을 위해 콜백 URL 구성, 로그아웃 URL 구성, 허용된 웹 원본 구성을 잊지 마십시오.



    http://localhost:4200 (포트가 있는 각도 로컬 환경)

    2. Auth0 Angular SDK 설치



    Auth0 Angular SDK를 도입하기 위해 귀하의 사업 레지스트리 내에서 수반되는 주문을 실행하십시오.

    npm install @auth0/auth0-angular
    


    인증 모듈 등록 및 구성




    // environment.ts
    
    export const environment = {
      production: false,
      auth: {
        domain: 'YOUR_DOMAIN',
        clientId: 'YOUR_CLIENT_ID'
      }
    };
    



    // 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 '@auth0/auth0-angular';
    import { environment } from 'src/environments/environment';
    
    @NgModule({
      declarations: [AppComponent],
      imports: [
        BrowserModule,
    
        // Import the module into the application, with configuration
        AuthModule.forRoot(environment.auth)
      ],
    
      bootstrap: [AppComponent],
    })
    export class AppModule {}
    


    3,4. 애플리케이션에 로그인/로그아웃 추가



    SDK에서 AuthService 유형을 가져오고 AuthService 서비스 클래스에서 loginWithRedirect() 및 logout() 메서드를 사용하여 로그인 버튼을 만듭니다.



    import { Component, OnInit } from '@angular/core';
    
    // Import the AuthService type from the SDK
    import { AuthService } from '@auth0/auth0-angular';
    
    @Component({
      selector: 'app-header',
      templateUrl: './header.component.html',
      styleUrls: ['./header.component.scss']
    })
    export class HeaderComponent implements OnInit {
    
      // Inject the authentication service into your component through the constructor
      constructor(public auth: AuthService) {}
    
      ngOnInit(): void {
      }
    
    }
    



    <header>
        <h3>Auth0 Angular</h3>
        <div *ngIf="auth.isAuthenticated$ | async; else loggedOut">
            <button (click)="auth.logout()">
              Log out
            </button>
        </div>
    
        <ng-template #loggedOut>
            <button (click)="auth.loginWithRedirect()">Log in</button>
        </ng-template>
    </header>
    


    5. 사용자 프로필 정보 표시



    Auth0 Angular SDK는 이름이나 프로필 사진과 같이 필요한 모든 부분에서 로그인한 클라이언트와 관련된 프로필 데이터를 신속하게 복구하는 데 도움을 줍니다. 프로필 데이터는 AuthService 관리에서 발견할 수 없는 user$를 통해 액세스할 수 있습니다. 위의 header.component.ts에서 본 구성 요소의 AuthService를 가져와서 구성 요소의 html 파일에서 데이터를 가져와야 합니다.

    <div *ngIf="auth.user$ | async as user">
        <h2>Welcome</h2>
        <p>{{ user.email }}</p>
    </div>
    




    Github 소스:
    https://github.com/muhammadawaisshaikh/angular-auth0

    좋은 웹페이지 즐겨찾기