*Java:SpringSecurityの事始め [#u7e1aa5b]
SpringSecurityの事始めです。
SpringMVCを知っている前提です。
***デフォルトの認証画面が出るまで [#t9f032cf]
以下の3つのファイルを編集、作成します。
-pom.xml
-applicationScurity.xml(新規作成)
-web.xml
それぞれのファイルの編集内容を見ていきます。
まず、pom.xmlにSpringSecurityの依存関係を追加します。
-pom.xml
<!-- Security -->
<dependency>
<groupId>org.springframework.security</groupId>
<artifactId>spring-security-core</artifactId>
<version>3.1.0.RELEASE</version>
</dependency>
<dependency>
<groupId>org.springframework.security</groupId>
<artifactId>spring-security-web</artifactId>
<version>3.1.0.RELEASE</version>
</dependency>
<dependency>
<groupId>org.springframework.security</groupId>
<artifactId>spring-security-config</artifactId>
<version>3.1.0.RELEASE</version>
</dependency>
次に、applicationScurity.xmlを作成し、以下の内容を追記します。
-applicationScurity.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:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://www.springframework.org/schema/beans
http://www.springframework.org/schema/beans/spring-beans-3.1.xsd
http://www.springframework.org/schema/security
http://www.springframework.org/schema/security/spring-security-3.1.xsd">
<http auto-config="true">
<intercept-url pattern="/**" access="ROLE_USER" />
</http>
<authentication-manager>
<authentication-provider>
<user-service>
<user name="test" password="test" authorities="ROLE_USER" />
</user-service>
</authentication-provider>
</authentication-manager>
</beans:beans>
次に、web.xmlのContext.xmlの設定の読み込み設定にapplicationSecurity.xmlを追加します。
-web.xml
<context-param>
<param-name>contextConfigLocation</param-name>
<param-value>
classpath:applicationContext.xml classpath:applicationSecurity.xml
</param-value>
</context-param>
また、同じくweb.xmlにSpringSecurityのfilter設定等を追加します。
-web.xml
<!-- SpringSecurityのフィルター設定 -->
<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>
これで、SpringSecurityの標準のログイン画面が出ます。
***ログイン情報の利用 [#rcd19017]
ログイン時に、Controllerからログイン情報を取得する場合、Controllerのメソッドの引数に「Principal」を追加します。
例えば、以下のとおりです。
@RequestMapping(value = "/")
public String index(Model model, Principal principal) {
String message = "Hello World ! :" + principal.getName();
model.addAttribute("helloMessage", message);
return "indexView";
}
すると、ログインしたユーザ名が取得できます。
***DBのユーザ情報を使用して認証 [#a24bcc92]
dataSourceの設定は済みの想定です。
まず、テーブルを用意します。
CREATE TABLE users(
user_id int(10) NOT NULL AUTO_INCREMENT,
user_name varchar(50) NOT NULL,
password text NOT NULL,
enabled tinyint( 1 ) NOT NULL DEFAULT '1',
role varchar(100) NOT NULL,
PRIMARY KEY (user_id)
)
して、このテーブルにユーザ情報をinsertします。
INSERT INTO users ( user_name , password , role)
VALUES ( 'testUser', 'password' , 'ROLE_USER' );
次に、applicationScurity.xmlの内容を以下のとおりに書き換えます。
-書き換え前
<user-service>
<user name="hoge" password="fuga" authorities="ROLE_USER" />
</user-service>
-書き換え後
<jdbc-user-service data-source-ref="dataSource"
users-by-username-query="SELECT user_name, password, enabled FROM users WHERE user_name = ?"
authorities-by-username-query="SELECT user_name, role FROM users WHERE user_name = ?"
/>
すると、DBに登録したユーザで認証できるようになります。
***カスタムログイン画面の設定 [#kb4e13e1]
SpringSecurityデフォルトのログインが面からカスタムのログイン画面に差し替えます。
-ログイン画面はSpringMVCで適当に作る前提です。
以下のような権限を設定してます。
-ログイン画面(/login)はログインしなくても表示
-静的資材(/static)はログインしなくても表示
-ログイン画面以外(/**)はログインしないと表示できない
-applicationScurity.xml
<http auto-config="true">
<intercept-url pattern="/login*" access="ROLE_ANONYMOUS,ROLE_USER" />
<intercept-url pattern="/static/**/*" access="ROLE_ANONYMOUS,ROLE_USER" />
<intercept-url pattern="/**" access="ROLE_USER"/>
<form-login login-page="/login"
default-target-url="/"
authentication-failure-url="/login?error=true" />
<logout logout-success-url="/login" />
</http>
ちなみに、ログインしていない人を表すROLEはSpringSecurityにデフォルトで定義されていて、「ROLE_ANONYMOUS」です。
設定のポイント
-/login、/static/**/*はaccessにROLE_ANONYMOUS,ROLE_USERの2つのROLEを設定
-/**はROLE_USERのみを設定
あとは、適当にログイン画面作ってコントローラ作れば表示されますw(jspであればそこら辺に落ちてる奴を使えばOK)
ちなみに、小生はbootstrapのsignin画面をベースに作りました。
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN"
"http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xml:lang="ja" lang="ja" xmlns="http://www.w3.org/1999/xhtml">
<head>
<title>Web application with SpringMVC and mixer2 and Bootstrap</title>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
<meta name="viewport" content="width=device-width, initial-scale=1.0" />
<link href="../static/bootstrap/css/bootstrap.css" rel="stylesheet" />
<link href="../static/css/signin.css" rel="stylesheet" />
<!-- Just for debugging purposes. Don't actually copy this line! -->
<!--[if lt IE 9]><script src="../../docs-assets/js/ie8-responsive-file-warning.js"></script><![endif]-->
<!-- HTML5 shim and Respond.js IE8 support of HTML5 elements and media queries -->
<!--[if lt IE 9]>
<script src="https://oss.maxcdn.com/libs/html5shiv/3.7.0/html5shiv.js"></script>
<script src="https://oss.maxcdn.com/libs/respond.js/1.3.0/respond.min.js"></script>
<![endif]-->
</head>
<body>
<div class="container">
<form class="form-signin" role="form" name="f" action="j_spring_security_check" method="post">
<h2 class="form-signin-heading">Please sign in</h2>
<input type="text" class="form-control" placeholder="Email address" required="true" autofocus="true" name="j_username" />
<input type="password" class="form-control" placeholder="Password" required="true" name="j_password" />
<label class="checkbox">
<input type="checkbox" value="remember-me" /> Remember me
</label>
<button class="btn btn-lg btn-primary btn-block" type="submit" name="login">Sign in</button>
</form>
</div> <!-- /container -->
<!-- Bootstrap core JavaScript
================================================== -->
<!-- Placed at the end of the document so the pages load faster -->
<script src="../static/js/jquery-1.10.2.min.js"></script>
<script src="../static/bootstrap/js/bootstrap.min.js"></script>
</body>
</html>