This post is about implementing authentication with Slack. Similar to Linkedin or GitHub, Slack also supports OAuth 2 protocol for authentication. In this post, for authenticating a user against slack, the generic OAuth middleware is used. To use OAuth middleware you require few details about the OAuth provider.
A Client ID and Client Secret which is typically available from service’s Developer Portal or similar service.
The URL for the service’s OAuth2 Authorization endpoint.
The URL for the service’s OAuth2 Token endpoint.
Optionally a URL which will allow you to retrieve the user information for the authenticated user from the service.
For slack you can get the Client Id and Client Secret from the apps page. If you haven’t created an app you need to create it first. The return uri in this configuration and in our code should be same, otherwise slack authentication will not work.
User Information Endpoint - https://slack.com/api/users.identity - with token as the query string.
Instead of hard coding the Client Id and Client Secret in the code, it is better to read from configuration file. So you can create appsettings.json file and read the values using configuraion. Here is the appsettings.json file.
To use generic oauth middleware first you need to configure project.json file with the required references.
Now you need to run the “dotnet restore” command to restore the packages. Once the packages restored successfully, you can modify the startup file to implement authentication. Here is the ConfigureServices, which will register the authentication services.
And in the Configure method you need to register the Cookie and OAuth middlewares. Here is the Configure method.
The events property of OAuth middleware is used to create claims, using you can get username / id from the User profile. Unlike other OAuth providers Slack requires the Token to be passed a query string with Token as parameter. So if you look at the code, I am using query string token in the UserInformationEndpoint. You can create Login and Logout methods like this.
As I don’t have any other login mechanisms in place, I am not using a Account controller or Login view. The login url will issue a challenge to log in with Slack. And logout will Signout the user and redirect to the home page. And the view you can add following code snippet for logging in and logout if not authenticated.
Here is the screenshots of the Slack authentication in ASP.NET Core.
When user click on login link, which will invoke the login method mapped in Startup.cs
Once user’s team selection completed, the authentication dialog will be presented with username and password fields.
And finally once authentication is completed, it will redirect to the application, and with the Razor view code, it will display user’s name and logout button like this.
You can use the similar steps for Linkedin and Github as well.