Spring Cloudセキュリティ入門

Spring Cloudセキュリティの紹介

1. 概要

Spring Cloud Securityモジュールは、Spring Bootアプリケーションのトークンベースのセキュリティに関連する機能を提供します。

具体的には、OAuth2ベースのSSOをより簡単にします。リソースサーバー間でのトークンの中継のサポート、および組み込みZuulプロキシを使用したダウンストリーム認証の構成をサポートします。

この簡単な記事では、Spring Bootクライアントアプリケーション、承認サーバー、およびリソースサーバーとして機能するRESTAPIを使用してこれらの機能を構成する方法について説明します。

この例では、クラウドセキュリティ機能を示すためにSSOを使用するクライアントアプリケーションは1つしかありませんが、一般的なシナリオでは、シングルサインオンの必要性を正当化するために少なくとも2つのクライアントアプリケーションがあります。

2. クラウドセキュリティアプリのクイックスタート

configuring SSO in a Spring Boot application.から始めましょう

まず、spring-cloud-starter-oauth2の依存関係を追加する必要があります。


    org.springframework.cloud
    spring-cloud-starter-oauth2
    2.2.2.RELEASE

これにより、spring-cloud-starter-securityの依存関係も発生します。

http://localhost:7070/authserver.でローカルにデプロイされたWe can configure any social site as an Auth Server for our site or we can use our own server. In our case, we’ve chosen the latter option and configured an application that acts as an Authorization Server – which is

承認サーバーはJWTトークンを使用します。

さらに、クライアントがユーザーの資格情報を取得できるようにするには、ポート9000で実行されているリソースサーバーを、これらの資格情報を提供できるエンドポイントで構成する必要があります。

ここでは、http://localhost:9000/user.で使用可能な/userエンドポイントを構成しました

承認サーバーとリソースサーバーの設定方法の詳細については、previous article hereを確認してください。

これで、クライアントアプリケーションの構成クラスにアノテーションを追加できます。

@Configuration
@EnableOAuth2Sso
public class SiteSecurityConfigurer
  extends WebSecurityConfigurerAdapter {

    @Override
    protected void configure(HttpSecurity http) throws Exception {
        // ...
    }
}

Any requests that require authentication will be redirected to the Authorization Server.これを機能させるには、サーバーのプロパティも定義する必要があります。

security:
  oauth2:
    client:
      accessTokenUri: http://localhost:7070/authserver/oauth/token
      userAuthorizationUri: http://localhost:7070/authserver/oauth/authorize
      clientId: authserver
      clientSecret: passwordforauthserver
    resource:
      userInfoUri: http://localhost:9000/user

上記の構成が機能するためには、クラスパスにspring-boot-starter-securityが必要であることに注意してください。

3. アクセストークンの中継

トークンを中継している間、OAuth2クライアントは受信したOAuth2トークンを発信リソースリクエストに転送します。

@EnableOauth2Ssoアノテーションを宣言したので、Spring BootはリクエストスコープにOAuth2ClientContextBeanを追加します。 これに基づいて、クライアントアプリケーションで独自のOAuth2RestTemplateを作成できます。

@Bean
public OAuth2RestOperations restOperations(
  OAuth2ProtectedResourceDetails resource, OAuth2ClientContext context) {
    return new OAuth2RestTemplate(resource, context);
}

Bean,を構成すると、コンテキストはアクセストークンを要求されたサービスに転送し、有効期限が切れるとトークンを更新します。

4. RestTemplateを使用したOAuthトークンのリレー

以前、クライアントアプリケーションでタイプOAuth2RestTemplaterestOperationsBeanを定義しました。 その結果、クライアントからのwe can use the getForObject() method of OAuth2RestTemplate to send a request with the necessary tokens to a protected Resource server

まず、リソースサーバーで認証を必要とするエンドポイントを定義しましょう。

@GetMapping("/person")
@PreAuthorize("hasAnyRole('ADMIN', 'USER')")
public @ResponseBody Person personInfo(){
    return new Person("abir", "Dhaka", "Bangladesh", 29, "Male");
 }

これは、PersonオブジェクトのJSON表現を返す単純なRESTエンドポイントです。

さて、we can send a request from the Client application using the getForObject() method which will relay the token to the Resource Server

@Autowired
private RestOperations restOperations;

@GetMapping("/personInfo")
public ModelAndView person() {
    ModelAndView mav = new ModelAndView("personinfo");
    String personResourceUrl = "http://localhost:9000/person";
    mav.addObject("person",
      restOperations.getForObject(personResourceUrl, String.class));

    return mav;
}

5. トークンリレー用のZuulの構成

トークンをダウンストリームでプロキシサービスに中継する場合は、Spring Cloud Zuul Embedded ReverseProxyを使用できます。

まず、Zuulを使用するためにMaven依存関係を追加する必要があります。


    org.springframework.cloud
    spring-cloud-starter-netflix-zuul

次に、クライアントアプリケーションの構成クラスに@EnableZuulProxyアノテーションを追加する必要があります。

@Configuration
@EnableOAuth2Sso
@EnableZuulProxy
public class SiteSecurityConfigurer
  extends WebSecurityConfigurerAdapter {
    //...
}

あとは、Zuul構成プロパティをapplication.ymlファイルに追加するだけです。

zuul:
  sensitiveHeaders: Cookie,Set-Cookie
  routes:
    resource:
      path: /api/**
      url: http://localhost:9000
    user:
      path: /user/**
      url: http://localhost:9000/user

クライアントアプリケーションの/apiエンドポイントに到達するすべての要求は、リソースサーバーのURLにリダイレクトされます。 また、ユーザー資格情報エンドポイントのURLを提供する必要があります。

6. 結論

この簡単な記事では、OAuth2とZuulでSpring Cloud Securityを使用して、セキュリティで保護された承認サーバーとリソースサーバーを構成する方法と、Oauth2RestTemplateとEmbedded ZuulProxyを使用してサーバー間でOAuth2トークンを中継する方法について説明しました。

いつものように、コードはover on GitHubで利用できます。