LoginSignup
2
1

More than 5 years have passed since last update.

Playframework2で外部サイト/ドメインの画像を読み込む

Last updated at Posted at 2018-03-03

Play2系で外部サイト/ドメインの画像表示

筆者は非エンジニアなのでHTTP周りに疎く、詰まったので同じような開発初心者のために投稿。
今回はクラウドストレージの画像にアクセスしたいというシチュエーションだった。

プロジェクトルートにあるイメージファイル同様でいけるんじゃないかと以下のコードで対応。

index.html
//他省略
<img src="example.png">

GoogleChromeでlocalhostにアクセスすると画像が表示されていない。

image.png

Refused to load the image '画像URL' because it violates the following 
Content Security Policy directive: "default-src 'self'". Note that 
'img-src' was not explicitly set, so 'default-src' is used as a fallback.

デベロッパーツールで上記の警告が。
どうやらセキュリティ的に良くないからやめなさいとのこと。
コンテンツセキュリティポリシーについて詳しくはこちらのリンクから。

解決法:セキュリティヘッダの設定を行う

Playの公式ドキュメントを参考に。
https://www.playframework.com/documentation/ja/2.4.x/SecurityHeaders

filterクラスを新規作成

プロジェクトルートにfilterクラスを配置。
筆者はScalaだったが、Javaの方は上記ドキュメントからソースを取得。

filter.scala
//上記リンクから引用(https://www.playframework.com/documentation/ja/2.4.x/SecurityHeader)
import javax.inject.Inject

import play.api.http.HttpFilters
import play.filters.headers.SecurityHeadersFilter

class Filters @Inject() (securityHeadersFilter: SecurityHeadersFilter) extends HttpFilters {
  def filters = Seq(securityHeadersFilter)
}

application.confに信頼するドメインを記述

application.conf

play.filters.headers.contentSecurityPolicy = "default-src 'self'; img-src 'self' example.com;"




読み込まれた!
image.png

2
1
0

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
2
1