チーム開発の続き
Spring Securityによる認証
サイトにログイン機能を追加するには、Spring Security を使用すると簡単に実装できる。
Spring Security の設定ファイルを読み込ませるために、contextConfigLocation を追加する。
web.xml
<context-param> <param-name>contextConfigLocation</param-name> <param-value>classpath:spring/application-config.xml</param-value> </context-param> <context-param> <param-name>contextConfigLocation</param-name> <param-value>classpath:spring/spring-security.xml</param-value> </context-param>
すべてのページにアクセスする前にアクセス権限のチェックを実行させるため、web.xml の最後に、フィルターを追加する。
web.xml
<filter> <filter-name>springSecurityFilterChain</filter-name> <filter-class>org.springframework.web.filter.DelegatingFilterProxy</filter-class> </filter> <filter-mapping> <filter-name>springSecurityFilterChain</filter-name> <url-pattern>/*</url-pattern> </filter-mapping>
src/main/resources/spring フォルダに、spring-security.xml を作成する。
まずはXMLで指定したユーザーでログインできるようにする。
ユーザー名: taro
パスワード: abcd
あとでDBから取得するように変更する。
spring-security.xml
<?xml version="1.0" encoding="UTF-8"?> <beans:beans xmlns="http://www.springframework.org/schema/security" xmlns:beans="http://www.springframework.org/schema/beans" xmlns:sec="http://www.springframework.org/schema/security" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://www.springframework.org/schema/security http://www.springframework.org/schema/security/spring-security.xsd 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.xsd"> <beans:bean id="dataSource" class="org.springframework.jdbc.datasource.DriverManagerDataSource"> <beans:property name="driverClassName" value="org.hsqldb.jdbc.JDBCDriver" /> <beans:property name="url" value="jdbc:hsqldb:hsql://localhost/exam" /> <beans:property name="username" value="user" /> <beans:property name="password" value="password" /> </beans:bean> <beans:bean id="encoder" class="org.springframework.security.crypto.password.StandardPasswordEncoder" /> <sec:http pattern="/" security="none"/> <sec:http pattern="/index.jsp" security="none"/> <sec:http auto-config="true"> <intercept-url pattern="/**" access="ROLE_USER" /> </sec:http> <authentication-manager> <authentication-provider> <user-service> <user name="taro" password="abcd" authorities="ROLE_USER" /> </user-service> </authentication-provider> </authentication-manager> </beans:beans>