LoginSignup
5
1

はじめに

FlutterアプリケーションからクラウドベースのAPIにアクセスする際、セキュリティと認証はとても重要な要素です!
この記事では、API Gatewayを使用してAPIを保護し、Flutterアプリケーションから適切に認証されたリクエストを送信する方法について説明します。

目次

  1. 概要
  2. 手順
    1. API Gatewayの認証設定を更新
    2. ユーザー認証用のJWTトークンを発行
    3. リクエストにJWTトークンを含めてAPI Gatewayにアクセス
  3. まとめ

概要

API Gatewayは、クラウドベースのAPIのエンドポイントを簡単に作成、公開、管理できるサービスです。JWT(JSON Web Token)は、ウェブトークンの形式を使用して安全な情報を伝達するための標準化された方法です。この記事では、FlutterアプリケーションがAPI Gatewayを介して保護されたAPIにアクセスする方法に焦点を当てます。

手順

API GatewayにJWT認証を設定するには、次の手順を実行します。

  1. API Gatewayの認証設定を更新する
  2. ユーザー認証用のJWTトークンを発行する
  3. リクエストにJWTトークンを含めてAPI Gatewayにアクセスする

詳細

1. API Gatewayの認証設定を更新する

今回は以下の記事を参考にGoogle CloudでAPI Gateway設定をしました。

使用するSwaggerファイルは以下です

swagger: '2.0'
info:
  title: sample-api
  description: Sample API on API Gateway with a Google Cloud Functions backend
  version: 1.0.0
securityDefinitions:
  auth0_jwk:
    authorizationUrl: ""
    flow: "implicit"
    type: "oauth2"
    x-google-issuer: "xxx@iam.gserviceacouunt.com"
    x-google-jwks_uri: "https://www.googleapi.com/.../xxx@iam.gserviceacouunt.com"
    x-google-audiences: "https://xxx.an.gateway.dev/"
security:
  - auth0_jwk: []
schemes:
  - https
produces:
  - application/json
paths:
  /hello:
    get:
      summary: Greet a user
      operationId: hello
      x-google-backend:
        address: https://xxx.cloudfunctions.net/helloGET
      responses:
        '200':
          description: A successful response
          schema:
            type: string

2. 認証用のJWTトークンを発行する

以下のライブラリを使用してJWTトークンを取得します
(flutter_session_jwtといういかにも使えそうなライブラリもあったのですがバージョンがかなり不安だったのでこれを採用することに。。。)

JWTトークン発行にはSwagger上で定義しているissueraudience, あとはサービスアカウントのアクセスキーを必要とします

上記を踏まえて、Swaggerファイルを使用して作成したAPI Gatewayに対してFlutterアプリ側からJWTトークンを取得するコードは以下の通り

import 'package:dart_jsonwebtoken/dart_jsonwebtoken.dart';

...

final jwt = JWT({
    'aud': Audience.one('https://xxx.an.gateway.dev'),
    'sub': 'xxx@iam.gserviceacouunt.com',
    'iss': 'xxx@iam.gserviceacouunt.com',
});

final jwtToken = jwt.sign(RSA(privateKey),
    algorithm: JWTAlgorithm.RS256, expiresIn: const Duration(minutes: 10));

3. リクエストにJWTトークンを含めてAPI Gatewayにアクセスする

あとはJWTトークンをheaderに含めてアクセスするだけです!

final Map<String, String> header = {
    HttpHeaders.authorizationHeader = 'Bearer $jwtToken',
    HttpHeaders.contentTypeHeader: 'application/json'
}

final url = Uri.parse('https://xxx.an.gateway.dev/hello');
await http.get(url, header: header);

まとめ

FlutterアプリがAPI GatewayにJWT認証を使用してAPIにアクセスする方法について詳しく説明しました!
API Gatewayを使用することで、アプリケーションのセキュリティを強化し、安全にAPIにアクセスすることができます。ぜひお試しあれ!

5
1
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
5
1