SlideShare a Scribd company logo
1 of 14
Copyright ©2016 NS Solutions Corporation. All Rights Reserved.
Spring Security 4.1 の新機能
2016/09/03
新日鉄住金ソリューションズ株式会社
井岡 正和
日本Springユーザ会
SpringOne Platform 2016 報告会
Copyright ©2016 NS Solutions Corporation. All Rights Reserved.
自己紹介
 井岡 正和 (いおか まさかず)
 Spring ベースの社内標準FW開発・保守担当
 SpringOne の参加は3回目
 プライベートでは、iOS・Android のアプリを開発
http://www.slideshare.net/KoUmetani/spring2015-56309694
去年もSpring Security 関連について
紹介させていただきました。
2
Copyright ©2016 NS Solutions Corporation. All Rights Reserved.
今日紹介する内容
 Spring Security 4.1 の新機能について
 CookieCsrfTokenRepository
 Content Security Policy
 @AuthenticationPrincipal
 Path Variables in Web Security Expressions
 Referring to Beans in Web Security Expressions
 MvcRequestMatcher
3
参考セッション: To Spring Security 4.1 and Beyond
セッションで使用されたコード: https://github.com/rwinch/spring-security-4.1-and-beyond
Copyright ©2016 NS Solutions Corporation. All Rights Reserved.
(おさらい) Spring Security の基本的な使い方
@EnableWebSecurity
public class SecurityConfig extends WebSecurityConfigurerAdapter {
// @formatter:off
@Override
protected void configure(HttpSecurity http) throws Exception {
http
.authorizeRequests()
.antMatchers("/", "/assets/**", "/webjars/**").permitAll()
.anyRequest().authenticated()
.and()
.httpBasic();
}
// @formatter:on
WebSecurityConfigurerAdapter を継承
@EnableWebSecurity を追加
configure をオーバーライド
リソースへのアクセス許可
Basic認証を有効
その他のアクセスに認証
自分で指定したインデントがIDEのフォーマッタで崩れてしまうが、
「// @formatter:off」と「// @formatter:on」で囲うことで、
その中のコードはフォーマッターがかからなくなる。
4
Copyright ©2016 NS Solutions Corporation. All Rights Reserved.
Spring Security 4.1 の
新機能について
5
Copyright ©2016 NS Solutions Corporation. All Rights Reserved.
CookieCsrfTokenRepository
6
 CSRF トークンを Cookie に格納できるようになった
 デフォルトでは「XSRF-TOKEN」に格納される
AngularJS では、Cookie に XSRF-TOKEN があると、
自動的に X-XSRF-TOKEN ヘッダを付けてくれるらしい
@Override
protected void configure(HttpSecurity http) throws Exception {
http
.authorizeRequests()
.antMatchers("/", "/assets/**", "/webjars/**").permitAll()
.anyRequest().authenticated()
.and()
.httpBasic()
.and()
.csrf()
.csrfTokenRepository(CookieCsrfTokenRepository.withHttpOnlyFalse());
}
CSRF の CsrfTokenRepository に、
CookieCsrfTokenRepository を指定
JavaScript 等から読み込む場合は、
withHttpOnlyFalse() によって
CsrfTokenRepository を取得する。
Copyright ©2016 NS Solutions Corporation. All Rights Reserved.
Content Security Policy
7
 Content Security Policy の設定ができるようになった
 XSS やデータインジェクション等の攻撃を対策できる
@Override
protected void configure(HttpSecurity http) throws Exception {
http
.authorizeRequests()
.antMatchers("/", "/assets/**", "/webjars/**").permitAll()
.anyRequest().authenticated()
.and()
.httpBasic()
.and()
.headers()
.contentSecurityPolicy("default-src 'self' " +
"https://ajax.googleapis.com; " +
"style-src 'self' 'unsafe-inline'");
}
ヘッダに Content Security Policy を設定
contentSecurityPolicy() の後ろに「.reportOnly()」
を追加すると、ポリシー違反の通知のみになる。 ここでの設定では、
自身のドメインと「https://ajax.googleapis.com」を許可
スタイルについては自身のドメインとインラインの<style>要素のみ許可
Copyright ©2016 NS Solutions Corporation. All Rights Reserved.
@AuthenticationPrincipal (1/2)
8
 認証ユーザを Controller の引数で取得できるようになった
@RestController
public class SecurityController {
@RequestMapping(value = "/principal")
public ResponseEntity<User> currentPrincipal(@AuthenticationPrincipal User user) {
return new ResponseEntity<User>(user, HttpStatus.OK);
}
これだけ!
 以前は、下記のようにして取得していた
@RequestMapping(value = "/principal")
public ResponseEntity<User> currentPrincipal() {
User user =
(User) SecurityContextHolder.getContext().getAuthentication().getPrincipal();
@RequestMapping(value = "/principal")
public ResponseEntity<User> currentPrincipal(Authentication authentication) {
User user = (User) authentication.getPrincipal();
大変!
Copyright ©2016 NS Solutions Corporation. All Rights Reserved.
@AuthenticationPrincipal (2/2)
9
 ただし、@AuthenticationPrincipal は直接使用せず、
@CurrentUser のように意味が伝わるアノテーションを
作成して使用したほうが保守性が上がる
@RestController
public class SecurityController {
@RequestMapping(value = "/principal")
public ResponseEntity<User> currentPrincipal(@CurrentUser User user) {
return new ResponseEntity<User>(user, HttpStatus.OK);
}
@Target(ElementType.PARAMETER)
@Retention(RetentionPolicy.RUNTIME)
@Documented
@AuthenticationPrincipal
public @interface CurrentUser {
}
Copyright ©2016 NS Solutions Corporation. All Rights Reserved.
Path Variables in Web Security Expressions
10
 Web Security Expressions で Path Variable を
使用できるようになった
@Override
protected void configure(HttpSecurity http) throws Exception {
http
.authorizeRequests()
.antMatchers("/", "/assets/**", "/webjars/**").permitAll()
.antMatchers("/users/{userId}").access("#userId == principal.id.toString()")
.anyRequest().authenticated()
.and()
.httpBasic();
}
@RequestMapping と同じで
中括弧で変数を指定
「#変数名」で使用できる
Copyright ©2016 NS Solutions Corporation. All Rights Reserved.
Referring to Beans in Web Security Expressions
11
 Web Security Expressions で Bean を
使用できるようになった
@Override
protected void configure(HttpSecurity http) throws Exception {
http
.authorizeRequests()
.antMatchers("/", "/assets/**", "/webjars/**").permitAll()
.antMatchers("/users/{userId}").access("@authz.check(#userId,principal)")
.anyRequest().authenticated()
.and()
.httpBasic();
}
「@Bean名」で使用できる
@Component
public class Authz {
public boolean check(Long userId, User user) {
return userId.equals(user.getId());
}
}
「authz」というBean名で登録される
@PreAuthorize や@PostAuthorize 等でも Bean を使用できる
Copyright ©2016 NS Solutions Corporation. All Rights Reserved.
MvcRequestMatcher
12
 「/admin」のアクセス制限をした場合に、
「/admin/」からもアクセス制限できるようになった
@Override
protected void configure(HttpSecurity http) throws Exception {
http
.authorizeRequests()
.antMatchers("/", "/assets/**", "/webjars/**").permitAll()
.mvcMatchers("/admin").denyAll()
.anyRequest().authenticated()
.and()
.httpBasic();
}
antMatchers ではなく、
mvcMatchers を使用する
@Override
protected void configure(HttpSecurity http) throws Exception {
http
.authorizeRequests()
.antMatchers("/", "/assets/**", "/webjars/**").permitAll()
.antMatchers("/admin").denyAll()
.anyRequest().authenticated()
.and()
.httpBasic();
}
下記のように antMatchers("/admin").denyAll() とした場合は、
「/admin/」でアクセスできる
Copyright ©2016 NS Solutions Corporation. All Rights Reserved.
おわりに
13
 とても簡単にセキュリティ設定ができるので、
強固なアプリケーションを作ってください!
 他にもいろいろな機能が 4.1 で追加されています
 http://docs.spring.io/spring-
security/site/docs/current/reference/htmlsingle/#new
Copyright ©2016 NS Solutions Corporation. All Rights Reserved. 14
NS Solutions、NS(ロゴ)、NSSOLは、新日鉄住金ソリューションズ株式会社の登録商標です。
Javaは、米国ORACLE Corp.の登録商標です。
その他本文記載の会社名及び製品名は、それぞれ各社の商標又は登録商標です。

More Related Content

What's hot

Spring bootでweb セキュリティ(ログイン認証)編
Spring bootでweb セキュリティ(ログイン認証)編Spring bootでweb セキュリティ(ログイン認証)編
Spring bootでweb セキュリティ(ログイン認証)編なべ
 
SpringOne 2GX 2014 参加報告 & Spring 4.1について #jsug
SpringOne 2GX 2014 参加報告 & Spring 4.1について #jsugSpringOne 2GX 2014 参加報告 & Spring 4.1について #jsug
SpringOne 2GX 2014 参加報告 & Spring 4.1について #jsugToshiaki Maki
 
Yahoo! JAPANのコンテンツプラットフォームを支えるSpring Cloud Streamによるマイクロサービスアーキテクチャ #jsug #sf_52
Yahoo! JAPANのコンテンツプラットフォームを支えるSpring Cloud Streamによるマイクロサービスアーキテクチャ #jsug #sf_52Yahoo! JAPANのコンテンツプラットフォームを支えるSpring Cloud Streamによるマイクロサービスアーキテクチャ #jsug #sf_52
Yahoo! JAPANのコンテンツプラットフォームを支えるSpring Cloud Streamによるマイクロサービスアーキテクチャ #jsug #sf_52Yahoo!デベロッパーネットワーク
 
Spring data-rest-and-spring-cloud-contract
Spring data-rest-and-spring-cloud-contractSpring data-rest-and-spring-cloud-contract
Spring data-rest-and-spring-cloud-contractTakeshi Ogawa
 
Go conference 2015_winter
Go conference 2015_winterGo conference 2015_winter
Go conference 2015_wintermatsuo kenji
 
未来のwebに欠かせないREST APIをApache Solr + Drupal8で実装しよう@PHPカンファレンス2016 東京
未来のwebに欠かせないREST APIをApache Solr + Drupal8で実装しよう@PHPカンファレンス2016 東京未来のwebに欠かせないREST APIをApache Solr + Drupal8で実装しよう@PHPカンファレンス2016 東京
未来のwebに欠かせないREST APIをApache Solr + Drupal8で実装しよう@PHPカンファレンス2016 東京Masayuki Abe
 
[JavaDo] JAX-RS ハンズオン 第2部
[JavaDo] JAX-RS ハンズオン 第2部[JavaDo] JAX-RS ハンズオン 第2部
[JavaDo] JAX-RS ハンズオン 第2部haruki ueno
 
はじめてのSpring Boot
はじめてのSpring BootはじめてのSpring Boot
はじめてのSpring Bootなべ
 
Spring I/O 2017 報告 ThymeleafのWebFlux対応
Spring I/O 2017 報告 ThymeleafのWebFlux対応Spring I/O 2017 報告 ThymeleafのWebFlux対応
Spring I/O 2017 報告 ThymeleafのWebFlux対応Takuya Iwatsuka
 
ウェブ・セキュリティ基礎試験(徳丸基礎試験)の模擬試験問題
ウェブ・セキュリティ基礎試験(徳丸基礎試験)の模擬試験問題ウェブ・セキュリティ基礎試験(徳丸基礎試験)の模擬試験問題
ウェブ・セキュリティ基礎試験(徳丸基礎試験)の模擬試験問題Hiroshi Tokumaru
 
今からでも間に合う!インフラ自動化超入門 @渋谷
今からでも間に合う!インフラ自動化超入門 @渋谷今からでも間に合う!インフラ自動化超入門 @渋谷
今からでも間に合う!インフラ自動化超入門 @渋谷Daigou Harada
 
Spring Bootで変わる Javaアプリ開発! #jsug
Spring Bootで変わる Javaアプリ開発! #jsugSpring Bootで変わる Javaアプリ開発! #jsug
Spring Bootで変わる Javaアプリ開発! #jsugToshiaki Maki
 
Laravelの認証について
Laravelの認証についてLaravelの認証について
Laravelの認証についてTakeo Noda
 
Spring Fest 2018 Spring Bootで作るRESTful Web Service
Spring Fest 2018 Spring Bootで作るRESTful Web ServiceSpring Fest 2018 Spring Bootで作るRESTful Web Service
Spring Fest 2018 Spring Bootで作るRESTful Web ServiceWataruOhno
 
Excel on OneDrive is not a file
Excel on OneDrive is not a fileExcel on OneDrive is not a file
Excel on OneDrive is not a fileTakao Tetsuro
 
WildFly Swarm - Rightsize Your Java EE Apps
WildFly Swarm - Rightsize Your Java EE AppsWildFly Swarm - Rightsize Your Java EE Apps
WildFly Swarm - Rightsize Your Java EE AppsYoshimasa Tanabe
 

What's hot (20)

Spring bootでweb セキュリティ(ログイン認証)編
Spring bootでweb セキュリティ(ログイン認証)編Spring bootでweb セキュリティ(ログイン認証)編
Spring bootでweb セキュリティ(ログイン認証)編
 
SpringOne 2GX 2014 参加報告 & Spring 4.1について #jsug
SpringOne 2GX 2014 参加報告 & Spring 4.1について #jsugSpringOne 2GX 2014 参加報告 & Spring 4.1について #jsug
SpringOne 2GX 2014 参加報告 & Spring 4.1について #jsug
 
Yahoo! JAPANのコンテンツプラットフォームを支えるSpring Cloud Streamによるマイクロサービスアーキテクチャ #jsug #sf_52
Yahoo! JAPANのコンテンツプラットフォームを支えるSpring Cloud Streamによるマイクロサービスアーキテクチャ #jsug #sf_52Yahoo! JAPANのコンテンツプラットフォームを支えるSpring Cloud Streamによるマイクロサービスアーキテクチャ #jsug #sf_52
Yahoo! JAPANのコンテンツプラットフォームを支えるSpring Cloud Streamによるマイクロサービスアーキテクチャ #jsug #sf_52
 
Spring data-rest-and-spring-cloud-contract
Spring data-rest-and-spring-cloud-contractSpring data-rest-and-spring-cloud-contract
Spring data-rest-and-spring-cloud-contract
 
Go conference 2015_winter
Go conference 2015_winterGo conference 2015_winter
Go conference 2015_winter
 
未来のwebに欠かせないREST APIをApache Solr + Drupal8で実装しよう@PHPカンファレンス2016 東京
未来のwebに欠かせないREST APIをApache Solr + Drupal8で実装しよう@PHPカンファレンス2016 東京未来のwebに欠かせないREST APIをApache Solr + Drupal8で実装しよう@PHPカンファレンス2016 東京
未来のwebに欠かせないREST APIをApache Solr + Drupal8で実装しよう@PHPカンファレンス2016 東京
 
[JavaDo] JAX-RS ハンズオン 第2部
[JavaDo] JAX-RS ハンズオン 第2部[JavaDo] JAX-RS ハンズオン 第2部
[JavaDo] JAX-RS ハンズオン 第2部
 
はじめてのSpring Boot
はじめてのSpring BootはじめてのSpring Boot
はじめてのSpring Boot
 
Spring I/O 2017 報告 ThymeleafのWebFlux対応
Spring I/O 2017 報告 ThymeleafのWebFlux対応Spring I/O 2017 報告 ThymeleafのWebFlux対応
Spring I/O 2017 報告 ThymeleafのWebFlux対応
 
ウェブ・セキュリティ基礎試験(徳丸基礎試験)の模擬試験問題
ウェブ・セキュリティ基礎試験(徳丸基礎試験)の模擬試験問題ウェブ・セキュリティ基礎試験(徳丸基礎試験)の模擬試験問題
ウェブ・セキュリティ基礎試験(徳丸基礎試験)の模擬試験問題
 
今からでも間に合う!インフラ自動化超入門 @渋谷
今からでも間に合う!インフラ自動化超入門 @渋谷今からでも間に合う!インフラ自動化超入門 @渋谷
今からでも間に合う!インフラ自動化超入門 @渋谷
 
Spring AMQP × RabbitMQ
Spring AMQP × RabbitMQSpring AMQP × RabbitMQ
Spring AMQP × RabbitMQ
 
Spring Bootで変わる Javaアプリ開発! #jsug
Spring Bootで変わる Javaアプリ開発! #jsugSpring Bootで変わる Javaアプリ開発! #jsug
Spring Bootで変わる Javaアプリ開発! #jsug
 
イエラエセキュリティMeet up 20210820
イエラエセキュリティMeet up 20210820イエラエセキュリティMeet up 20210820
イエラエセキュリティMeet up 20210820
 
Laravelの認証について
Laravelの認証についてLaravelの認証について
Laravelの認証について
 
Spring Fest 2018 Spring Bootで作るRESTful Web Service
Spring Fest 2018 Spring Bootで作るRESTful Web ServiceSpring Fest 2018 Spring Bootで作るRESTful Web Service
Spring Fest 2018 Spring Bootで作るRESTful Web Service
 
Jsug 20160422 slides
Jsug 20160422 slidesJsug 20160422 slides
Jsug 20160422 slides
 
Excel on OneDrive is not a file
Excel on OneDrive is not a fileExcel on OneDrive is not a file
Excel on OneDrive is not a file
 
Vue入門
Vue入門Vue入門
Vue入門
 
WildFly Swarm - Rightsize Your Java EE Apps
WildFly Swarm - Rightsize Your Java EE AppsWildFly Swarm - Rightsize Your Java EE Apps
WildFly Swarm - Rightsize Your Java EE Apps
 

Similar to Spring Security 4.1 の新機能

ochacafe#6 人にもマシンにもやさしいAPIのエコシステム
ochacafe#6 人にもマシンにもやさしいAPIのエコシステムochacafe#6 人にもマシンにもやさしいAPIのエコシステム
ochacafe#6 人にもマシンにもやさしいAPIのエコシステムオラクルエンジニア通信
 
Webシステム脆弱性LT資料
Webシステム脆弱性LT資料Webシステム脆弱性LT資料
Webシステム脆弱性LT資料Tomohito Adachi
 
Spring I/O 2018 報告会 - Spring Cloud Gateway / Spring Cloud Pipelines
Spring I/O 2018 報告会 - Spring Cloud Gateway / Spring Cloud PipelinesSpring I/O 2018 報告会 - Spring Cloud Gateway / Spring Cloud Pipelines
Spring I/O 2018 報告会 - Spring Cloud Gateway / Spring Cloud PipelinesJunya Katada
 
Splunkを使ってKubernetesクラスターとコンテナのログ・メトリクスを可視化
Splunkを使ってKubernetesクラスターとコンテナのログ・メトリクスを可視化Splunkを使ってKubernetesクラスターとコンテナのログ・メトリクスを可視化
Splunkを使ってKubernetesクラスターとコンテナのログ・メトリクスを可視化Kunihiko Ikeyama
 
Contrail deploy by Juju/MAAS
Contrail deploy by Juju/MAASContrail deploy by Juju/MAAS
Contrail deploy by Juju/MAASIkuo Kumagai
 
CLOUDIAN at Support Engineer Night
CLOUDIAN at Support Engineer NightCLOUDIAN at Support Engineer Night
CLOUDIAN at Support Engineer NightCLOUDIAN KK
 
Quarkus による超音速な Spring アプリケーション開発
Quarkus による超音速な Spring アプリケーション開発Quarkus による超音速な Spring アプリケーション開発
Quarkus による超音速な Spring アプリケーション開発Chihiro Ito
 
安全なPHPアプリケーションの作り方2016
安全なPHPアプリケーションの作り方2016安全なPHPアプリケーションの作り方2016
安全なPHPアプリケーションの作り方2016Hiroshi Tokumaru
 
Google I/O 2016 報告会
Google I/O 2016 報告会Google I/O 2016 報告会
Google I/O 2016 報告会shingo suzuki
 
Interop2014 - OpenStackの概要と最新技術動向(Icehouse)
Interop2014 - OpenStackの概要と最新技術動向(Icehouse)Interop2014 - OpenStackの概要と最新技術動向(Icehouse)
Interop2014 - OpenStackの概要と最新技術動向(Icehouse)irix_jp
 
MySQLデータ暗号化と暗号鍵のローテーション
MySQLデータ暗号化と暗号鍵のローテーションMySQLデータ暗号化と暗号鍵のローテーション
MySQLデータ暗号化と暗号鍵のローテーションShinya Sugiyama
 
最近のKeycloakのご紹介 ~クライアントポリシーとFAPI~
最近のKeycloakのご紹介 ~クライアントポリシーとFAPI~最近のKeycloakのご紹介 ~クライアントポリシーとFAPI~
最近のKeycloakのご紹介 ~クライアントポリシーとFAPI~Hitachi, Ltd. OSS Solution Center.
 
Xamarin.formsで作成する翻訳機能付きtwitterクライアント
Xamarin.formsで作成する翻訳機能付きtwitterクライアント Xamarin.formsで作成する翻訳機能付きtwitterクライアント
Xamarin.formsで作成する翻訳機能付きtwitterクライアント Shinichi Hirauchi
 
Apache Spark 3.0新機能紹介 - 拡張機能やWebUI関連のアップデート(Spark Meetup Tokyo #3 Online)
Apache Spark 3.0新機能紹介 - 拡張機能やWebUI関連のアップデート(Spark Meetup Tokyo #3 Online)Apache Spark 3.0新機能紹介 - 拡張機能やWebUI関連のアップデート(Spark Meetup Tokyo #3 Online)
Apache Spark 3.0新機能紹介 - 拡張機能やWebUI関連のアップデート(Spark Meetup Tokyo #3 Online)NTT DATA Technology & Innovation
 
20161111 java one2016-feedback
20161111 java one2016-feedback20161111 java one2016-feedback
20161111 java one2016-feedbackTakashi Ito
 
XAML と C# を使った Windows ストアアプリ(LOB)構築のためのtips Prism 4.5 & Kona project 等のご紹介
XAML と C# を使った Windows ストアアプリ(LOB)構築のためのtips   Prism 4.5 & Kona project 等のご紹介XAML と C# を使った Windows ストアアプリ(LOB)構築のためのtips   Prism 4.5 & Kona project 等のご紹介
XAML と C# を使った Windows ストアアプリ(LOB)構築のためのtips Prism 4.5 & Kona project 等のご紹介Shotaro Suzuki
 
Spring BootでHello Worldのその先へ
Spring BootでHello Worldのその先へSpring BootでHello Worldのその先へ
Spring BootでHello Worldのその先へMasatoshi Fujino
 
安全なWebアプリケーションの作り方2018
安全なWebアプリケーションの作り方2018安全なWebアプリケーションの作り方2018
安全なWebアプリケーションの作り方2018Hiroshi Tokumaru
 

Similar to Spring Security 4.1 の新機能 (20)

ochacafe#6 人にもマシンにもやさしいAPIのエコシステム
ochacafe#6 人にもマシンにもやさしいAPIのエコシステムochacafe#6 人にもマシンにもやさしいAPIのエコシステム
ochacafe#6 人にもマシンにもやさしいAPIのエコシステム
 
Osaka-Meetup-Sep2016
Osaka-Meetup-Sep2016Osaka-Meetup-Sep2016
Osaka-Meetup-Sep2016
 
Webシステム脆弱性LT資料
Webシステム脆弱性LT資料Webシステム脆弱性LT資料
Webシステム脆弱性LT資料
 
Spring I/O 2018 報告会
Spring I/O 2018 報告会Spring I/O 2018 報告会
Spring I/O 2018 報告会
 
Spring I/O 2018 報告会 - Spring Cloud Gateway / Spring Cloud Pipelines
Spring I/O 2018 報告会 - Spring Cloud Gateway / Spring Cloud PipelinesSpring I/O 2018 報告会 - Spring Cloud Gateway / Spring Cloud Pipelines
Spring I/O 2018 報告会 - Spring Cloud Gateway / Spring Cloud Pipelines
 
Splunkを使ってKubernetesクラスターとコンテナのログ・メトリクスを可視化
Splunkを使ってKubernetesクラスターとコンテナのログ・メトリクスを可視化Splunkを使ってKubernetesクラスターとコンテナのログ・メトリクスを可視化
Splunkを使ってKubernetesクラスターとコンテナのログ・メトリクスを可視化
 
Contrail deploy by Juju/MAAS
Contrail deploy by Juju/MAASContrail deploy by Juju/MAAS
Contrail deploy by Juju/MAAS
 
CLOUDIAN at Support Engineer Night
CLOUDIAN at Support Engineer NightCLOUDIAN at Support Engineer Night
CLOUDIAN at Support Engineer Night
 
Quarkus による超音速な Spring アプリケーション開発
Quarkus による超音速な Spring アプリケーション開発Quarkus による超音速な Spring アプリケーション開発
Quarkus による超音速な Spring アプリケーション開発
 
安全なPHPアプリケーションの作り方2016
安全なPHPアプリケーションの作り方2016安全なPHPアプリケーションの作り方2016
安全なPHPアプリケーションの作り方2016
 
Google I/O 2016 報告会
Google I/O 2016 報告会Google I/O 2016 報告会
Google I/O 2016 報告会
 
Interop2014 - OpenStackの概要と最新技術動向(Icehouse)
Interop2014 - OpenStackの概要と最新技術動向(Icehouse)Interop2014 - OpenStackの概要と最新技術動向(Icehouse)
Interop2014 - OpenStackの概要と最新技術動向(Icehouse)
 
MySQLデータ暗号化と暗号鍵のローテーション
MySQLデータ暗号化と暗号鍵のローテーションMySQLデータ暗号化と暗号鍵のローテーション
MySQLデータ暗号化と暗号鍵のローテーション
 
最近のKeycloakのご紹介 ~クライアントポリシーとFAPI~
最近のKeycloakのご紹介 ~クライアントポリシーとFAPI~最近のKeycloakのご紹介 ~クライアントポリシーとFAPI~
最近のKeycloakのご紹介 ~クライアントポリシーとFAPI~
 
Xamarin.formsで作成する翻訳機能付きtwitterクライアント
Xamarin.formsで作成する翻訳機能付きtwitterクライアント Xamarin.formsで作成する翻訳機能付きtwitterクライアント
Xamarin.formsで作成する翻訳機能付きtwitterクライアント
 
Apache Spark 3.0新機能紹介 - 拡張機能やWebUI関連のアップデート(Spark Meetup Tokyo #3 Online)
Apache Spark 3.0新機能紹介 - 拡張機能やWebUI関連のアップデート(Spark Meetup Tokyo #3 Online)Apache Spark 3.0新機能紹介 - 拡張機能やWebUI関連のアップデート(Spark Meetup Tokyo #3 Online)
Apache Spark 3.0新機能紹介 - 拡張機能やWebUI関連のアップデート(Spark Meetup Tokyo #3 Online)
 
20161111 java one2016-feedback
20161111 java one2016-feedback20161111 java one2016-feedback
20161111 java one2016-feedback
 
XAML と C# を使った Windows ストアアプリ(LOB)構築のためのtips Prism 4.5 & Kona project 等のご紹介
XAML と C# を使った Windows ストアアプリ(LOB)構築のためのtips   Prism 4.5 & Kona project 等のご紹介XAML と C# を使った Windows ストアアプリ(LOB)構築のためのtips   Prism 4.5 & Kona project 等のご紹介
XAML と C# を使った Windows ストアアプリ(LOB)構築のためのtips Prism 4.5 & Kona project 等のご紹介
 
Spring BootでHello Worldのその先へ
Spring BootでHello Worldのその先へSpring BootでHello Worldのその先へ
Spring BootでHello Worldのその先へ
 
安全なWebアプリケーションの作り方2018
安全なWebアプリケーションの作り方2018安全なWebアプリケーションの作り方2018
安全なWebアプリケーションの作り方2018
 

Spring Security 4.1 の新機能

  • 1. Copyright ©2016 NS Solutions Corporation. All Rights Reserved. Spring Security 4.1 の新機能 2016/09/03 新日鉄住金ソリューションズ株式会社 井岡 正和 日本Springユーザ会 SpringOne Platform 2016 報告会
  • 2. Copyright ©2016 NS Solutions Corporation. All Rights Reserved. 自己紹介  井岡 正和 (いおか まさかず)  Spring ベースの社内標準FW開発・保守担当  SpringOne の参加は3回目  プライベートでは、iOS・Android のアプリを開発 http://www.slideshare.net/KoUmetani/spring2015-56309694 去年もSpring Security 関連について 紹介させていただきました。 2
  • 3. Copyright ©2016 NS Solutions Corporation. All Rights Reserved. 今日紹介する内容  Spring Security 4.1 の新機能について  CookieCsrfTokenRepository  Content Security Policy  @AuthenticationPrincipal  Path Variables in Web Security Expressions  Referring to Beans in Web Security Expressions  MvcRequestMatcher 3 参考セッション: To Spring Security 4.1 and Beyond セッションで使用されたコード: https://github.com/rwinch/spring-security-4.1-and-beyond
  • 4. Copyright ©2016 NS Solutions Corporation. All Rights Reserved. (おさらい) Spring Security の基本的な使い方 @EnableWebSecurity public class SecurityConfig extends WebSecurityConfigurerAdapter { // @formatter:off @Override protected void configure(HttpSecurity http) throws Exception { http .authorizeRequests() .antMatchers("/", "/assets/**", "/webjars/**").permitAll() .anyRequest().authenticated() .and() .httpBasic(); } // @formatter:on WebSecurityConfigurerAdapter を継承 @EnableWebSecurity を追加 configure をオーバーライド リソースへのアクセス許可 Basic認証を有効 その他のアクセスに認証 自分で指定したインデントがIDEのフォーマッタで崩れてしまうが、 「// @formatter:off」と「// @formatter:on」で囲うことで、 その中のコードはフォーマッターがかからなくなる。 4
  • 5. Copyright ©2016 NS Solutions Corporation. All Rights Reserved. Spring Security 4.1 の 新機能について 5
  • 6. Copyright ©2016 NS Solutions Corporation. All Rights Reserved. CookieCsrfTokenRepository 6  CSRF トークンを Cookie に格納できるようになった  デフォルトでは「XSRF-TOKEN」に格納される AngularJS では、Cookie に XSRF-TOKEN があると、 自動的に X-XSRF-TOKEN ヘッダを付けてくれるらしい @Override protected void configure(HttpSecurity http) throws Exception { http .authorizeRequests() .antMatchers("/", "/assets/**", "/webjars/**").permitAll() .anyRequest().authenticated() .and() .httpBasic() .and() .csrf() .csrfTokenRepository(CookieCsrfTokenRepository.withHttpOnlyFalse()); } CSRF の CsrfTokenRepository に、 CookieCsrfTokenRepository を指定 JavaScript 等から読み込む場合は、 withHttpOnlyFalse() によって CsrfTokenRepository を取得する。
  • 7. Copyright ©2016 NS Solutions Corporation. All Rights Reserved. Content Security Policy 7  Content Security Policy の設定ができるようになった  XSS やデータインジェクション等の攻撃を対策できる @Override protected void configure(HttpSecurity http) throws Exception { http .authorizeRequests() .antMatchers("/", "/assets/**", "/webjars/**").permitAll() .anyRequest().authenticated() .and() .httpBasic() .and() .headers() .contentSecurityPolicy("default-src 'self' " + "https://ajax.googleapis.com; " + "style-src 'self' 'unsafe-inline'"); } ヘッダに Content Security Policy を設定 contentSecurityPolicy() の後ろに「.reportOnly()」 を追加すると、ポリシー違反の通知のみになる。 ここでの設定では、 自身のドメインと「https://ajax.googleapis.com」を許可 スタイルについては自身のドメインとインラインの<style>要素のみ許可
  • 8. Copyright ©2016 NS Solutions Corporation. All Rights Reserved. @AuthenticationPrincipal (1/2) 8  認証ユーザを Controller の引数で取得できるようになった @RestController public class SecurityController { @RequestMapping(value = "/principal") public ResponseEntity<User> currentPrincipal(@AuthenticationPrincipal User user) { return new ResponseEntity<User>(user, HttpStatus.OK); } これだけ!  以前は、下記のようにして取得していた @RequestMapping(value = "/principal") public ResponseEntity<User> currentPrincipal() { User user = (User) SecurityContextHolder.getContext().getAuthentication().getPrincipal(); @RequestMapping(value = "/principal") public ResponseEntity<User> currentPrincipal(Authentication authentication) { User user = (User) authentication.getPrincipal(); 大変!
  • 9. Copyright ©2016 NS Solutions Corporation. All Rights Reserved. @AuthenticationPrincipal (2/2) 9  ただし、@AuthenticationPrincipal は直接使用せず、 @CurrentUser のように意味が伝わるアノテーションを 作成して使用したほうが保守性が上がる @RestController public class SecurityController { @RequestMapping(value = "/principal") public ResponseEntity<User> currentPrincipal(@CurrentUser User user) { return new ResponseEntity<User>(user, HttpStatus.OK); } @Target(ElementType.PARAMETER) @Retention(RetentionPolicy.RUNTIME) @Documented @AuthenticationPrincipal public @interface CurrentUser { }
  • 10. Copyright ©2016 NS Solutions Corporation. All Rights Reserved. Path Variables in Web Security Expressions 10  Web Security Expressions で Path Variable を 使用できるようになった @Override protected void configure(HttpSecurity http) throws Exception { http .authorizeRequests() .antMatchers("/", "/assets/**", "/webjars/**").permitAll() .antMatchers("/users/{userId}").access("#userId == principal.id.toString()") .anyRequest().authenticated() .and() .httpBasic(); } @RequestMapping と同じで 中括弧で変数を指定 「#変数名」で使用できる
  • 11. Copyright ©2016 NS Solutions Corporation. All Rights Reserved. Referring to Beans in Web Security Expressions 11  Web Security Expressions で Bean を 使用できるようになった @Override protected void configure(HttpSecurity http) throws Exception { http .authorizeRequests() .antMatchers("/", "/assets/**", "/webjars/**").permitAll() .antMatchers("/users/{userId}").access("@authz.check(#userId,principal)") .anyRequest().authenticated() .and() .httpBasic(); } 「@Bean名」で使用できる @Component public class Authz { public boolean check(Long userId, User user) { return userId.equals(user.getId()); } } 「authz」というBean名で登録される @PreAuthorize や@PostAuthorize 等でも Bean を使用できる
  • 12. Copyright ©2016 NS Solutions Corporation. All Rights Reserved. MvcRequestMatcher 12  「/admin」のアクセス制限をした場合に、 「/admin/」からもアクセス制限できるようになった @Override protected void configure(HttpSecurity http) throws Exception { http .authorizeRequests() .antMatchers("/", "/assets/**", "/webjars/**").permitAll() .mvcMatchers("/admin").denyAll() .anyRequest().authenticated() .and() .httpBasic(); } antMatchers ではなく、 mvcMatchers を使用する @Override protected void configure(HttpSecurity http) throws Exception { http .authorizeRequests() .antMatchers("/", "/assets/**", "/webjars/**").permitAll() .antMatchers("/admin").denyAll() .anyRequest().authenticated() .and() .httpBasic(); } 下記のように antMatchers("/admin").denyAll() とした場合は、 「/admin/」でアクセスできる
  • 13. Copyright ©2016 NS Solutions Corporation. All Rights Reserved. おわりに 13  とても簡単にセキュリティ設定ができるので、 強固なアプリケーションを作ってください!  他にもいろいろな機能が 4.1 で追加されています  http://docs.spring.io/spring- security/site/docs/current/reference/htmlsingle/#new
  • 14. Copyright ©2016 NS Solutions Corporation. All Rights Reserved. 14 NS Solutions、NS(ロゴ)、NSSOLは、新日鉄住金ソリューションズ株式会社の登録商標です。 Javaは、米国ORACLE Corp.の登録商標です。 その他本文記載の会社名及び製品名は、それぞれ各社の商標又は登録商標です。