Spring Framework Advent Calendar 2011 part.3 - Spring Security で LDAP 認証を行う

Spring Framework Advent Calendar の 3 日目です。早くもネタが尽きてきました。本日も Spring Security ネタです。

業務アプリケーションにおけるユーザー認証で圧倒的に多いのは、DB接続を用いた認証でしょう。Spring Security はもちろん、ユーザーDBと認証基盤との接続レイヤーを用意してくれています。スタンダードであるこの方式については書籍などでもよく取り上げられるでしょうから、ここでは触れません。今回は、DB接続による認証に比べるとマイナーな LDAP 認証をあつかうケースについて紹介します。

Spring Security は、認証を行う方法を提供するサービスを AuthenticationProvider として抽象化しています。具体的な実装として、たとえば以下のようなものがあります。

AuthenticationProvider 説明
DaoAuthenticationProvider データベースアクセスによる認証
LdapAuthenticationProvider LDAP による認証
OpenIDAuthenticationProvider OpenID による認証
PreAuthenticatedAuthenticationProvider すでに認証されている場合にチェックなしで認証を通す
RememberMeAuthenticationProvider 「ログインを記憶する」のような remember me 機能での認証


認証において利用する AuthenticationProvider の情報は、例によって Spring の Bean 定義ファイルに記述しておく必要があります。が、DaoAuthenticationProvider のような利用頻度の高い認証プロバイダーの設定は、Spring Security の namespace 拡張によって、簡易的に記述できるようになっています。そして、LdapAuthenticationProvider も、この簡易記法がサポートされています!

  <sec:ldap-server url="ldap://your.ldap.server.domain:389/dc=foo,dc=bar" />
  
  <sec:authentication-manager>
    <sec:ldap-authentication-provider user-dn-pattern="uid={0},ou=people" />
  </sec:authentication-manager>


LDAP 認証を利用するには、

  • LDAP サーバーの設定
  • LdapAuthenticationProvider を使う宣言および、サーバーへの問い合わせ設定

の2つの設定を行う必要がありますが、ご覧の通り、これらは両方とも簡易記法がサポートされています。時間がなくて詳細まで説明している時間がないのが残念ですが、参考までに公式サイトへのリンクを張っておきます。
http://static.springsource.org/spring-security/site/docs/3.0.x/reference/ldap.html


こうした XML の namespace 拡張を用いるには、Bean 定義ファイルの先頭で namespace 宣言を追加してやる必要がある点には注意が必要です。たとえば、context, mvc, sec を利用できるようにした設定は以下のようになります。

<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
  xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
  xmlns:context="http://www.springframework.org/schema/context"
  xmlns:mvc="http://www.springframework.org/schema/mvc"
  xmlns:sec="http://www.springframework.org/schema/security"
  xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans.xsd
    http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context-3.0.xsd
    http://www.springframework.org/schema/mvc http://www.springframework.org/schema/mvc/spring-mvc-3.0.xsd
    http://www.springframework.org/schema/security http://www.springframework.org/schema/security/spring-security-3.0.4.xsd">


Eclipse であれば、Spring IDE などのプラグインを導入することで、こうした記述をいくらか楽にしたり、また XML の補完もサポートしてくれますので、導入をおすすめします。STS *1 を使うのもよいでしょう。

*1:Spring Tool Suite. Spring 開発に特化した Eclipse ベースのIDE