{"title":"Authenticate","description":"","section":"cookbook","version":"v1.5","path":"cookbook/authenticate","canonical_url":"https://amberframework.org/docs/v1.5/cookbook/authenticate","markdown_url":"https://amberframework.org/docs/v1.5/cookbook/authenticate.md","inherited":true,"content_markdown":"# Authenticate\n\nThis recipe will help you to setup an authentication pipe in your application:\n\n{% hint style=\"warning\" %}\nFirst you need an amber project generated with [Amber CLI](../guides/create-new-app.md) or [from scratch](from-scratch.md).\n{% endhint %}\n\n{% code-tabs %}\n{% code-tabs-item title=\"src/pipes/authenticate.cr\" %}\n```crystal\nclass Authenticate < Amber::Pipe::Base\n  PUBLIC_PATHS = [\"/\"]\n\n  def call(context)\n    some_id = context.session[\"some_id\"]? # setup by some controller\n    if some_id || public_path?(context.request.path)\n      call_next(context)\n    else\n      context.flash[:warning] = \"Please Sign In\"\n      context.response.headers.add \"Location\", \"/\"\n      context.response.status_code = 302\n    end\n  end\n\n  private def public_path?(path)\n    PUBLIC_PATHS.includes?(path)\n\n    # Different strategies can be used to determine if a path is public\n    # Example, if /admin/* paths are the only private paths\n    # return false if path.starts_with?(\"/admin\")\n    #\n    # Example, if only a few private paths exist\n    # return false if [\"/secret\", \"/super/secret\"].includes?(path)\n  end\nend\n```\n{% endcode-tabs-item %}\n{% endcode-tabs %}\n\nThen in your routes file:\n\n{% code-tabs %}\n{% code-tabs-item title=\"config/routes.cr\" %}\n```crystal\nAmber::Server.configure do |app|\n  pipeline :web do\n    # other pipes...\n    plug Authenticate.new\n  end\n\n  routes :web do\n    # some routes,,,\n  end\nend\n```\n{% endcode-tabs-item %}\n{% endcode-tabs %}\n\nTo have a full authentication experience some extra controllers, views and models are still required, please see [Amber Auth Example](../examples/amber-auth.md).\n\nAlso see [pipelines](../guides/routing/pipelines.md)."}