かんがるーさんの日記

最近自分が興味をもったものを調べた時の手順等を書いています。今は Spring Boot をいじっています。

Spring Boot 1.2.x の Web アプリを 1.3.x へバージョンアップする ( その5 )( 1.2 → 1.3 で実装方法が変更された箇所を修正する )

概要

Spring Boot 1.2.x の Web アプリを 1.3.x へバージョンアップする ( その4 )( build.gradle 修正後のテストが失敗する原因を解消する ) の続きです。

  • 今回の手順で確認できるのは以下の内容です。
    • 1.2 → 1.3 へのバージョンアップで実装方法が変更された箇所の修正

参照したサイト・書籍

目次

  1. logback.xml --> logback-spring.xml へリネームし、一部の設定を変更する
  2. Spring Security 4 から "ROLE_" が不要になったらしいのですが。。。
  3. 次回は。。。

手順

logback.xml --> logback-spring.xml へリネームし、一部の設定を変更する

以下のドキュメントの記述から、

以下の点を変更します。

  • src/main/resources の下の logback.xmllogback-spring.xml へリネームします。
  • logback-spring.xml の中で <property name="LOG_FILE" ... /> の value 属性にログファイルのパスを直接記述していますが、value 属性には ${LOG_FILE} を記述し、application-product.properties の logging.file にログファイルのパスを記述するようにします。

変更後の logback-spring.xml は以下のようになります。

<?xml version="1.0" encoding="UTF-8"?>
<configuration>
    <include resource="org/springframework/boot/logging/logback/defaults.xml"/>

    <appender name="CONSOLE" class="ch.qos.logback.core.ConsoleAppender">
        <encoder>
            <pattern>${CONSOLE_LOG_PATTERN}</pattern>
            <charset>UTF-8</charset>
        </encoder>
    </appender>

    <if condition='"${spring.profiles.active}" == "product"'>
        <then>
            <property name="LOG_FILE" value="${LOG_FILE}"/>
            <appender name="FILE" class="ch.qos.logback.core.rolling.RollingFileAppender">
                <encoder>
                    <pattern>${FILE_LOG_PATTERN}</pattern>
                </encoder>
                <file>${LOG_FILE}</file>
                <rollingPolicy class="ch.qos.logback.core.rolling.TimeBasedRollingPolicy">
                    <fileNamePattern>${LOG_FILE}.%d{yyyy-MM-dd}</fileNamePattern>
                    <maxHistory>30</maxHistory>
                </rollingPolicy>
            </appender>
        </then>
    </if>

    <if condition='"${spring.profiles.active}" == "develop"'>
        <then>
            <include resource="logback-develop.xml"/>
        </then>
    </if>
    <if condition='"${spring.profiles.active}" == "unittest"'>
        <then>
            <include resource="logback-unittest.xml"/>
        </then>
    </if>
    <if condition='"${spring.profiles.active}" == "product"'>
        <then>
            <include resource="logback-product.xml"/>
        </then>
    </if>
</configuration>
  • <property name="LOG_FILE" value="C:/webapps/ksbysample-webapp-lending/logs/ksbysample-webapp-lending.log"/><property name="LOG_FILE" value="${LOG_FILE}"/> に変更します。

変更後の application-product.properties は以下のようになります。

server.tomcat.basedir=C:/webapps/ksbysample-webapp-lending
logging.file=${server.tomcat.basedir}/logs/ksbysample-webapp-lending.log

spring.datasource.url=jdbc:postgresql://localhost/ksbylending
spring.datasource.username=ksbylending_user
spring.datasource.password=xxxxxxxx
spring.datasource.driverClassName=org.postgresql.Driver

spring.mail.host=localhost
spring.mail.port=25

spring.rabbitmq.host=localhost
spring.rabbitmq.port=5672

spring.redis.sentinel.master=mymaster
spring.redis.sentinel.nodes=localhost:6381,localhost:6382,localhost:6383

spring.thymeleaf.cache=true
  • logging.file=${server.tomcat.basedir}/logs/ksbysample-webapp-lending.log を追加します。

Spring Security 4 から "ROLE_" が不要になったらしいのですが。。。

8. Automatic ROLE_ prefixing

を見ると ROLE には自動的に "ROLE_" が付くようになったらしいのですが、試してみると動作する場合と動作しない場合があるようです。

まず動作する場合です。

src/main/java/ksbysample/webapp/lending/web/admin/library/AdminLibraryController.java を以下のように変更します。

@Controller
@PreAuthorize("hasRole('ADMIN')")
@RequestMapping("/admin/library")
public class AdminLibraryController {
  • @PreAuthorize("hasRole('ROLE_ADMIN')")@PreAuthorize("hasRole('ADMIN')") に変更します。

Tomcat を起動して tanaka.taro@sample.com ( ROLE_ADMIN あり ) でログインすると /admin/library に問題なくアクセスできました。

f:id:ksby:20160524013226p:plain

また src/main/resources/templates/common/mainparts.html を以下のように変更します。

                <div class="collapse navbar-collapse pull-left" id="navbar-collapse">
                    <ul class="nav navbar-nav">
                        <li class="dropdown">
                            <a href="#" class="dropdown-toggle" data-toggle="dropdown">メニュー <span class="caret"></span></a>
                            <ul class="dropdown-menu" role="menu">
                                <li><a href="/booklist">貸出希望書籍登録</a></li>
                                <li class="divider" sec:authorize="hasRole('ROLE_ADMIN')"></li>
                                <li sec:authorize="hasRole('ADMIN')"><a href="/admin/library">検索対象図書館登録</a></li>
                            </ul>
                        </li>
                    </ul>
                </div>
  • <li sec:authorize="hasRole('ROLE_ADMIN')"><a href="/admin/library">検索対象図書館登録</a></li><li sec:authorize="hasRole('ADMIN')"><a href="/admin/library">検索対象図書館登録</a></li> に変更します。

Tomcat を再起動して tanaka.taro@sample.com ( ROLE_ADMIN あり ) でログインすると「検索対象図書館登録」メニューが表示されました。

f:id:ksby:20160524014024p:plain

次は動作しない場合です。

src/main/java/ksbysample/webapp/lending/helper/url/UrlAfterLoginHelper.java を以下のように変更します。

    public static String getUrlAfterLogin(Authentication authentication, HttpServletRequest request) {
        String targetUrl = WebSecurityConfig.DEFAULT_SUCCESS_URL;

        // 特定の権限を持っている場合には対応するURLへリダイレクトする
        GrantedAuthority roleAdmin = new SimpleGrantedAuthority("ADMIN");
        if (authentication.getAuthorities().contains(roleAdmin)) {
            // 管理権限 ( ROLE_ADMIN ) を持っている場合には検索対象図書館登録画面へ遷移させる
            targetUrl = Constant.URL_AFTER_LOGIN_FOR_ROLE_ADMIN;
        }

        // LastLendingAppId Cookie に貸出申請ID をセットされている場合には貸出申請画面へリダイレクトさせる
        String cookieLastLendingAppId = CookieUtils.getCookieValue(CookieLastLendingAppId.COOKIE_NAME, request);
        if (StringUtils.isNotBlank(cookieLastLendingAppId)) {
            targetUrl = String.format("%s?lendingAppId=%s", Constant.URL_LENDINGAPP, cookieLastLendingAppId);
        }

        return targetUrl;
    }
  • GrantedAuthority roleAdmin = new SimpleGrantedAuthority("ROLE_ADMIN");GrantedAuthority roleAdmin = new SimpleGrantedAuthority("ADMIN"); に変更します。

Tomcat を再起動して tanaka.taro@sample.com ( ROLE_ADMIN あり ) でログインすると、検索対象図書館登録画面ではなく貸出希望書籍 CSV ファイルアップロード画面に遷移してしまいました。

f:id:ksby:20160524015417p:plain

また src/test/java/ksbysample/webapp/lending/helper/url/UrlAfterLoginHelperTest.java を以下のように変更します。

    @Test
    public void testGetUrlAfterLogin_管理権限がある場合() throws Exception {
        Authentication authentication = new TestingAuthenticationToken("test", "test", "ADMIN", "USER");
        String url = UrlAfterLoginHelper.getUrlAfterLogin(authentication);
        assertThat(url).isEqualTo(Constant.URL_AFTER_LOGIN_FOR_ROLE_ADMIN);
    }
  • Authentication authentication = new TestingAuthenticationToken("test", "test", "ROLE_ADMIN", "ROLE_USER");Authentication authentication = new TestingAuthenticationToken("test", "test", "ADMIN", "USER"); に変更します。

このテストを実行してみると、以下のように失敗しました。

f:id:ksby:20160524020119p:plain

上記の動作する場合と動作しない場合ですが、どれも "ROLE_" が付いた状態で動作しました。

常に "ROLE_" がなくてもよいのであれば削除しようと思いましたが、そうではないようなのでこのままにしたいと思います。

次回は。。。

JRebel をインストールしている場合 devtools は似たような機能を実現しようとしているので問題が出るとつい思っていたのですが、以下の Issue を見つけました。

どうも問題なく動作するよう考慮されているみたいです。devtools を入れて試してみたいと思います。

ソースコード

履歴

2016/05/24
初版発行。