1
2

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

Angular初心者用

1
Posted at

以下は「固定ユーザーでログイン済み扱い」「ログイン画面スキップ」の最小サンプルです。

1. auth.service.ts

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

export type LoginUser = {
  id: string;
  name: string;
  roles: string[];
};

@Injectable({ providedIn: 'root' })
export class AuthService {
  private fixedUser: LoginUser = {
    id: 'test-user-001',
    name: '固定テストユーザー',
    roles: ['USER', 'ADMIN']
  };

  isLoggedIn(): boolean {
    return true; // 常にログイン済み
  }

  getUser(): LoginUser {
    return this.fixedUser;
  }

  getAccessToken(): string {
    // 開発用の固定トークン
    return 'dummy-fixed-token';
  }
}

2. auth.guard.ts

import { inject } from '@angular/core';
import { CanActivateFn } from '@angular/router';
import { AuthService } from './auth.service';

export const authGuard: CanActivateFn = () => {
  const auth = inject(AuthService);
  return auth.isLoggedIn(); // trueなのでログイン画面へ行かない
};

AngularのGuardはルートアクセス可否を制御する仕組みです。trueなら画面遷移できます。(Angular)

3. auth.interceptor.ts

import { HttpInterceptorFn } from '@angular/common/http';
import { inject } from '@angular/core';
import { AuthService } from './auth.service';

export const authInterceptor: HttpInterceptorFn = (req, next) => {
  const auth = inject(AuthService);

  const authReq = req.clone({
    setHeaders: {
      Authorization: `Bearer ${auth.getAccessToken()}`,
      'X-User-Id': auth.getUser().id
    }
  });

  return next(authReq);
};

InterceptorはAPIリクエスト共通でヘッダー追加などに使えます。Angular公式でも認証ヘッダー追加のような共通処理に使う説明があります。(Angular)

4. app.config.ts

import { ApplicationConfig } from '@angular/core';
import { provideRouter } from '@angular/router';
import { provideHttpClient, withInterceptors } from '@angular/common/http';

import { routes } from './app.routes';
import { authInterceptor } from './auth.interceptor';

export const appConfig: ApplicationConfig = {
  providers: [
    provideRouter(routes),
    provideHttpClient(
      withInterceptors([authInterceptor])
    )
  ]
};

5. app.routes.ts

import { Routes } from '@angular/router';
import { authGuard } from './auth.guard';
import { HomeComponent } from './home/home.component';

export const routes: Routes = [
  {
    path: '',
    component: HomeComponent,
    canActivate: [authGuard]
  }
];

6. componentで固定ユーザー表示

import { Component, inject } from '@angular/core';
import { AuthService } from '../auth.service';

@Component({
  selector: 'app-home',
  template: `
    <h2>ログイン済み</h2>
    <p>ユーザーID: {{ user.id }}</p>
    <p>ユーザー名: {{ user.name }}</p>
  `
})
export class HomeComponent {
  private auth = inject(AuthService);

  user = this.auth.getUser();
}

結論:

isLoggedIn(): boolean {
  return true;
}

これでログイン画面を完全にスキップできます。
ただし、本番ではNGです。開発環境・結合環境だけにしてください。

1
2
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
1
2

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?