0
1

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

More than 3 years have passed since last update.

SPAでログイン済か否かをチェックする方法

Posted at

概要

SPAで作成されたアプリで、ログイン済であるか否かをチェックする方法について自分なりに備忘録としてまとめていきたいと思います。

全体の流れ

APIで認証トークンが発行され、その認証トークンを保持しているのか否かをチェックする方法を用います。

  1. APIに接続し、認証トークンを受け取る
  2. フロント側で認証トークンを保持しているのか否かをチェックする
APIから認証トークンを受け取る(※axiosを使用)
AccessTokenAPIConnector.ts
private var accessToken = "";

axios.get('https://example.com', params) // この辺は適当です。
.then(function(response) {
    // APIから受け取った認証トークン
    this.accessToken = response.data.token;
}).catch(function(error) {
    // APIでエラーが発生した場合の処理
});
認証トークンをlocal Storageに保存する
AccessTokenAPIConnector.ts
// ローカルストレージ
private val store: Storage = localStorage

// ローカルストレージに受け取った認証トークンを設定
this.store.setItem("token", accessToken);
local Storageに認証トークンが保存されているのかをチェック
Authentication.ts
// ローカルストレージ
private val store: Storage = localStorage

if(!this.store.getItem("token")){
    // ローカルストレージに認証トークンがない場合
    this.$route.go("/login")
}else{
    // 認証済!
}

最後に...

他により良い方法などもあるかもしれないですが、今回紹介した方法はあまり時間をかけずに期待通りに動いてくれたので、ひとつの方法として覚えておきたいなと思いました。

参考にした記事

SPAでのログイン処理のやりかた

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

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?