mike-neckのブログ

Java or Groovy or Swift or Golang

Spring WebFlux Security のカスタム認証

Spring WebFlux Security でカスタム認証を実装します。ベースとなるユーザー認証部分は以前に実装したとおりです。

mike-neck.hatenadiary.com

今回は権限まわりの実装します。〜〜のパスには〜〜の権限が必要みたいなやつです。


特定のリソースへの特定のメソッドでのアクセス可否を設定するには SecurityWebFIlterChain を Bean 登録します。

  @Bean
  SecurityWebFilterChain springSecurityFilterChain(final ServerHttpSecurity http) {
    return http.httpBasic() // (1)
        .and()
        .authorizeExchange() // (2)
        .pathMatchers(HttpMethod.GET, "/talks/**") // (3)
        .hasAuthority("USER") // (4)
        .pathMatchers(HttpMethod.GET, "/test/**")
        .hasAuthority("ADMIN")
        .and()
        .build();
  }
  1. 今回はベーシック認証なので httpBasic を呼び出します
  2. アクセス可能なパス、メソッド、Authority(Role) の組み合わせ設定をします
  3. GET で /talk 以下のアクセスを許可します
  4. 上記のパスへのGETアクセスを authority=USER をもつユーザーに限定します

例えば USER 権限のみをもつユーザー foo を用意して、 /talks にアクセスしてみます

$ curl -v http://localhost:8080/talks --basic -u "foo:foo-pass"
> GET /talks HTTP/1.1
> Host: localhost:8080
> Authorization: Basic Zm9vOmZvby1wYXNz
> User-Agent: curl/7.54.0
> Accept: */*
> 
< HTTP/1.1 200 OK
< transfer-encoding: chunked
< Content-Type: application/json
< Cache-Control: no-cache, no-store, max-age=0, must-revalidate
< Pragma: no-cache
< Expires: 0
< X-Content-Type-Options: nosniff
< X-Frame-Options: DENY
< X-XSS-Protection: 1 ; mode=block
< 
[{"id":23014831827719168,"name":"beta users","description":"beta users","created":[2018,3,4,10,30,18,464000000]}]

talks にこのユーザーはアクセスできるので、jsonが返ってきます。今後は ADMIN 権限が必要な /test にアクセスしてみます。

$ curl -v http://localhost:8080/test --basic -u "foo:foo-pass"
> GET /test HTTP/1.1
> Host: localhost:8080
> Authorization: Basic Zm9vOmZvby1wYXNz
> User-Agent: curl/7.54.0
> Accept: */*
> 
< HTTP/1.1 403 Forbidden
< transfer-encoding: chunked
< Content-Type: text/plain
< Cache-Control: no-cache, no-store, max-age=0, must-revalidate
< Pragma: no-cache
< Expires: 0
< X-Content-Type-Options: nosniff
< X-Frame-Options: DENY
< X-XSS-Protection: 1 ; mode=block
< 
Access Denied

今度は403が返ってきました。