{"componentChunkName":"component---src-templates-lesson-js","path":"/phoenix-chat/login-and-authentication-part-1","result":{"data":{"mdx":{"body":"function _extends() { _extends = Object.assign || function (target) { for (var i = 1; i < arguments.length; i++) { var source = arguments[i]; for (var key in source) { if (Object.prototype.hasOwnProperty.call(source, key)) { target[key] = source[key]; } } } return target; }; return _extends.apply(this, arguments); }\n\nfunction _objectWithoutProperties(source, excluded) { if (source == null) return {}; var target = _objectWithoutPropertiesLoose(source, excluded); var key, i; if (Object.getOwnPropertySymbols) { var sourceSymbolKeys = Object.getOwnPropertySymbols(source); for (i = 0; i < sourceSymbolKeys.length; i++) { key = sourceSymbolKeys[i]; if (excluded.indexOf(key) >= 0) continue; if (!Object.prototype.propertyIsEnumerable.call(source, key)) continue; target[key] = source[key]; } } return target; }\n\nfunction _objectWithoutPropertiesLoose(source, excluded) { if (source == null) return {}; var target = {}; var sourceKeys = Object.keys(source); var key, i; for (i = 0; i < sourceKeys.length; i++) { key = sourceKeys[i]; if (excluded.indexOf(key) >= 0) continue; target[key] = source[key]; } return target; }\n\n/* @jsx mdx */\nvar _frontmatter = {\n  \"title\": \"Login and Authentication: Part 1\",\n  \"order\": 19,\n  \"free\": false,\n  \"active\": true,\n  \"tech\": [\"phoenix\", \"elixir\", \"ueberauth\"]\n};\n\nvar makeShortcode = function makeShortcode(name) {\n  return function MDXDefaultShortcode(props) {\n    console.warn(\"Component \" + name + \" was not imported, exported, or provided by MDXProvider as global scope\");\n    return mdx(\"div\", props);\n  };\n};\n\nvar layoutProps = {\n  _frontmatter: _frontmatter\n};\nvar MDXLayout = \"wrapper\";\nreturn function MDXContent(_ref) {\n  var components = _ref.components,\n      props = _objectWithoutProperties(_ref, [\"components\"]);\n\n  return mdx(MDXLayout, _extends({}, layoutProps, props, {\n    components: components,\n    mdxType: \"MDXLayout\"\n  }), mdx(\"h1\", null, \"Login and Authentication: Part 1\"), mdx(\"ul\", null, mdx(\"li\", {\n    \"parentName\": \"ul\"\n  }, \"Sign in\"), mdx(\"li\", {\n    \"parentName\": \"ul\"\n  }, \"Ueberauth and Guardian\"), mdx(\"li\", {\n    \"parentName\": \"ul\"\n  }, \"Plugs\")), mdx(\"p\", null, \"In this section, we go over Elixir plugs and add user authentication with Ueberauth and Guardian. We also set up an authentication controller (\", mdx(\"inlineCode\", {\n    \"parentName\": \"p\"\n  }, \"AuthController\"), \") to handle requests that need authorization.\"), mdx(\"h2\", null, \"Account login\"), mdx(\"p\", null, \"Now that we can register for an account, we'll want to sign in. But what does it mean to \\\"log in\\\"? The question is more complex than most people realize. There are many ways of approaching this problem, but we are going to use a JSON web token (JWT) for user authentication.\"), mdx(\"p\", null, \"A JSON web token is a random string that our server generates after a user passes in valid credentials (username and password). A JSON web token looks something like this:\"), mdx(\"pre\", null, mdx(\"code\", {\n    \"className\": \"language-text\",\n    \"parentName\": \"pre\"\n  }, \"2b125jQggWD1BFWECdbQyxe4KXVB18Sgi64m9Iu2MgCciljCCsIG\\n\")), mdx(\"p\", null, \"When a user passes valid credentials to our server, our server will respond with a JSON web token that we can store in our browser either in \", mdx(\"inlineCode\", {\n    \"parentName\": \"p\"\n  }, \"cookies\"), \" or \", mdx(\"inlineCode\", {\n    \"parentName\": \"p\"\n  }, \"localStorage\"), \". For a user to be considered \\\"logged in\\\", we send that JSON web token in a request to our server asking, \\\"Is this JSON web token still valid?\\\" If the response is in the affirmative, then the user is logged in. If the response is negative, then the user is not logged in.\"), mdx(\"p\", null, \"When a user logs out, we remove the JSON web token from \", mdx(\"inlineCode\", {\n    \"parentName\": \"p\"\n  }, \"localStorage\"), \" and send a request to our server to invalidate the token to ensure it cannot be used again. This prevents what is called a \", mdx(\"a\", {\n    \"href\": \"https://en.wikipedia.org/wiki/Replay_attack\",\n    \"parentName\": \"p\"\n  }, \"replay attack\"), \" where someone uses an old JSON web token to gain access to your account.\"), mdx(\"p\", null, \"The basic strategy we're going to use follows the flow chart below.\"), mdx(\"p\", null, mdx(\"img\", {\n    \"src\": \"https://raw.githubusercontent.com/LearnPhoenix/graphics/master/jwt.png\",\n    \"alt\": \"jwt flow chart\",\n    \"parentName\": \"p\"\n  })), mdx(\"p\", null, \"For more information on how JSON web tokens work, check out \", mdx(\"a\", {\n    \"href\": \"https://jwt.io\",\n    \"parentName\": \"p\"\n  }, \"jwt.io\"), \".\"), mdx(\"p\", null, \"For authentication we'll work with \", mdx(\"a\", {\n    \"href\": \"https://github.com/ueberauth\",\n    \"parentName\": \"p\"\n  }, \"\\xDCberauth\"), \" (often spelled Ueberauth, without the \", mdx(\"a\", {\n    \"href\": \"https://en.wikipedia.org/wiki/%C3%9C\",\n    \"parentName\": \"p\"\n  }, \"u-umlaut\"), \" -- this is how we will refer to it going forward). Ueberauth is an authentication framework that allows us to use many different strategies to authenticate users. For now we'll use \", mdx(\"a\", {\n    \"href\": \"https://github.com/ueberauth/ueberauth_identity\",\n    \"parentName\": \"p\"\n  }, \"Ueberauth Identity\"), \" to implement our email-password authentication but later we can use \", mdx(\"a\", {\n    \"href\": \"https://github.com/ueberauth/ueberauth_twitter\",\n    \"parentName\": \"p\"\n  }, \"Ueberauth Twitter\"), \", \", mdx(\"a\", {\n    \"href\": \"https://github.com/ueberauth/ueberauth_facebook\",\n    \"parentName\": \"p\"\n  }, \"Ueberauth Facebook\"), \", and several others.\"), mdx(\"p\", null, \"In addition to Ueberauth and Ueberauth Identity, we'll use \", mdx(\"a\", {\n    \"href\": \"https://github.com/ueberauth/guardian\",\n    \"parentName\": \"p\"\n  }, \"Guardian\"), \" to generate our JSON web tokens. If you're not familiar with JSON web tokens, we will cover them in greater detail later.\"), mdx(\"p\", null, \"If you're interested to see how Ueberauth works with multiple strategies, take a look at the \", mdx(\"a\", {\n    \"href\": \"https://github.com/ueberauth/ueberauth_example\",\n    \"parentName\": \"p\"\n  }, \"Ueberauth Example\"), \" project provided by the Ueberauth team.\"), mdx(\"p\", null, \"Let's go ahead and add \", mdx(\"inlineCode\", {\n    \"parentName\": \"p\"\n  }, \"ueberauth\"), \", \", mdx(\"inlineCode\", {\n    \"parentName\": \"p\"\n  }, \"ueberauth_identity\"), \", and \", mdx(\"inlineCode\", {\n    \"parentName\": \"p\"\n  }, \"guardian\"), \" to our project's dependecies in \", mdx(\"inlineCode\", {\n    \"parentName\": \"p\"\n  }, \"mix.exs\"), \":\"), mdx(\"pre\", null, mdx(\"code\", {\n    \"className\": \"language-elixir\",\n    \"parentName\": \"pre\"\n  }, \"defp deps do\\n  [\\n    {:comeonin, \\\"~> 2.3\\\"},\\n    ...\\n    {:ueberauth, \\\"~> 0.2\\\"},\\n    {:ueberauth_identity, \\\"~> 0.2\\\"},\\n    {:guardian, \\\"~> 0.10\\\"}\\n  ]\\nend\\n\")), mdx(\"p\", null, \"We need to add both \", mdx(\"inlineCode\", {\n    \"parentName\": \"p\"\n  }, \"ueberauth\"), \" and \", mdx(\"inlineCode\", {\n    \"parentName\": \"p\"\n  }, \"ueberauth_identity\"), \" to our project's applications:\"), mdx(\"pre\", null, mdx(\"code\", {\n    \"className\": \"language-elixir\",\n    \"parentName\": \"pre\"\n  }, \"def application do\\n  [mod: {PhoenixChat, []},\\n    applications: [\\n      :comeonin,\\n      ...\\n      :ueberauth,\\n      :ueberauth_identity\\n    ]]\\nend\\n\")), mdx(\"p\", null, \"Let's run \", mdx(\"inlineCode\", {\n    \"parentName\": \"p\"\n  }, \"mix deps.get\"), \" and get our new dependencies:\"), mdx(\"pre\", null, mdx(\"code\", {\n    \"className\": \"language-bash\",\n    \"parentName\": \"pre\"\n  }, \"$ mix deps.get\\n\")), mdx(\"h2\", null, \"Configuring Ueberauth\"), mdx(\"p\", null, \"The next thing to do is configure Ueberauth. Within \", mdx(\"inlineCode\", {\n    \"parentName\": \"p\"\n  }, \"config/config.exs\"), \", add the following:\"), mdx(\"pre\", null, mdx(\"code\", {\n    \"className\": \"language-elixir\",\n    \"parentName\": \"pre\"\n  }, \"config :ueberauth, Ueberauth,\\n  providers: [\\n    identity: {\\n      Ueberauth.Strategy.Identity,\\n      [callback_methods: [\\\"POST\\\"]]\\n    }\\n  ]\\n\")), mdx(\"p\", null, \"This is taken straight from the docs, but what it is doing is telling Ueberauth that we are using the \", mdx(\"inlineCode\", {\n    \"parentName\": \"p\"\n  }, \"identity\"), \" strategy to log in users with a username-password combination. At some point later on, we can add Twitter and Facebook login to the \", mdx(\"inlineCode\", {\n    \"parentName\": \"p\"\n  }, \"providers\"), \" list.\"), mdx(\"h2\", null, \"Configuring Guardian\"), mdx(\"p\", null, \"While we're in \", mdx(\"inlineCode\", {\n    \"parentName\": \"p\"\n  }, \"config/config.exs\"), \" let's add our Guardian configuration:\"), mdx(\"pre\", null, mdx(\"code\", {\n    \"className\": \"language-elixir\",\n    \"parentName\": \"pre\"\n  }, \"config :guardian, Guardian,\\n  issuer: \\\"PhoenixChat\\\",\\n  ttl: {30, :days},\\n  secret_key: \\\"uw/27wdrIquPn2fktwfJg9tg8qOl5ysTPCFjISw1TCCaLlfWgRUAea1SuWcfERzX\\\",\\n  serializer: PhoenixChat.GuardianSerializer,\\n  permissions: %{default: [:read, :write]}\\n\")), mdx(\"p\", null, \"Before we go any further, let's generate a new \", mdx(\"inlineCode\", {\n    \"parentName\": \"p\"\n  }, \"secret_key\"), \" (it's not very secret otherwise). We can either come up with a random string or we can use the handy generator provided by Phoenix:\"), mdx(\"pre\", null, mdx(\"code\", {\n    \"className\": \"language-bash\",\n    \"parentName\": \"pre\"\n  }, \"$ mix phoenix.gen.secret\\n\")), mdx(\"p\", null, \"Copy and paste the output into the \", mdx(\"inlineCode\", {\n    \"parentName\": \"p\"\n  }, \"secret_key\"), \" value above and we're done. For now storing the \", mdx(\"inlineCode\", {\n    \"parentName\": \"p\"\n  }, \"secret_key\"), \" in the file is fine but later we will move this into a system environment variable; relying on our system's environment lets us remove passwords and secret keys from our code and source control, limiting its exposure.\"), mdx(\"p\", null, \"The last step of our Guardian configuration is to create the \", mdx(\"inlineCode\", {\n    \"parentName\": \"p\"\n  }, \"PhoenixChat.GuardianSerializer\"), \" we specified. We'll put this file in a new directory within the \", mdx(\"inlineCode\", {\n    \"parentName\": \"p\"\n  }, \"web\"), \" directory:\"), mdx(\"pre\", null, mdx(\"code\", {\n    \"className\": \"language-bash\",\n    \"parentName\": \"pre\"\n  }, \"$ mkdir web/auth\\n$ touch web/auth/guardian_serializer.ex\\n\")), mdx(\"p\", null, \"Let's open the serializer at \", mdx(\"inlineCode\", {\n    \"parentName\": \"p\"\n  }, \"web/auth/guardian_serializer.ex\"), \" and update the file to look like this:\"), mdx(\"pre\", null, mdx(\"code\", {\n    \"className\": \"language-elixir\",\n    \"parentName\": \"pre\"\n  }, \"defmodule PhoenixChat.GuardianSerializer do\\n  @behaviour Guardian.Serializer\\n\\n  alias PhoenixChat.{Repo, User}\\n\\n  def for*token(%User{id: id}), do: {:ok, \\\"User:#{id}\\\"}\\n  def for_token(*), do: {:error, \\\"Unknown resource type\\\"}\\n\\n  def from*token(\\\"User:\\\" <> id), do: {:ok, Repo.get(User, id)}\\n  def from_token(*), do: {:error, \\\"Unknown resource type\\\"}\\nend\\n\\n\")), mdx(\"p\", null, \"We don't need to dig into this too much as this is verbatim from the Guardian documentation. Once we start using our authentication system, we can come back to this and it will make more sense. The serializer is what ties Guardian in with our user systems. Guardian relies on the \", mdx(\"inlineCode\", {\n    \"parentName\": \"p\"\n  }, \"for_token/1\"), \" function to convert a given \", mdx(\"inlineCode\", {\n    \"parentName\": \"p\"\n  }, \"%User{}\"), \" into a token. The \", mdx(\"inlineCode\", {\n    \"parentName\": \"p\"\n  }, \"from_token/1\"), \" function does the opposite, retrieving our user from a given token.\"), mdx(\"p\", null, \"A quick thing to note is \", mdx(\"inlineCode\", {\n    \"parentName\": \"p\"\n  }, \"@behaviour\"), \". Elixir is built on Erlang, which uses the British version of some English words. Just keep that in mind going forward.\"), mdx(\"p\", null, \"The next few steps require a deeper dive into Phoenix.\"), mdx(\"h2\", null, \"Plugs\"), mdx(\"p\", null, \"In many ways, every app is just a series of functions. React has popularized this approach on the frontend, each function either transforms data or triggers a side-effect like rendering to the DOM or a change to the database.\"), mdx(\"p\", null, \"Plug is a library that takes a connection and returns a modified version of the connection. With plugs you can authenticate users, validate requests, send HTTP responses, sanitize inputs, and trigger background work. Throughout this course, we'll cover these and many other uses for plugs.\"), mdx(\"p\", null, \"Since plugs are so flexible it's no surprise that our Phoenix app is nothing more than a series of plugs.\"), mdx(\"h2\", null, \"Creating our AuthController\"), mdx(\"p\", null, \"For this controller we're not going to use a generator. Instead, we're going to create it manually so we can take a closer look at the different components.\"), mdx(\"p\", null, \"The way the Phoenix directory structure is set up everything web-related lives within the \", mdx(\"inlineCode\", {\n    \"parentName\": \"p\"\n  }, \"web\"), \" directory. Since we are building a web API, most of what we are doing will be within this directory.\"), mdx(\"p\", null, \"Let's create our auth controller:\"), mdx(\"pre\", null, mdx(\"code\", {\n    \"className\": \"language-bash\",\n    \"parentName\": \"pre\"\n  }, \"$ touch web/controllers/auth_controller.ex\\n\")), mdx(\"p\", null, \"Now update the new file to look like this:\"), mdx(\"pre\", null, mdx(\"code\", {\n    \"className\": \"language-elixir\",\n    \"parentName\": \"pre\"\n  }, \"defmodule PhoenixChat.AuthController do\\n  use PhoenixChat.Web, :controller\\n  plug Ueberauth\\n\\nend\\n\\n\")), mdx(\"p\", null, \"Here we define our new module and include some helper methods from the \", mdx(\"inlineCode\", {\n    \"parentName\": \"p\"\n  }, \"PhoenixChat.Web\"), \" module for controllers. We've also included a plug for Ueberauth in our controller. When requests come into our controller, they will be routed through the Ueberauth plug. We'll revisit the Ueberauth plug shortly.\"), mdx(\"p\", null, mdx(\"strong\", {\n    \"parentName\": \"p\"\n  }, \"Note on debugging in Elixir:\"), \" In Elixir, you can log to the terminal with \", mdx(\"inlineCode\", {\n    \"parentName\": \"p\"\n  }, \"IO.puts\"), \" or \", mdx(\"inlineCode\", {\n    \"parentName\": \"p\"\n  }, \"Logger.debug\"), \" after adding \", mdx(\"inlineCode\", {\n    \"parentName\": \"p\"\n  }, \"require Logger\"), \". This is one of the primary means by which you can debug your apps. It's identical to \", mdx(\"inlineCode\", {\n    \"parentName\": \"p\"\n  }, \"console.log()\"), \" if you're a JavaScript developer or \", mdx(\"inlineCode\", {\n    \"parentName\": \"p\"\n  }, \"puts\"), \" if you're a Ruby developer.\"), mdx(\"p\", null, \"In fact, we will keep this controller mostly empty for the time being and just add a log to show that it was hit. This will cause an error, but it will show that the request was hit. Change your \", mdx(\"inlineCode\", {\n    \"parentName\": \"p\"\n  }, \"AuthController\"), \" to the following:\"), mdx(\"pre\", null, mdx(\"code\", {\n    \"className\": \"language-elixir\",\n    \"parentName\": \"pre\"\n  }, \"defmodule PhoenixChat.AuthController do\\n  use PhoenixChat.Web, :controller\\n\\n  def test(conn, _params) do\\n    IO.puts \\\"AuthController called!\\\"\\n    conn\\n  end\\nend\\n\")), mdx(\"p\", null, \"Open \", mdx(\"inlineCode\", {\n    \"parentName\": \"p\"\n  }, \"web/router.ex\"), \" and make the following changes:\"), mdx(\"pre\", null, mdx(\"code\", {\n    \"className\": \"language-elixir\",\n    \"parentName\": \"pre\"\n  }, \"...\\n\\nscope \\\"/api\\\", PhoenixChat do\\npipe_through :api\\n\\n    get \\\"/auth\\\", AuthController, :test\\n    resources \\\"/users\\\", UserController, except: [:new, :edit]\\n\\nend\\n\\n...\\n\\n\")), mdx(\"p\", null, \"For now we want to direct anyone who runs a \", mdx(\"inlineCode\", {\n    \"parentName\": \"p\"\n  }, \"GET\"), \" request to \", mdx(\"inlineCode\", {\n    \"parentName\": \"p\"\n  }, \"/api/auth\"), \" to be routed to the \", mdx(\"inlineCode\", {\n    \"parentName\": \"p\"\n  }, \"AuthController\"), \" and the \", mdx(\"inlineCode\", {\n    \"parentName\": \"p\"\n  }, \"test/2\"), \" function we created.\"), mdx(\"p\", null, \"To try out our new route, start your server:\"), mdx(\"pre\", null, mdx(\"code\", {\n    \"className\": \"language-bash\",\n    \"parentName\": \"pre\"\n  }, \"$ mix phoenix.server\\n\\nGenerated PhoenixChat app\\n[info] Running PhoenixChat.Endpoint with Cowboy using http on port 4000\\n\")), mdx(\"p\", null, \"Open up a browser and visit \", mdx(\"inlineCode\", {\n    \"parentName\": \"p\"\n  }, \"localhost:4000/api/auth\"), \". We won't see anything in the browser because we aren't telling Phoenix to render any HTML, but if you head over to your terminal (the one in which you ran \", mdx(\"inlineCode\", {\n    \"parentName\": \"p\"\n  }, \"mix pheonix.server\"), \"), you should see the output \\\"AuthController called!\\\" just before the error.\"), mdx(\"pre\", null, mdx(\"code\", {\n    \"className\": \"language-bash\",\n    \"parentName\": \"pre\"\n  }, \"[info] GET /api/auth\\nAuthController called!\\n[debug] Processing by PhoenixChat.AuthController.test/2\\n  Parameters: %{}\\n  Pipelines: [:api]\\n  ...\\n\")), mdx(\"p\", null, \"This is a contrived example, but you can see the following happen:\"), mdx(\"pre\", null, mdx(\"code\", {\n    \"className\": \"language-elixir\",\n    \"parentName\": \"pre\"\n  }, \"connection\\n|> router\\n|> api_pipeline\\n|> AuthController.test\\n\")), mdx(\"p\", null, \"The connection was sent through a series of functions and transformations before finally being returned to the user.\"));\n}\n;\nMDXContent.isMDXComponent = true;","excerpt":"Login and Authentication: Part 1 Sign in Ueberauth and Guardian Plugs In this section, we go over Elixir plugs and add user authentication…","frontmatter":{"title":"Login and Authentication: Part 1","order":19,"active":true,"free":false,"tech":["phoenix","elixir","ueberauth"]}}},"pageContext":{"slug":"login-and-authentication-part-1","prevNode":{"frontmatter":{"title":"Actions, Reducers, and Store","active":true,"free":false,"order":18,"tech":["react","redux"]},"fields":{"slug":"actions-reducers-and-store"}},"nextNode":{"frontmatter":{"title":"Login and Authentication: Part 2","active":true,"free":false,"order":20,"tech":["phoenix","elixir","ueberauth"]},"fields":{"slug":"login-and-authentication-part-2"}}}},"staticQueryHashes":["1723017916"]}