Express.js APIアプリケーションに認可を追加する

このガイドは、新規または既存のExpress.js APIアプリケーションにexpress-oauth2-jwt-bearerパッケージを使ってAuth0を統合する方法を説明します。

Auth0 DashboardでAPIをまだ作成していない場合は、対話型のセレクターを使ってAuth0 APIを新規作成します。そうでない場合は、既存のプロジェクトAPIを選択します。

Auth0 Dashboardを使って初めてAPIをセットアップする場合には、使用の開始ガイドを確認してください。それぞれのAuth0 APIにはAPI識別子があり、アプリケーションにアクセストークンの検証で使用されます。

1

アクセス許可を定義する

アクセス許可は、ユーザーの代わりに、提供されたアクセストークンを使ってどのようにしてリソースにアクセスできるのかを定義できるようにします。たとえば、ユーザーがマネージャーアクセスレベルを持つ場合には、messagesリソースに対して読み出しアクセスを付与し、管理者アクセスレベルを持つ場合には、書き込みアクセスを付与することができます。

Auth0 Dashboardの[APIs]セクションにある[Permissions(権限)]ビューで使用可能なアクセス許可を定義することができます。

null

2

依存関係をインストールする

まず、npmでSDKをインストールします。

npm install --save express-oauth2-jwt-bearer

Was this helpful?

/

3

ミドルウェアを構成する

ドメインとAPI識別子を使って、express-oauth2-jwt-bearerを構成します。

右に示したcheckJwtミドルウェアは、要求に含まれるユーザーのアクセストークンが有効かを確認します。トークンが有効でない場合、ユーザーがエンドポイントにアクセスしようとすると、「401 Authorization」というエラーが発生します。

ミドルウェアは、トークンに要求されたリソースにアクセスするだけの十分なスコープがあるかを確認しません。

4

APIエンドポイントを保護する

有効なJWTを必須して個々のルートを保護するには、express-oauth2-jwt-bearerから構築されたcheckJwtミドルウェアでルートを構成します。

特定のスコープを検索するために、個々のルートを構成することができます。これを実現するには、requiresScopeメソッドで別のミドルウェアをセットアップします。必要なスコープを提供し、認可を追加したいルートにミドルウェアを適用します。

checkJwtrequiredScopesミドルウェアを保護したいルートに渡します。

この構成では、read:messagesスコープを持つアクセストークンのみがエンドポイントにアクセスすることができます。

APIを呼び出す

APIを呼び出すにはアクセストークンが必要です。テスト用のアクセストークンは、API設定[Test(テスト)]ビューから取得することができます。

null

要求のAuthorizationヘッダーにアクセストークンを指定します。

curl --request get \
--url http:///%7ByourDomain%7D/api_path \
--header 'authorization: Bearer YOUR_ACCESS_TOKEN_HERE'

Was this helpful?

/
var client = new RestClient("http:///%7ByourDomain%7D/api_path");
var request = new RestRequest(Method.GET);
request.AddHeader("authorization", "Bearer YOUR_ACCESS_TOKEN_HERE");
IRestResponse response = client.Execute(request);

Was this helpful?

/
package main
import (
"fmt"
"net/http"
"io/ioutil"
)
func main() {
url := "http:///%7ByourDomain%7D/api_path"
req, _ := http.NewRequest("get", url, nil)
req.Header.Add("authorization", "Bearer YOUR_ACCESS_TOKEN_HERE")
res, _ := http.DefaultClient.Do(req)
defer res.Body.Close()
body, _ := ioutil.ReadAll(res.Body)
fmt.Println(res)
fmt.Println(string(body))
}

Was this helpful?

/
HttpResponse<String> response = Unirest.get("http:///%7ByourDomain%7D/api_path")
.header("authorization", "Bearer YOUR_ACCESS_TOKEN_HERE")
.asString();

Was this helpful?

/
var axios = require("axios").default;
var options = {
method: 'get',
url: 'http:///%7ByourDomain%7D/api_path',
headers: {authorization: 'Bearer YOUR_ACCESS_TOKEN_HERE'}
};
axios.request(options).then(function (response) {
console.log(response.data);
}).catch(function (error) {
console.error(error);
});

Was this helpful?

/
#import <Foundation/Foundation.h>
NSDictionary *headers = @{ @"authorization": @"Bearer YOUR_ACCESS_TOKEN_HERE" };
NSMutableURLRequest *request = [NSMutableURLRequest requestWithURL:[NSURL URLWithString:@"http:///%7ByourDomain%7D/api_path"]
                                                   cachePolicy:NSURLRequestUseProtocolCachePolicy

                                               timeoutInterval:10.0];

[request setHTTPMethod:@"get"];
[request setAllHTTPHeaderFields:headers];
NSURLSession *session = [NSURLSession sharedSession];
NSURLSessionDataTask *dataTask = [session dataTaskWithRequest:request
                                        completionHandler:^(NSData *data, NSURLResponse *response, NSError *error) {

                                            if (error) {

                                                NSLog(@&quot;%@&quot;, error);

                                            } else {

                                                NSHTTPURLResponse *httpResponse = (NSHTTPURLResponse *) response;

                                                NSLog(@&quot;%@&quot;, httpResponse);

                                            }

                                        }];

[dataTask resume];

Was this helpful?

/
$curl = curl_init();
curl_setopt_array($curl, [
CURLOPT_URL => "http:///%7ByourDomain%7D/api_path",
CURLOPT_RETURNTRANSFER => true,
CURLOPT_ENCODING => "",
CURLOPT_MAXREDIRS => 10,
CURLOPT_TIMEOUT => 30,
CURLOPT_HTTP_VERSION => CURL_HTTP_VERSION_1_1,
CURLOPT_CUSTOMREQUEST => "get",
CURLOPT_HTTPHEADER => [
&quot;authorization: Bearer YOUR_ACCESS_TOKEN_HERE&quot;

],
]);
$response = curl_exec($curl);
$err = curl_error($curl);
curl_close($curl);
if ($err) {
echo "cURL Error #:" . $err;
} else {
echo $response;
}

Was this helpful?

/
import http.client
conn = http.client.HTTPConnection("")
headers = { 'authorization': "Bearer YOUR_ACCESS_TOKEN_HERE" }
conn.request("get", "%7ByourDomain%7D/api_path", headers=headers)
res = conn.getresponse()
data = res.read()
print(data.decode("utf-8"))

Was this helpful?

/
require 'uri'
require 'net/http'
url = URI("http:///%7ByourDomain%7D/api_path")
http = Net::HTTP.new(url.host, url.port)
request = Net::HTTP::Get.new(url)
request["authorization"] = 'Bearer YOUR_ACCESS_TOKEN_HERE'
response = http.request(request)
puts response.read_body

Was this helpful?

/
import Foundation
let headers = ["authorization": "Bearer YOUR_ACCESS_TOKEN_HERE"]
let request = NSMutableURLRequest(url: NSURL(string: "http:///%7ByourDomain%7D/api_path")! as URL,
                                    cachePolicy: .useProtocolCachePolicy,

                                timeoutInterval: 10.0)

request.httpMethod = "get"
request.allHTTPHeaderFields = headers
let session = URLSession.shared
let dataTask = session.dataTask(with: request as URLRequest, completionHandler: { (data, response, error) -> Void in
if (error != nil) {
print(error)

} else {
let httpResponse = response as? HTTPURLResponse

print(httpResponse)

}
})
dataTask.resume()

Was this helpful?

/

checkpoint.header

アプリケーションの構成が完了したら、アプリケーションを実行して次の点を確認します:

  • GET /api/publicが認証を必要としない要求に使用できる。

  • GET /api/privateが認証された要求に使用できる。

  • GET /api/private-scopedread:messagesスコープが付与されたアクセストークンを含む認証された要求に使用できる。

Next Steps

Excellent work! If you made it this far, you should now have login, logout, and user profile information running in your application.

This concludes our quickstart tutorial, but there is so much more to explore. To learn more about what you can do with Auth0, check out:

Did it work?

Any suggestion or typo?

Edit on GitHub
Sign Up

Sign up for an or to your existing account to integrate directly with your own tenant.