Goアプリケーションに認可を追加する

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

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

Auth0 Dashboardを使って初めてAPIをセットアップする場合には、使用の開始ガイドを確認してください。

それぞれのAuth0 APIにはAPI識別子があり、アプリケーションにアクセストークンの検証で使用されます。

1

アクセス許可を定義する

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

Auth0 Dashboardの[API]セクションにある[Permissions(権限)]ビューで使用可能なアクセス許可を定義することができます。以下の例ではread:messagesスコープを使用します。

[Auth0 Dashboard]>[Applications(アプリケーション)]>[APIs]>[Specific API(特定のAPI]>[Permissions(権限)]タブ

2

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

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?

/

3

アプリケーションを構成する

アプリの構成を保存するために、.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?

/

4

アクセストークンを検証するミドルウェアを作成する

EnsureValidTokenミドルウェア関数はアクセストークンを検証します。この関数は、保護したいすべてのエンドポイントに適用することができます。トークンが有効であれば、エンドポイントがリソースを開放します。トークンが無効であれば、APIが401 Authorizationエラーを返します。

受信する要求のアクセストークンを検証するには、go-jwt-middlewareミドルウェア をセットアップします。

APIはデフォルトで、RS256をトークン署名アルゴリズムとしてセットアップします。RS256は秘密鍵と公開鍵のペアで機能するため、トークンはAuth0アカウントの公開鍵を使用して検証することができます。この公開鍵には、https://{yourDomain}/.well-known/jwks.jsonでアクセスすることができます。

トークンが要求されたリソースへのアクセスに十分なスコープを持っているか確認する機能を含めてください。

HasScope関数を作成して、応答を返す前に、アクセストークンに正しいスコープがあることを確認します。

5

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

この例では、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(テスト)]タブ

要求の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(@&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:///{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 => [
&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", "/{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-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.