Thymeleafを使った春のセキュリティ

Thymeleafを使用したSpring Security

1. 概要

In this quick tutorial, we’ll focus on Spring Security with Thymeleaf.セキュリティダイアレクトの使用法を示すSpringBootアプリケーションを作成します。

フロントエンドテクノロジーの選択肢はThymeleafです。これは、Spring MVCフレームワークとの良好な統合を備えた、最新のサーバー側Webテンプレートエンジンです。 詳細については、intro articleをご覧ください。

最後に、Spring Security DialectはThymeleafのエクストラモジュールであり、当然、これらの両方を統合するのに役立ちます。

Spring Boot tutorialの記事で作成した単純なプロジェクトを使用します。また、Thymeleaf tutorial with Springがあり、標準のThymeleaf構成を見つけることができます。

2. 依存関係

まず、Mavenpom.xmlに新しい依存関係を追加しましょう。


    org.thymeleaf.extras
    thymeleaf-extras-springsecurity4

常に最新バージョンを使用することをお勧めします。これはMaven Centralで解決できます。

3. Spring Securityの構成

次に、SpringSecurityの構成を定義しましょう。

また、セキュリティの方言の使用方法を示すために、少なくとも2人の異なるユーザーが必要です。

@Configuration
@EnableWebSecurity
public class SecurityConfiguration extends WebSecurityConfigurerAdapter {

    // [...]
    @Autowired
    public void configureGlobal(AuthenticationManagerBuilder auth)
      throws Exception {
        auth
          .inMemoryAuthentication()
          .withUser("user").password(passwordEncoder().encode("password")).roles("USER")
          .and()
          .withUser("admin").password(passwordEncoder().encode("admin")).roles("ADMIN");
    }

    @Bean
    public BCryptPasswordEncoder passwordEncoder() {
        return new BCryptPasswordEncoder();
    }
}

ご覧のとおり、configureGlobal(AuthenticationManagerBuilder auth)で、ユーザー名とパスワードを使用して2人のユーザーを定義します。 これらを使用してアプリケーションにアクセスできます。

ユーザーにはそれぞれADMINUSERという異なる役割があり、役割に基づいて特定のコンテンツを表示できます。

4. セキュリティ方言

The Spring Security dialect allows us to conditionally display content based on user roles, permissions or other security expressions.また、SpringAuthenticationオブジェクトへのアクセスも提供します。

セキュリティ方言の例が含まれているインデックスページを見てみましょう。



    
        Welcome to Spring Security Thymeleaf tutorial
    
    
        

Welcome

Spring Security Thymeleaf tutorial

Text visible to user.
Text visible to admin.
Text visible only to authenticated users.
Authenticated username:
Authenticated user roles:

Spring Security Dialectに固有の属性sec:authorizeおよびsec:authenticationを確認できます。

これらについて1つずつ説明しましょう。

4.1. sec:authorizeを理解する

簡単に言うと、sec:authorize属性を使用して表示されるコンテンツを制御します。

たとえば、ロールUSERを持つユーザーにのみコンテンツを表示する場合は、次のようにします。<div sec:authorize=”hasRole(‘USER')”>.

そして、すべての認証済みユーザーへのアクセスを広げたい場合、次の式を使用できます。

4.2. sec:authenticationを理解する

Spring SecurityAuthenticationインターフェースは、認証されたプリンシパルまたは認証要求に関する有用なメソッドを公開します。

access an authentication object withing Thymeleafには、単に<div sec:authentication=”name”>または<div sec:authentication=”principal.authorities”>.を使用できます。

前者は認証されたユーザーの名前へのアクセスを許可し、後者は認証されたユーザーのロールへのアクセスを許可します。

5. 概要

この記事では、Thymeleafの単純なSpring BootアプリケーションでSpring Securityサポートを使用しました。

いつものように、この記事に示されているコードの作業バージョンは、GitHub repositoryで入手できます。