OAuth2の勉強も兼ねて、Spring Boot x Spring Security x Kotlin でOAuth2サーバを作ってみました
成果物
環境
- Java 1.8
- Gradle
または、IntelliJ IDEAをインストール
起動方法
1.依存関係のインストール
$ gradle dependencies
2.サーバの起動
$ gradle bootRun
IntelliJ IDEAの場合はプロジェクトを開いたあと、
- Application.ktを右クリック → run
- Gradleタブを開く → Tasks → application → bootRun
のどちらかで起動できます
動作確認
OAuth Bearer Token
正しいアクセス情報
アクセストークンが取得できる
$ curl -X POST \
-d client_id=client_id \
-d client_secret=client_secret \
-d grant_type=password \
-d username=user \
-d password=password \
http://localhost:8080/oauth/token
{"access_token":"[your_access_token]","token_type":"bearer","expires_in":43199,"scope":"read"}
クライアント情報が誤っている場合
invalid_clientのエラーが発生
$ curl -X POST \
-d client_id=client_id \
-d client_secret=client_secret2 \
-d grant_type=password \
-d username=user \
-d password=password \
http://localhost:8080/oauth/token
{"error":"invalid_client","error_description":"Bad client credentials"}
ユーザ情報が誤っている場合
invalid_grantのエラーが発生
$ curl -X POST \
-d client_id=client_id \
-d client_secret=client_secret \
-d grant_type=password \
-d username=user \
-d password=password2 \
http://localhost:8080/oauth/token
{"error":"invalid_grant","error_description":"Bad credentials"}
リソースの取得
正しいアクセストークン
$ curl -H "Authorization: Bearer [your_access_token]" localhost:8080/hello Hello!
アクセストークンがない場合
unauthorizedのエラーが発生
$ curl http://localhost:8080
{"error":"unauthorized","error_description":"Full authentication is required to access this resource"}
アクセストークンが無効な場合
invalid_tokenのエラーが発生
$ curl -H "Authorization: Bearer bad_access_token" localhost:8080/hello
{"error":"invalid_token","error_description":"Invalid access token: bad_access_token"}