概要
devise token認証するAPIに、jTokerをつかってOAuth2ログインする。
jTokerの公式demoはReact+JQueryでつくられているが、JQueryだけで使えるサンプルをつくる
TL;DR
- $.auth.configure()が非同期メソッドなのが肝。
- issueでもいくつか上がっているが、await忘れるとログイン後に$.auth.userの中身が空になったりする。
- Promiseが返ってくるようなので、async/awaitを使う。
- もしくは(オプションとなっている)PubSubライブラリを使ってイベントを受信する。
環境
- Rails5のAPIモードでdevise_token_authとomniauthを使ったログインを試す - Qiita を参考にdevise token認証するAPIを用意
- 認証はパスワードではく、GoogleのOAuth2.0を使う
サンプルソース
$ touch dist src
async/awaitを使いたいのでbabel/webpackを準備
npmとwebpack4でビルド - jQueryからの次のステップ - Qiita
webpack.config.js
const path = require('path');
const webpack = require("webpack");
const js = {
mode: 'development',
entry: {
main: path.resolve(__dirname, 'src', 'main.js')
},
output: {
path: path.resolve(__dirname, 'dist'),
filename: '[name].js'
},
module: {
rules: [
{
test: /\.js$/,
use: [
{
loader: 'babel-loader',
}
]
}
]
},
devServer: {
publicPath: '/dist/'
},
};
module.exports = [js]
package.json
{
"name": "example",
"version": "1.0.0",
"description": "",
"main": "webpack.config.js",
"dependencies": {
"babel-core": "^6.26.3",
"babel-loader": "^7.1.5",
"babel-preset-env": "^1.7.0",
"j-toker": "^0.0.10-beta3",
"webpack-dev-server": "^3.7.2",
"webpack-cli": "^3.3.5",
"webpack": "^4.35.0"
},
"devDependencies": {},
(中略)
}
main.js
import $ from 'jquery';
import Auth from 'j-toker';
$(async () => {
$('.signin').on('click', async() => {
try {
await $.auth.configure({
apiUrl: 'http://localhost:3000',
storage: 'localStorage',
authProviderPaths: {
google: '/auth/google'
}
});
}catch(e){
console.log(e);
}
try {
if(!$.auth.user.signedIn) {
const user = await $.auth.oAuthSignIn({provider: 'google'});
}
console.log($.auth.user);
//ログイン後はヘッダにトークンが自動的にセットされる
const result = await $.ajax({
url:`http://localhost:3000/api/v1/hoge`,
type: 'GET'
});
} catch(e) {
console.log(e);
}
});
});
index.html
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title>j-tokerサンプル</title>
<script src="dist/main.js"></script>
</head>
<body>
<p><input type='button' value='ログイン' class='signin button button-primary button-large'></p>
</body>
</html>
$ npm i
$ npx webpack-dev-server
http://localhost:8080/index.htmlにアクセス
課題
ログアウトは実装できていない
- API側が対応する必要がある
- devise_token_auth + omniauthにログアウトを追加 - Qiita
他ライブラリでの認証方法
devise_token_authのREADME.mdに記載されている。
- React: redux-token-auth
- ng-token-auth: AngularJS
- vuejsは記載されていないが vue-auth/drivers/auth at master · websanova/vue-authが使える模様(使用例がほしい。。。)