How to set security headers in phoenix live view?

How do I set security header for phoenix elixir application.

I used this plug, but its not working.

defmodule Provider.Plugs.SecurityHeaders do
  @moduledoc """
  put response header for security
  """
  import Plug.Conn

  def init(opts), do: opts

  def call(conn, _opts) do
    conn
    |> put_resp_header("x-frame-options", "DENY")
    |> put_resp_header("content-security-policy", "frame-src 'self'; frame-ancestors 'none'")
    |> put_resp_header("x-content-type-options", "nosniff")
    |> put_resp_header("referrer-policy", "no-referrer")
    |> put_resp_header("cross-origin-opener-policy", "same-origin")
    |> put_resp_header("cross-origin-embedder-policy", "unsafe-none")
    |> put_resp_header("cross-origin-resource-policy", "same-origin")
    |> put_resp_header("strict-transport-security", "max-age=31536000; includeSubDomains")
  end
end

pipeline :browser do
    plug(:accepts, ["html"])
    plug(:fetch_session)
    # plug :fetch_flash
    plug(:fetch_live_flash)
    plug(:put_root_layout, {Provider.LayoutView, :root})
    plug(:protect_from_forgery)
    plug(:put_secure_browser_headers)
    plug(:load_information)
    plug(:fetch_current_user)
    plug(Provider.Plugs.CSP)
    plug(Provider.Plugs.SecurityHeaders)
  end

Can you elaborate on what this means? What did you expect to have happen, and what did happen?

3 Likes

Security headers are not being sent with the response.

It means security headers are not being set

I just want to set HTTP security headers for the phoenix application how do i do that?

You, sir or madam, need to work on your communication skills. You will not receive help if you’re unable to express yourself and describe the problem.

1 Like

Have a look at the documentation for put_secure_browser_headers.

A custom headers map may also be given to be merged with defaults. It is recommended for custom header keys to be in lowercase, to avoid sending duplicate keys in a request. Additionally, responses with mixed-case headers served over HTTP/2 are not considered valid by common clients, resulting in dropped responses.

pipeline :browser do
    ...
    plug :put_secure_browser_headers,
    %{
         "content-security-policy" =>
         "frame-src 'self'; frame-ancestors 'none'"
     }
end

But I have a seperate plug for putting csp.

But I want to put http security headers

X-Content-Type-Options: nosniff
Cross-Origin-Embedder-Policy
Cross-Origin-Opener-Policy:

etc.
I am currently using a plug,which puts response headers on incoming request from browser,
Is this the correct way to do it?
what is the correct way to set the security headers apart from CSP.

okay I wil improve

1 Like