Django APIアプリケーションに認可を追加する
このガイドは、Djangoを使ってビルドされた新規または既存のPython APIアプリケーションにAuth0を統合する方法を説明します。
Auth0 DashboardでAPIをまだ作成していない場合は、対話型のセレクターを使ってAuth0 APIを新規作成します。そうでない場合は、統合したいプロジェクトを表す既存のAPIを選択することができます。
または、Auth0 Dashboardを使って初めてAPIをセットアップする方法を使用の開始ガイドで確認することもできます。
Auth0にあるAPIはそれぞれAPI識別子を使って構成され、アプリケーションのコードはAPI識別子をオーディエンスとしてアクセストークンを検証します。
アクセス許可は、ユーザーの代わりに、提供されたアクセストークンを使ってどのようにしてリソースにアクセスできるのかを定義できるようにします。たとえば、ユーザーがマネージャーアクセスレベルを持つ場合には、messages
リソースに対して読み取りアクセスを付与し、管理者アクセスレベルを持つ場合には、書き込みアクセスを付与することができます。
Auth0 Dashboardの[API]セクションにある[Permissions(権限)]ビューで使用可能なアクセス許可を定義することができます。以下の例ではread:messages
スコープを使用します。
![[Auth0 Dashboard]>[Applications(アプリケーション)]>[APIs]>[Specific API(特定のAPI]>[Permissions(権限)]タブ](http://images.ctfassets.net/cdy7uua7fh8z/1s3Yp5zqJiKiSWqbPSezNO/acef814282795bef6921535f044f96e9/Quickstarts_API.png)
依存関係をインストールする
requirements.txt
に次の依存関係を追加します:pip install -r requirements.txt
を実行する
Djangoアプリケーションを作成する
Authlibという名前のライブラリーを使用して、ResourceProtectorを作成します。これはDjangoビューのデコレーターの一種で、該当するバリデーターを使ってリソース(APIビュー)を保護します。
バリデーターは、リソースに渡すアクセストークンに有効な署名とクレームがあることを確認して検証します。
AuthLibのJWTBearerTokenValidator
バリデーターに多少の変更を加えて、アクセストークンの検証要件が満たされるようにします。
Auth0JWTBearerTokenValidator
を作成するには、domain
とaudience
(API識別子)に渡すことが必要です。そうすると、トークンの署名を検証するのに必要な公開鍵が取得され、JWTBearerTokenValidator
クラスに渡されます。
そして、クラスのclaims_options
をオーバーライドし、トークンのexpiry
、audience
、issue
クレームが要件を満たして有効であることを確認します。
インタラクティブパネルからのコードを利用して、apiexample/validator.py
ファイルを作成します。
次に、apiexample/views.py
に3つのAPIビューを作成します:
/api/public
:認証を必要としないパブリックエンドポイントです。/api/private
:有効なJWTを必要とするプライベートエンドポイントです。/api/private-scoped
:与えられたscope
を含む有効なJWTを必要とするプライベートエンドポイントです。
保護されたルートにはrequire_auth
デコレーターがあり、これは、以前に作成したAuth0JWTBearerTokenValidator
を使用するResourceProtector
です。
Auth0JWTBearerTokenValidator
を作成するには、テナントのドメインと以前に作成したAPIのAPI識別子に渡します。
private_scoped
ルートのrequire_auth
デコレーターは、追加の引数である"read:messages"
を受け付けます。これは、以前に作成したアクセス許可(スコープ)について、アクセストークンをチェックします。
前の手順では、views.py
ファイルにメソッドを追加しました。次に、DjangoのURL dispatcherを使用して、それらのメソッドをURLへマッピングします。URL dispatcherでは、URLパターンをビューにマッピングすることができます。
apiexample/urls.py
ファイルにURLパターンを追加します。
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}.com/api_path' \
--header 'authorization: Bearer YOUR_ACCESS_TOKEN_HERE'
Was this helpful?
var client = new RestClient("http:///{yourDomain}.com/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}.com/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}.com/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}.com/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}.com/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}.com/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}.com/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}.com/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}.com/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 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.