Flask APIアプリケーションに認可を追加する
このガイドは、Flaskを使ってビルドされた新規または既存のPython APIにAuth0を統合する方法を説明します。
Auth0 DashboardでAPIをまだ作成していない場合は、対話型のセレクターを使ってAuth0 APIを新規作成します。そうでない場合は、統合したいプロジェクトを表す既存のAPIを選択することができます。
または、Auth0 Dashboardを使って初めてAPIをセットアップする方法を使用の開始ガイドで確認することもできます。
Auth0にあるAPIはそれぞれAPI識別子を使って構成され、アプリケーションのコードはAPI識別子をオーディエンスとしてアクセストークンを検証します。
アクセス許可は、ユーザーの代わりに、提供されたアクセストークンを使ってどのようにしてリソースにアクセスできるのかを定義できるようにします。たとえば、ユーザーがマネージャーアクセスレベルを持つ場合には、messages
リソースに対して読み出しアクセスを付与し、管理者アクセスレベルを持つ場合には、書き込みアクセスを付与することができます。
Auth0 Dashboardの[APIs]セクションにある[Permissions(権限)]ビューで使用可能なアクセス許可を定義することができます。
![[Auth0 Dashboard]>[Applications(アプリケーション)]>[APIs]>[Specific API(特定のAPI]>[Permissions(権限)]タブ](http://images.ctfassets.net/cdy7uua7fh8z/1s3Yp5zqJiKiSWqbPSezNO/acef814282795bef6921535f044f96e9/Quickstarts_API.png)
requirements.txt
に次の依存関係を追加します:
# /requirements.txt
flask
Authlib
Was this helpful?
Authlibという名前のライブラリーを使用して、ResourceProtectorを作成します。これはFlaskデコレーターの一種で、該当するバリデーターを使ってリソース(APIルート)を保護します。
バリデーターは、リソースに渡すアクセストークンに有効な署名とクレームがあることを検証します。
AuthLibのJWTBearerTokenValidator
バリデーターに多少の変更を加えて、アクセストークンの検証要件が満たされるようにします。
Auth0JWTBearerTokenValidator
を作成するには、domain
とaudience
(API識別子)に渡すことが必要です。そうすると、トークンの署名を検証するのに必要な公開鍵が取得され、JWTBearerTokenValidator
クラスに渡されます。
そして、クラスのclaims_options
をオーバーライドし、トークンのexpiry、audience、issueクレームが要件を満たして有効であることを確認します。
次に、3つのAPIルートを使ってFlaskアプリケーションを作成します。
/api/public
:認証を必要としないパブリックエンドポイントです。/api/private
:有効なJWTアクセストークンを必要とするプライベートエンドポイントです。/api/private-scoped
:与えられたscope
を含む有効なJWTアクセストークンを必要とするプライベートエンドポイントです。
保護されたルートにはrequire_auth
デコレーターがあり、これは、以前に作成したAuth0JWTBearerTokenValidator
を使用するResourceProtector
です。
Auth0JWTBearerTokenValidator
を作成するには、テナントのドメインと以前に作成したAPIのAPI識別子に渡します。
private_scoped
ルートのrequire_auth
デコレーターは、追加の引数である"read:messages"
を受け付けます。これは、以前に作成したアクセス許可(スコープ)について、アクセストークンをチェックします。
APIを呼び出す
APIを呼び出すにはアクセストークンが必要です。テスト用のアクセストークンは、API設定の[Test(テスト)]ビューから取得することができます。
![[Auth0 Dashboard]>[Applications(アプリケーション)]>[API]>[Specific API(特定のAPI]>[Test(テスト)]タブ](http://images.ctfassets.net/cdy7uua7fh8z/6jeVBuypOGX5qMRXeJn5ow/dd20eb74e1e9079287762ce33dcf8e2d/Quickstart_Example_App_API.png)
要求のAuthorization
ヘッダーにアクセストークンを指定します。
curl --request get \
--url 'http:///{yourDomain}/api_path' \
--header 'authorization: Bearer YOUR_ACCESS_TOKEN_HERE'
Was this helpful?
var client = new RestClient("http:///{yourDomain}/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:///{yourDomain}/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:///{yourDomain}/api_path")
.header("authorization", "Bearer YOUR_ACCESS_TOKEN_HERE")
.asString();
Was this helpful?
var axios = require("axios").default;
var options = {
method: 'get',
url: 'http:///{yourDomain}/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:///{yourDomain}/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(@"%@", error);
} else {
NSHTTPURLResponse *httpResponse = (NSHTTPURLResponse *) response;
NSLog(@"%@", httpResponse);
}
}];
[dataTask resume];
Was this helpful?
$curl = curl_init();
curl_setopt_array($curl, [
CURLOPT_URL => "http:///{yourDomain}/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 => [
"authorization: Bearer YOUR_ACCESS_TOKEN_HERE"
],
]);
$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", "/{yourDomain}/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:///{yourDomain}/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:///{yourDomain}/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?
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:
- Auth0 Dashboard - Learn how to configure and manage your Auth0 tenant and applications
- auth0-python SDK - Explore the SDK used in this tutorial more fully
- Auth0 Marketplace - Discover integrations you can enable to extend Auth0’s functionality
Sign up for an or to your existing account to integrate directly with your own tenant.