Spring SecurityでOAuth2サーバを作ってみた
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認証
正しいアクセス情報
アクセストークンが取得できる
$ 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"}