Spring Security OAuth2 - 単純なトークンの失効

Spring Security OAuth2 –シンプルなトークン取り消し

1. 概要

このクイックチュートリアルでは、Spring Securityで実装されたOAuth Authorization Serverによって付与されたトークンを取り消す方法を説明します。

ユーザーがログアウトしても、トークンはトークンストアからすぐには削除されず、代わりに有効期限が切れるまで有効のままになります。

そのため、トークンの取り消しとは、トークンストアからそのトークンを削除することを意味します。

また、この記事では、フレームワークでの標準トークン実装のみを説明し、JWTトークンについては説明していません。

2. TokenStore

まず、トークンストアを設定しましょう。付随するデータソースとともに、JdbcTokenStoreを使用します。

@Bean
public TokenStore tokenStore() {
    return new JdbcTokenStore(dataSource());
}

@Bean
public DataSource dataSource() {
    DriverManagerDataSource dataSource =  new DriverManagerDataSource();
    dataSource.setDriverClassName(env.getProperty("jdbc.driverClassName"));
    dataSource.setUrl(env.getProperty("jdbc.url"));
    dataSource.setUsername(env.getProperty("jdbc.user"));
    dataSource.setPassword(env.getProperty("jdbc.pass"));
    return dataSource;
}

3. DefaultTokenServices Bean

すべてのトークンを処理するクラスはDefaultTokenServicesであり、構成でBeanとして定義する必要があります。

@Bean
@Primary
public DefaultTokenServices tokenServices() {
    DefaultTokenServices defaultTokenServices = new DefaultTokenServices();
    defaultTokenServices.setTokenStore(tokenStore());
    defaultTokenServices.setSupportRefreshToken(true);
    return defaultTokenServices;
}

4. トークンのリストの表示

管理目的で、現在有効なトークンを表示する方法も設定しましょう。

コントローラのTokenStoreにアクセスし、指定されたクライアントIDに対して現在保存されているトークンを取得します。

@Resource(name="tokenStore")
TokenStore tokenStore;

@RequestMapping(method = RequestMethod.GET, value = "/tokens")
@ResponseBody
public List getTokens() {
    List tokenValues = new ArrayList();
    Collection tokens = tokenStore.findTokensByClientId("sampleClientId");
    if (tokens!=null){
        for (OAuth2AccessToken token:tokens){
            tokenValues.add(token.getValue());
        }
    }
    return tokenValues;
}

5. アクセストークンの取り消し

トークンを無効にするために、ConsumerTokenServicesインターフェースからrevokeToken()APIを利用します。

@Resource(name="tokenServices")
ConsumerTokenServices tokenServices;

@RequestMapping(method = RequestMethod.POST, value = "/tokens/revoke/{tokenId:.*}")
@ResponseBody
public String revokeToken(@PathVariable String tokenId) {
    tokenServices.revokeToken(tokenId);
    return tokenId;
}

もちろんこれは非常にデリケートな操作であるため、内部でのみ使用するか、適切なセキュリティを設定して公開するように細心の注意を払う必要があります。

6. フロントエンド

この例のフロントエンドでは、有効なトークンのリスト、失効リクエストを行うログインユーザーが現在使用しているトークン、およびユーザーが失効させたいトークンを入力できるフィールドを表示します。

$scope.revokeToken =
  $resource("http://localhost:8082/spring-security-oauth-resource/tokens/revoke/:tokenId",
  {tokenId:'@tokenId'});
$scope.tokens = $resource("http://localhost:8082/spring-security-oauth-resource/tokens");

$scope.getTokens = function(){
    $scope.tokenList = $scope.tokens.query();
}

$scope.revokeAccessToken = function(){
    if ($scope.tokenToRevoke && $scope.tokenToRevoke.length !=0){
        $scope.revokeToken.save({tokenId:$scope.tokenToRevoke});
        $rootScope.message="Token:"+$scope.tokenToRevoke+" was revoked!";
        $scope.tokenToRevoke="";
    }
}

ユーザーが失効したトークンを再度使用しようとすると、ステータスコード401の「無効なトークン」エラーが表示されます。

7. 更新トークンの取り消し

更新トークンを使用して、新しいアクセストークンを取得できます。 アクセストークンが取り消されるたびに、アクセストークンとともに受信された更新トークンは無効になります。

更新トークン自体も無効にする場合は、クラスJdbcTokenStoreのメソッドremoveRefreshToken()を使用できます。これにより、ストアから更新トークンが削除されます。

@RequestMapping(method = RequestMethod.POST, value = "/tokens/revokeRefreshToken/{tokenId:.*}")
@ResponseBody
public String revokeRefreshToken(@PathVariable String tokenId) {
    if (tokenStore instanceof JdbcTokenStore){
        ((JdbcTokenStore) tokenStore).removeRefreshToken(tokenId);
    }
    return tokenId;
}

取り消された後に更新トークンが無効になったことをテストするために、次のテストを作成します。このテストでは、アクセストークンを取得して更新し、更新トークンを削除して、もう一度更新を試みます。

「無効なリフレッシュトークン」:私たちは失効した後、我々は応答エラーを受信しますことがわかります。

public class TokenRevocationLiveTest {
    private String refreshToken;

    private String obtainAccessToken(String clientId, String username, String password) {
        Map params = new HashMap();
        params.put("grant_type", "password");
        params.put("client_id", clientId);
        params.put("username", username);
        params.put("password", password);

        Response response = RestAssured.given().auth().
          preemptive().basic(clientId,"secret").and().with().params(params).
          when().post("http://localhost:8081/spring-security-oauth-server/oauth/token");
        refreshToken = response.jsonPath().getString("refresh_token");

        return response.jsonPath().getString("access_token");
    }

    private String obtainRefreshToken(String clientId) {
        Map params = new HashMap();
        params.put("grant_type", "refresh_token");
        params.put("client_id", clientId);
        params.put("refresh_token", refreshToken);

        Response response = RestAssured.given().auth()
          .preemptive().basic(clientId,"secret").and().with().params(params)
          .when().post("http://localhost:8081/spring-security-oauth-server/oauth/token");

        return response.jsonPath().getString("access_token");
    }

    private void authorizeClient(String clientId) {
        Map params = new HashMap();
        params.put("response_type", "code");
        params.put("client_id", clientId);
        params.put("scope", "read,write");

        Response response = RestAssured.given().auth().preemptive()
          .basic(clientId,"secret").and().with().params(params).
          when().post("http://localhost:8081/spring-security-oauth-server/oauth/authorize");
    }

    @Test
    public void givenUser_whenRevokeRefreshToken_thenRefreshTokenInvalidError() {
        String accessToken1 = obtainAccessToken("fooClientIdPassword", "john", "123");
        String accessToken2 = obtainAccessToken("fooClientIdPassword", "tom", "111");
        authorizeClient("fooClientIdPassword");

        String accessToken3 = obtainRefreshToken("fooClientIdPassword");
        authorizeClient("fooClientIdPassword");
        Response refreshTokenResponse = RestAssured.given().
          header("Authorization", "Bearer " + accessToken3)
          .get("http://localhost:8082/spring-security-oauth-resource/tokens");
        assertEquals(200, refreshTokenResponse.getStatusCode());

        Response revokeRefreshTokenResponse = RestAssured.given()
          .header("Authorization", "Bearer " + accessToken1)
          .post("http://localhost:8082/spring-security-oauth-resource/tokens/revokeRefreshToken/"+refreshToken);
        assertEquals(200, revokeRefreshTokenResponse.getStatusCode());

        String accessToken4 = obtainRefreshToken("fooClientIdPassword");
        authorizeClient("fooClientIdPassword");
        Response refreshTokenResponse2 = RestAssured.given()
          .header("Authorization", "Bearer " + accessToken4)
          .get("http://localhost:8082/spring-security-oauth-resource/tokens");
        assertEquals(401, refreshTokenResponse2.getStatusCode());
    }
}

8. 結論

このチュートリアルでは、OAuthアクセストークンとOauth更新トークンを取り消す方法を示しました。

このチュートリアルの実装はthe GitHub projectにあります。これはMavenベースのプロジェクトであるため、そのままインポートして実行するのは簡単です。