Slack Authentication

Authentication

Slack uses OAuth 2.0 for authentication. Below you'll find a quick example on how to set up an authentication page using ASP.NET MVC and this package:

@using Skybrud.Social.Slack.OAuth
@using Skybrud.Social.Slack.Responses.Authentication
@using Skybrud.Social.Slack.Scopes
@{
    ViewBag.Title = "Slack: OAuth";
}

@{

    // Initialize and configure the OAuth client
    SlackOAuthClient client = new SlackOAuthClient {
        ClientId = "Your client ID here",
        ClientSecret = "Your client secret here",
        RedirectUri = "Your redirect URI here"
    };

    if (Request.QueryString["do"] == "login") {

        // Generate a random scope
        string state = Guid.NewGuid().ToString();

        // Generate the session key for the state
        string stateKey = "SlackOAuthState_" + state;

        // Store the state in the session of the user
        Session[stateKey] = Request.RawUrl;

        // Generate the authorization URL (and specify the required scope)
        string authorizationUrl = client.GetAuthorizationUrl(state, SlackScopes.Chat.WriteUser + SlackScopes.Chat.WriteBot);

        // Redirect the user
        Response.Redirect(authorizationUrl);

    } else if (Request.QueryString["code"] != null) {

        // Get the state from the query string
        string state = Request.QueryString["state"];

        // Get the code from the query string
        string code = Request.QueryString["code"];

        // Generate the session key for the state
        string stateKey = "SlackOAuthState_" + state;

        if (Session[stateKey] == null) {
            <p>Has your session expired?</p>
            <p>
                <a class="btn btn-default" href="@Url.Action("OAuth")?do=login">Re-try login</a>
            </p>
            return;
        }

        // Exchange the authorization code for an access token
        SlackTokenResponse response = client.GetAccessTokenFromAuthCode(code);

        <div>Access Token:</div>
        <pre>@response.Body.AccessToken</pre>

        <div>JSON:</div>
        <pre>@response.Body.JObject</pre>

        return;

    }

    <p>
        <a class="btn btn-default" href="@Url.Action("OAuth")?do=login">Login with Slack</a>
    </p>

}