Giter Club home page Giter Club logo

ueberauth_slack's Introduction

Überauth

Build Status Codecov Inline docs Hex Version Hex docs Total Download License Last Updated

An Elixir Authentication System for Plug-based Web Applications

Ueberauth is a two-phase authentication framework that provides a clear API - allowing for many strategies to be created and shared within the community. It is heavily inspired by Omniauth. You could call it a port but it is significantly different in operation - but almost the same concept. Huge hat tip to Intridea.

Ueberauth provides only the initial authentication challenge, (initial OAuth flow, collecting the information from a login form, etc). It does not authenticate each request, that's up to your application. You could issue a token or put the result into a session for your applications needs. Libraries like Guardian can help you with that aspect of authentication.

The two phases are request and callback. These phases are implemented by Strategies.

Strategies

Strategies are plugs that decorate or intercept requests (or both).

Strategies implement the two phases and then may allow the request to flow through to your downstream plugs. Implementing the request and callback phases is optional depending on the strategies requirements. If a strategy does not redirect, the request will be decorated with Ueberauth information and allowed to carry on through the pipeline.

See the full list of the strategies on the Wiki.

Request Phase

The request phase is where you request information about the user. This could be a redirect to an OAuth2 authorization url or a form for collecting username and password. The request phase is concerned with only the collection of information. When a request comes in on the request phase url the relevant strategy will receive the handle_request! call.

In some cases (default) the application using Ueberauth is responsible for implementing the request phase. That is, you should set up a route to receive the request phase and provide a form etc. In some cases, like OAuth, the request phase is used to redirect your user to a 3rd party site to fulfill the request.

For example, an OAuth strategy for GitHub will receive the request phase url and stop the request, redirecting you to GitHub’s OAuth challenge url with some query parameters. Once you complete the GitHub OAuth flow, the user will be redirected back to the host site to the callback URL.

Another example is simple email/password authentication. A request is made by the client to the request phase path and the host application displays a form. The strategy will likely not do anything with the incoming handle_request! request and simply pass through to the application. Once the form is completed, the POST should go to the callback url where it is handled (passwords checked, users created / authenticated).

Callback Phase

The callback phase is where the fun happens. Once a successful request phase has been completed, the request phase provider (OAuth provider or host site, etc) should call the callback URL. The strategy will intercept the request via the handle_callback!. If successful, it should prepare the connection so the Ueberauth.Auth struct can be created, or set errors to indicate a failure.

See Ueberauth.Strategy for more information on constructing the Ueberauth.Auth struct.

Looking for an example? Take a look ueberauth/ueberauth_example.

Setup

Add the dependency

# mix.exs

defp deps do
  # Add the dependency
  [{:ueberauth, "~> 0.10"}]
end

Fetch the dependencies

mix deps.get

Configuring providers

In your configuration file (config/config.exs) provide a list of the providers you intend to use. For example:

config :ueberauth, Ueberauth,
  providers: [
    facebook: { Ueberauth.Strategy.Facebook, [ opt1: "value", opts2: "value" ] },
    github: { Ueberauth.Strategy.Github, [ opt1: "value", opts2: "value" ] }
  ]

This will define two providers for you. The general structure of the providers value is:

config :ueberauth, Ueberauth,
  providers: [
    <provider name>: { <Strategy Module>, [ <strategy options> ] }
  ]

We use the configuration options for defining these to allow for dependency injection in different environments. The provider name will be used to construct request and response paths (by default) but will also be returned in the Ueberauth.Auth struct as the provider field.

Once you've setup your providers, in your router you need to configure the plug to run. The plug should run before your application routes.

In phoenix, plug this module in your controller:

defmodule MyApp.AuthController do
  use MyApp.Web, :controller
  plug Ueberauth
  ...
end

Its URL matching is done via pattern matching rather than explicit runtime checks so your strategies will only fire for relevant requests.

Now that you have this, your strategies will intercept relevant requests for each strategy for both request and callback phases. The default urls are (for our Facebook & GitHub example)

# Request phase paths
/auth/facebook
/auth/github

# Callback phase paths
/auth/facebook/callback
/auth/github/callback

Customizing Paths

These paths can be configured on a per strategy basis by setting options on the provider.

Note: These paths are absolute

config :ueberauth, Ueberauth,
  base_path: "/login", # default is "/auth"
  providers: [
    identity: {Ueberauth.Strategies.Identity, [request_path: "/login/identity",
                                               callback_path: "/login/identity/callback"]}
  ]

Customizing JSON Serializer

Your JSON serializer can be configured depending on what you have installed in your application. Defaults to Jason.

config :ueberauth, Ueberauth,
  json_library: Poison # default is Jason

HTTP Methods

By default, all callback URLs are only available via the "GET" method. You can override this via options to your strategy.

providers: [
  identity: {Ueberauth.Strategies.Identity, [callback_methods: ["POST"]]}
]

Strategy Options

All options that are passed into your strategy are available at runtime to modify the behaviour of the strategy.

Copyright and License

Copyright (c) 2015 Sonny Scroggin

Released under the MIT License, which can be found in the repository in LICENSE.

ueberauth_slack's People

Stargazers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

Watchers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar

ueberauth_slack's Issues

Doesn't work with ueberauth 0.7.0

Authentication callback fails with CSFR error.

%Ueberauth.Failure.Error{message: "Cross-Site Request Forgery attack", message_key: :csrf_attack}

if "team:read" is not present in the scope, authentification fail

The error is :
** (exit) an exception was raised: (KeyError) key :slack_team not found in: %{ ..... ..... lib/ueberauth/strategy/slack.ex:165: Ueberauth.Strategy.Slack.extra/1

I saw you have a condition on this scope, but somehow it still try to access it. I don't really know where the problem come from.

Incompatible with ueberauth_github

Hello,

It seems the current version is not compatible with oauth2 0.8.

I tried to update the calls but have had no success, I don't quite understand everything the code does (I have just started learning elixir).

After seeing the github strategy was updated I tried to follow the way it is donewith no success.

Any plans to update this strategy?

Thanks!

key :slack_team not found during callback

Hello

I have set up my auth server according to your README and following the ueberauth example, however I am stuck with this error when trying to use the Slack button

https://api.slack.com/docs/slack-button

Request: GET /auth/slack/callback?code=32537399780.69572279236.f19e2f3c2f&state=
2016-08-15T18:45:44.932301+00:00 app[web.1]: ** (exit) an exception was raised:
2016-08-15T18:45:44.932304+00:00 app[web.1]:     ** (KeyError) key :slack_team not found in: %{EchochamberIo.Router => {[], %{}}, :phoenix_action => :callback, :phoenix_controller => EchochamberIo.AuthController, :phoenix_endpoint => EchochamberIo.Endpoint, :phoenix_flash => %{}, :phoenix_format => "html", :phoenix_layout => {EchochamberIo.LayoutView, :app}, :phoenix_pipelines => [:browser], :phoenix_route => #Function<10.117359548/1 in EchochamberIo.Router.match_route/4>, :phoenix_router => EchochamberIo.Router, :phoenix_view => EchochamberIo.AuthView, :plug_session => %{}, :plug_session_fetch => :done, :slack_auth => %{"ok" => true, "team" => "joemsak", "team_id" => "[FILTERED]", "url" => "https://joemsak.slack.com/", "user" => "joemsak", "user_id" => "[FILTERED]"}, :slack_token => %OAuth2.AccessToken{access_token: "[FILTERED]", client: %OAuth2.Client{authorize_url: "https://slack.com/oauth/authorize", client_id: "[FILTERED]", client_secret: "[FILTERED]", headers: [], params: %{"client_id" => "[FILTERED]", "client_secret" => "[FILTERED]", "code" => "[FILTERED]", "grant_type" => "authorization_code", "redirect_uri" => "https://echo-chmbr.herokuapp.com/auth/slack/callback"}, redirect_uri: "https://echo-chmbr.herokuapp.com/auth/slack/callback", site: "https://slack.com/api", strategy: Ueberauth.Strategy.Slack.OAuth, token_method: :post, token_url: "https://slack.com/api/oauth.access"}, expires_at: nil, other_params: %{"ok" => true, "scope" => "identify,users:read", "team_id" => "[FILTERED]", "team_name" => "joemsak", "user_id" => "[FILTERED]"}, refresh_token: nil, token_type: "Bearer"}, :slack_user => %{"color" => "9f69e7", "deleted" => false, "has_2fa" => false, "id" => "[FILTERED]", "is_admin" => true, "is_bot" => false, "is_owner" => true, "is_primary_owner" => true, "is_restricted" => false, "is_ultra_restricted" => false, "name" => "joemsak", "profile" => %{"avatar_hash" => "b082e9bf3676", "email" => "[email protected]", "first_name" => "Joe", "image_1024" => "https://avatars.slack-edge.com/2016-06-10/49902273206_b082e9bf36764cc67146_192.jpg", "image_192" => "https://avatars.slack-edge.com/2016-06-10/49902273206_b082e9bf36764cc67146_192.jpg", "image_24" => "https://avatars.slack-edge.com/2016-06-10/49902273206_b082e9bf36764cc67146_24.jpg", "image_32" => "https://avatars.slack-edge.com/2016-06-10/49902273206_b082e9bf36764cc67146_32.jpg", "image_48" => "https://avatars.slack-edge.com/2016-06-10/49902273206_b082e9bf36764cc67146_48.jpg", "image_512" => "https://avatars.slack-edge.com/2016-06-10/49902273206_b082e9bf36764cc67146_192.jpg", "image_72" => "https://avatars.slack-edge.com/2016-06-10/49902273206_b082e9bf36764cc67146_72.jpg", "image_original" => "https://avatars.slack-edge.com/2016-06-10/49902273206_b082e9bf36764cc67146_original.jpg", "last_name" => "Sak", "phone" => "517 944 5230", "real_name" => "Joe Sak", "real_name_normalized" => "Joe Sak", "skype" => "joemsak", "title" => "Software Craftsmanship Mentor"}, "real_name" => "Joe Sak", "status" => nil, "team_id" => "[FILTERED]", "tz" => "America/Indiana/Indianapolis", "tz_label" => "Eastern Daylight Time", "tz_offset" => -14400}, :ueberauth_request_options => %{callback_methods: ["GET"], callback_path: "/auth/slack/callback", callback_url: nil, options: [team: nil], request_path: "/auth/slack", strategy: Ueberauth.Strategy.Slack, strategy_name: :slack}}
2016-08-15T18:45:44.932305+00:00 app[web.1]:         (ueberauth_slack) lib/ueberauth/strategy/slack.ex:162: Ueberauth.Strategy.Slack.extra/1
2016-08-15T18:45:44.932305+00:00 app[web.1]:         (ueberauth_slack) lib/ueberauth/strategy/slack.ex:18: Ueberauth.Strategy.Slack.auth/1
2016-08-15T18:45:44.932306+00:00 app[web.1]:         (ueberauth) lib/ueberauth/strategy.ex:308: Ueberauth.Strategy.handle_callback_result/2
2016-08-15T18:45:44.932307+00:00 app[web.1]:         (ueberauth) lib/ueberauth/strategy.ex:300: Ueberauth.Strategy.run_callback/2
2016-08-15T18:45:44.932312+00:00 app[web.1]:         (echochamber_io) web/controllers/auth_controller.ex:1: EchochamberIo.AuthController.phoenix_controller_pipeline/2
2016-08-15T18:45:44.932313+00:00 app[web.1]:         (echochamber_io) lib/echochamber_io/endpoint.ex:1: EchochamberIo.Endpoint.instrument/4
2016-08-15T18:45:44.932313+00:00 app[web.1]:         (echochamber_io) lib/phoenix/router.ex:261: EchochamberIo.Router.dispatch/2
2016-08-15T18:45:44.932314+00:00 app[web.1]:         (echochamber_io) web/router.ex:1: EchochamberIo.Router.do_call/2
2016-08-15T18:45:44.852866+00:00 heroku[router]: at=info method=GET path="/auth/slack/callback?code=32537399780.69572279236.f19e2f3c2f&state=" host=echo-chmbr.herokuapp.com request_id=b03594f0-6219-45c5-b726-60b54f3fe35a fwd="50.232.114.250" dyno=web.1 connect=0ms service=260ms status=500 bytes=435

I get this error whether I add team:read to scopes or not

Exchanging a verification code for an access token no longer works

Summary

The example Heroku app with Slack no longer seems to handle Step 3 of the Slack OAuth sign in. I can confirm this same thing happens with my own app.

Steps to reproduce

  1. Head to sample Heroku app on any browser (I've tried this on Safari, Firefox, Chrome on Mac OSX 10.13.5 High Sierra)
  2. Click "Sign in with Slack"
  3. Click "Authorize"
    Expected: The app was installed (my app) and I was signed in successfully (sample app and my app)
    Actual: The response on the Heroku app says "Internal Server Error" (both apps)

Config Info

These are the relevant pieces from my Elixir/Phoenix app to compare against the sample app:

  def project do
    [
      elixir: "~> 1.4",
    ]
  end
  defp deps do
    [
      {:phoenix, "~> 1.3.2"},
      {:phoenix_pubsub, "~> 1.0"},
      {:phoenix_ecto, "~> 3.2"},
      {:postgrex, ">= 0.0.0"},
      {:phoenix_html, "~> 2.10"},
      {:phoenix_live_reload, "~> 1.0", only: :dev},
      {:gettext, "~> 0.11"},
      {:cowboy, "~> 1.0"},
      {:oauth, github: "tim/erlang-oauth"},
      {:oauth2, "~> 0.8", override: true},
      {:ueberauth, "~> 0.4"},
      {:ueberauth_slack, "~> 0.4"},
      {:poison, "~> 3.0", override: true}
    ]
  end

Possible solution

I noticed with my app it was returning this in the logs (sensitive information redacted, also formatted because GitHub sucks at long lines):

** (KeyError) key :access_token not found in: 

%OAuth2.Client{
  authorize_url: "https://slack.com/oauth/authorize", 
  client_id: "XXX.YYY", 
  client_secret: "THESECRET", 
  headers: [], 
  params: %{}, 
  redirect_uri: "https://myapp.herokuapp.com/auth/slack/callback", 
  ref: nil, 
  request_opts: [], 
  site: "https://slack.com/api", 
  strategy: Ueberauth.Strategy.Slack.OAuth, 
  token: %OAuth2.AccessToken{
    access_token: nil, 
    expires_at: nil, 
    other_params: %{
      "error" => "bad_client_secret", 
      "ok" => false
    }, 
    refresh_token: nil, 
    token_type: "Bearer"
  }, 
  token_method: :post, 
  token_url: "https://slack.com/api/oauth.access"
}

2018-06-26T03:37:24.064879+00:00 app[web.1]:(ueberauth_slack) 
lib/ueberauth/strategy/slack.ex:63: 
Ueberauth.Strategy.Slack.handle_callback!/1

2018-06-26T03:37:24.064881+00:00 app[web.1]:(ueberauth) 
lib/ueberauth/strategy.ex:301: 
Ueberauth.Strategy.run_callback/2

2018-06-26T03:37:24.064883+00:00 app[web.1]:(myapp) 
lib/myapp_web/controllers/auth_controller.ex:1:
MyappWeb.AuthController.phoenix_controller_pipeline/2

Notice the error points to "error" => "bad_client_secret" - even though I can 100% confirm in my app that the Client Secret returned is indeed the same and correct Client Secret that Slack provides me. Is this the same thing you see in the ueberauth_example app logs on Heroku?

oauth2 0.6.0 breaks ueberauth_slack

When attempting to update to oauth2 version 0.6.0, the OAuth2 token validation step fails with the error:

Poison.EncodeError at GET /auth/slack/callback
unable to encode value: {:token, "XXXXXXXXXXXX"}

Downgrading to oauth2 0.5.0 does not exibit the issue.

Full stacktrace:

Request: GET /auth/slack/callback?code=9849826625.34528945029.32cfe35503&state=
** (exit) an exception was raised:
    ** (Poison.EncodeError) unable to encode value: {:token, "xoxp-XXXXXXX-XXXXXXXXX"}
        (poison) lib/poison/encoder.ex:339: Poison.Encoder.Any.encode/2
        (poison) lib/poison/encoder.ex:232: anonymous fn/3 in Poison.Encoder.List.encode/3
        (poison) lib/poison/encoder.ex:233: Poison.Encoder.List.encode/3
        (poison) lib/poison.ex:41: Poison.encode!/2
        (oauth2) lib/oauth2/request.ex:13: OAuth2.Request.request/5
        (oauth2) lib/oauth2/access_token.ex:221: OAuth2.AccessToken.request/6
        (ueberauth_slack) lib/ueberauth/strategy/slack.ex:167: Ueberauth.Strategy.Slack.fetch_auth/2
        (ueberauth_slack) lib/ueberauth/strategy/slack.ex:65: Ueberauth.Strategy.Slack.handle_callback!/1
        (ueberauth) lib/ueberauth/strategy.ex:299: Ueberauth.Strategy.run_callback/2
        (gatekeeper) web/controllers/authentication_controller.ex:1: Gatekeeper.AuthenticationController.phoenix_controller_pipeline/2
        (gatekeeper) lib/phoenix/router.ex:261: Gatekeeper.Router.dispatch/2
        (gatekeeper) web/router.ex:1: Gatekeeper.Router.do_call/2
        (gatekeeper) lib/gatekeeper/endpoint.ex:1: Gatekeeper.Endpoint.phoenix_pipeline/1
        (gatekeeper) lib/plug/debugger.ex:93: Gatekeeper.Endpoint."call (overridable 3)"/2
        (gatekeeper) lib/phoenix/endpoint/render_errors.ex:34: Gatekeeper.Endpoint.call/2
        (plug) lib/plug/adapters/cowboy/handler.ex:15: Plug.Adapters.Cowboy.Handler.upgrade/4
        (cowboy) src/cowboy_protocol.erl:442: :cowboy_protocol.execute/4

Support for JSON based API's Unknown

Not sure if this is the right place to pose this questions, but I'm a bit confused on the flow of this.

I'm currently trying to implement this library with Guardian 1.0 but running into some issues that I'm not 100% sure of and hoping to get some help.

Question 1
In the documentation it states you can start the request via a GET to /auth/slack. But I'm not sure how that fits with a JSON based API flow?

Question 2
I have a frontend app, built in React that has the "Sign In with Slack" button and that takes the user to Slacks auth page. I then set the redirect to hit /auth/slack as a GET and get the following:

[debug] Processing with IDIWeb.AuthController.callback/2
  Parameters: %{"code" => "XXXX", "provider" => "slack"}
  Pipelines: [:api]
[info] Sent 500 in 369ms
[error] #PID<0.923.0> running IDIWeb.Endpoint terminated
Server: localhost:4000 (http)
Request: GET /auth/slack/callback?code=XXXX
** (exit) an exception was raised:
    ** (ArgumentError) flash not fetched, call fetch_flash/2
        (phoenix) lib/phoenix/controller.ex:1228: Phoenix.Controller.get_flash/1
        (phoenix) lib/phoenix/controller.ex:1210: Phoenix.Controller.put_flash/3
        (ididit) lib/ididit_web/controllers/auth_controller.ex:14: IDIWeb.AuthController.callback/2
        (ididit) lib/ididit_web/controllers/auth_controller.ex:1: IDIWeb.AuthController.action/2
        (ididit) lib/ididit_web/controllers/auth_controller.ex:1: IDIWeb.AuthController.phoenix_controller_pipeline/2
        (ididit) lib/ididit_web/endpoint.ex:1: IDIWeb.Endpoint.instrument/4
        (phoenix) lib/phoenix/router.ex:278: Phoenix.Router.__call__/1
        (ididit) lib/ididit_web/endpoint.ex:1: IDIWeb.Endpoint.plug_builder_call/2
        (ididit) lib/plug/debugger.ex:99: IDIWeb.Endpoint."call (overridable 3)"/2
        (ididit) lib/ididit_web/endpoint.ex:1: IDIWeb.Endpoint.call/2
        (plug) lib/plug/adapters/cowboy/handler.ex:15: Plug.Adapters.Cowboy.Handler.upgrade/4
        (cowboy) /Users/alvincrespo/workspace/personal/ididit/ididit-backend/deps/cowboy/src/cowboy_protocol.erl:442: :cowboy_protocol.execute/4

Basically I'm expecting to return some JSON from this endpoint and my SPA (single page app) will do the redirect. Is this something I can do with the lib as is? Or would I need to fork and adjust to fit my use case?

Support for V2 Oauth API

Slack now allows apps to configure granular scopes for the bot token. This uses a new version of their oauth URLs and also changes the structure of the callback payload. More information here: https://api.slack.com/authentication/oauth-v2. If you upgrade to this version, it looks like you cannot go back to using the old version and you'll get a oauth_authorization_url_mismatch error.

To solve this (until the default oauth URLs in ueberauth_slack are changed):

  1. Override authorize_url and token_url in your config:
config :ueberauth, Ueberauth.Strategy.Slack.OAuth,
  client_id: System.get_env("SLACK_CLIENT_ID"),
  client_secret: System.get_env("SLACK_CLIENT_SECRET"),
  authorize_url: "https://slack.com/oauth/v2/authorize",
  token_url: "https://slack.com/api/oauth.v2.access"
  1. Change your callback function in AuthController to support the new payload structure. Compare the responses of https://api.slack.com/methods/oauth.access and https://api.slack.com/methods/oauth.v2.access to get an idea.

Recommend Projects

  • React photo React

    A declarative, efficient, and flexible JavaScript library for building user interfaces.

  • Vue.js photo Vue.js

    🖖 Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.

  • Typescript photo Typescript

    TypeScript is a superset of JavaScript that compiles to clean JavaScript output.

  • TensorFlow photo TensorFlow

    An Open Source Machine Learning Framework for Everyone

  • Django photo Django

    The Web framework for perfectionists with deadlines.

  • D3 photo D3

    Bring data to life with SVG, Canvas and HTML. 📊📈🎉

Recommend Topics

  • javascript

    JavaScript (JS) is a lightweight interpreted programming language with first-class functions.

  • web

    Some thing interesting about web. New door for the world.

  • server

    A server is a program made to process requests and deliver data to clients.

  • Machine learning

    Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.

  • Game

    Some thing interesting about game, make everyone happy.

Recommend Org

  • Facebook photo Facebook

    We are working to build community through open source technology. NB: members must have two-factor auth.

  • Microsoft photo Microsoft

    Open source projects and samples from Microsoft.

  • Google photo Google

    Google ❤️ Open Source for everyone.

  • D3 photo D3

    Data-Driven Documents codes.