LoginSignup
90
88

More than 5 years have passed since last update.

Spring Boot で Spring Security

Last updated at Posted at 2014-06-22

軽くやってみたら、ちと、Getting Started に不備があったのでメモ

STSのインストール

3.5.1をインストール
https://spring.io/tools/sts
(gradle使いたければ、dashboadのIDE EXTENTIONSから Gradle Pluginもインストール)

Getting Started プロジェクトの作成

1.new ➡Import Spring Getting Started Contents
2.securing Webを選択。(しばらく待つと、ダウンロードして、finishが押せる。)
3.finish
スクリーンショット 2014-06-22 14.54.24.png

起動してみる。

1.gs-securing-web-completeを選択して、Run As➡Spring Boot App
スクリーンショット 2014-06-22 14.58.53.png
2.ブラウザでlocalhost:8080/loginにアクセスすると、
スクリーンショット 2014-06-22 14.59.39.png
3.ユーザー名は「user」,パスワードは「password」でログイン可能。
スクリーンショット 2014-06-22 15.02.15.png

管理者ページの確認

package hello;


@Configuration
@EnableWebMvcSecurity
public class WebSecurityConfig extends WebSecurityConfigurerAdapter {
    @Override
    protected void configure(HttpSecurity http) throws Exception {
        http
            .authorizeRequests()
                .antMatchers("/", "/home").permitAll()
         //管理者ページの追加
                .antMatchers("/admin").hasRole("ADMIN")
                .anyRequest().authenticated();
        http
            .formLogin()
                .loginPage("/login")
                .permitAll()
                .and()
            .logout()
                .permitAll();
    }

    @Override
    protected void configure(AuthenticationManagerBuilder auth) throws Exception {
        auth
            .inMemoryAuthentication()
                .withUser("user").password("password").roles("USER");
        //管理者ユーザーの登録
        auth
           .inMemoryAuthentication()
                .withUser("admin").password("password").roles("ADMIN");

    }
}
MvcConfig

@Configuration
public class MvcConfig extends WebMvcConfigurerAdapter {

    @Override
    public void addViewControllers(ViewControllerRegistry registry) {
        registry.addViewController("/home").setViewName("home");
        registry.addViewController("/").setViewName("home");
        registry.addViewController("/hello").setViewName("hello");
        registry.addViewController("/login").setViewName("login");
        //管理者ページの追加
        registry.addViewController("/admin").setViewName("admin");
    }

}

適当にテンプレートページも追加(java/main/resources/templates).

admin.html

<!DOCTYPE html>
<html xmlns="http://www.w3.org/1999/xhtml" xmlns:th="http://www.thymeleaf.org"
      xmlns:sec="http://www.thymeleaf.org/thymeleaf-extras-springsecurity4">
    <head>
        <title>Admin Page</title>
    </head>
    <body>
        <h1 th:inline="text">Hello Administrator[[${#httpServletRequest.remoteUser}]]!</h1>
        <form th:action="@{/logout}" method="post">
            <input type="submit" value="Sign Out"/>
        </form>
    </body>
</html>

アクセスしてみる。

「user」でログオンし、localhost:8080/adminに入るとエラー。

スクリーンショット 2014-06-22 15.29.04.png

「admin」でログオンし、localhost:8080/adminに入ると正常に表示される。

スクリーンショット 2014-06-22 15.30.16.png

タグによる表示の制御

thymeleafにはSpring Security用のdialectがある。
http://www.thymeleaf.org/springsecurity.html

hello.html

<!DOCTYPE html>
<html xmlns="http://www.w3.org/1999/xhtml" xmlns:th="http://www.thymeleaf.org"
      xmlns:sec="http://www.thymeleaf.org/thymeleaf-extras-springsecurity4">
    <head>
        <title>Hello World!</title>
    </head>
    <body>

        <div sec:authorize="hasRole('ROLE_ADMIN')">This is Admin</div>
        <div sec:authorize="hasRole('ROLE_USER')">This is User</div>

        <h1 th:inline="text">Hello [[${#httpServletRequest.remoteUser}]]!</h1>
        <form th:action="@{/logout}" method="post">
            <input type="submit" value="Sign Out"/>
        </form>
    </body>
</html>

これでいいはずだが、なぜか、sec:がhtmlでもそのまま表示されてしまい、タグの表示制御ができていない。

build.gradleに下記を追加する。
参考:http://stackoverflow.com/questions/22606311/filter-html-content-with-spring-and-thymeleaf

build.gradle
dependencies {
    compile("org.springframework.boot:spring-boot-starter-thymeleaf")
    compile("org.springframework.boot:spring-boot-starter-security")
    //追加 
    compile ('org.thymeleaf.extras:thymeleaf-extras-springsecurity3:2.1.1.RELEASE')
//これは不備で、本来は下記のようになるはず
//compile ('org.thymeleaf.extras:thymeleaf-extras-springsecurity4:バージョン')
    testCompile("junit:junit")
}

これでタグの表示制御もできる。

追記。コメントで指摘の通り、templateのns宣言とdependenciesの宣言があっていない。org.thymeleaf.extrasはSpring3用と4用で分かれるので、本来は間違い。修正してからの、動作確認できてないです。すみません。

90
88
2

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
90
88