Skip to content

Instantly share code, notes, and snippets.

@fideloper
Last active February 17, 2017 22:57
Show Gist options
  • Star 6 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save fideloper/20dc871d98abe7c9b4cb to your computer and use it in GitHub Desktop.
Save fideloper/20dc871d98abe7c9b4cb to your computer and use it in GitHub Desktop.
Slack oAuth2.0 Round Trip
<?php
namespace App\Http\Controllers\Auth;
use Illuminate\Http\Request;
use App\Http\Requests;
use App\Http\Controllers\Controller;
use GuzzleHttp\Client;
class SlackOAuthController extends Controller
{
const SLACK_AUTH_URL = 'https://slack.com/oauth/authorize?client_id=%s&scope=%s&redirect_uri=%s';
const SLACK_ACCESS_URL = 'https://slack.com/api/oauth.access';
/**
* SlackOAuthController constructor.
* @param Client $http
*/
public function __construct(Client $http)
{
$this->http = $http;
}
/**
* Redirect to Slack authentication route
* @route /slack/auth
* @link https://api.slack.com/docs/oauth
* @return \Illuminate\Http\RedirectResponse|\Illuminate\Routing\Redirector
*/
public function auth()
{
return redirect( $this->authUrl() );
}
/**
* Retrieve authentication token and
* exchange for authorization token
* @route /slack/token
* @link https://api.slack.com/methods/oauth.access
* @param Request $request
* @return \Illuminate\Http\RedirectResponse|\Illuminate\Routing\Redirector
*/
public function access(Request $request)
{
$response = $this->http->post(static::SLACK_ACCESS_URL, [
'form_params' => [
'client_id' => env('SLACK_CLIENT'),
'client_secret' => env('SLACK_SECRET'),
'code' => $request->input('code'),
'redirect_uri' => env('SLACK_REDIRECT'),
]
]);
/**
* JSON response:
* ok: true,
* access_token: "xoxp-xxxxxxxxxx-xxxxxxxxxx-xxxxxxxxxx-xxxxxxxxxx",
* scope: "identify,chat:write:bot,files:write:user",
* team_name: "SomeTeam",
* team_id: "T01234567"
*/
$parsedResponse = json_decode($response->getBody());
// Save to database, perhaps encrypt that access token
return redirect('/dashboard');
}
/**
* Build slack authentication URL
* @link https://api.slack.com/docs/oauth-scopes
* @return string
*/
protected function authUrl()
{
return sprintf(static::SLACK_AUTH_URL,
env('SLACK_CLIENT'),
env('SLACK_SCOPES'), // e.g. identify,chat:write:bot,files:write:user
env('SLACK_REDIRECT') // e.g. https://example.com/slack/token
);
}
}
@fideloper
Copy link
Author

Send users to the /slack/auth route to kick off the round-trip.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment