Goアプリケーションに認可を追加する
このガイドは、新規または既存のGo APIアプリケーションにgo-jwt-middlewareパッケージを使ってAuth0を統合する方法を説明します。
Auth0 DashboardでAPIをまだ作成していない場合は、対話型のセレクターを使ってAuth0 APIを新規作成します。そうでない場合は、プロジェクトに既存のAPIを選択することができます。
Auth0 Dashboardを使って初めてAPIをセットアップする場合には、使用の開始ガイドを確認してください。
それぞれのAuth0 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)
go.mod
ファイルを追加して、必要な依存関係をすべてリストします。
// go.mod
module 01-Authorization-RS256
go 1.21
require (
github.com/auth0/go-jwt-middleware/v2 v2.2.0
github.com/joho/godotenv v1.5.1
)
Was this helpful?
次のシェルコマンドを実行して、依存関係をダウンロードします:
go mod download
Was this helpful?
アプリの構成を保存するために、.env
ファイルをプロジェクトディレクトリのルート内に作成します。その後、環境変数を入力します:
# The URL of our Auth0 Tenant Domain.
If you're using a Custom Domain, be sure to set this to that value instead.
AUTH0_DOMAIN='{yourDomain}'
Our Auth0 API's Identifier.
AUTH0_AUDIENCE='{yourApiIdentifier}'
Was this helpful?
EnsureValidToken
ミドルウェア関数はアクセストークンを検証します。この関数は、保護したいすべてのエンドポイントに適用することができます。トークンが有効であれば、エンドポイントがリソースを開放します。トークンが無効であれば、APIが401 Authorization
エラーを返します。
受信する要求のアクセストークンを検証するには、go-jwt-middlewareミドルウェア をセットアップします。
APIはデフォルトで、RS256をトークン署名アルゴリズムとしてセットアップします。RS256は秘密鍵と公開鍵のペアで機能するため、トークンはAuth0アカウントの公開鍵を使用して検証することができます。この公開鍵には、https://{yourDomain}/.well-known/jwks.jsonでアクセスすることができます。
トークンが要求されたリソースへのアクセスに十分なスコープを持っているか確認する機能を含めてください。
HasScope
関数を作成して、応答を返す前に、アクセストークンに正しいスコープがあることを確認します。
この例では、EnsureToken
ミドルウェアを使用しない/api/public
エンドポイントを作成して、未認証の要求にも対応できるようにします。
EnsureToken
ミドルウェアを必要とする/api/private
エンドポイントを作成して、追加スコープのないアクセストークンを含む認証済み要求にのみ利用できるようにします。
EnsureToken
ミドルウェアとHasScope
を必要とする/api/private-scoped
エンドポイントを作成して、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?
checkpoint.header
アプリケーションの構成が完了したら、アプリケーションを実行して次の点を確認します:
GET /api/public
が認証を必要としない要求に使用できる。GET /api/private
が認証された要求に使用できる。GET /api/private-scoped
がread: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:
- Auth0 Dashboard - Learn how to configure and manage your Auth0 tenant and applications
- go-jwt-middleware 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.