Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Adds distribution OAuth2 flow #4

Merged
merged 1 commit into from
Sep 28, 2021
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
2 changes: 2 additions & 0 deletions Samples/HelloWorld/Program.cs
Original file line number Diff line number Diff line change
@@ -1,3 +1,4 @@
using System.Threading.Tasks;
using Slackbot.Net.Endpoints.Hosting;
using Slackbot.Net.Endpoints.Authentication;
using Slackbot.Net.Endpoints.Abstractions;
Expand Down Expand Up @@ -38,4 +39,5 @@ class TokenStore : ITokenStore
public Task<IEnumerable<string>> GetTokens() => Task.FromResult(new [] { SlackToken }.AsEnumerable());
public Task<string> GetTokenByTeamId(string teamId) => Task.FromResult(SlackToken);
public Task Delete(string token) => throw new NotImplementedException("Single workspace app");
public Task Insert(Workspace slackTeam) => throw new NotImplementedException("Single workspace app");
}
Original file line number Diff line number Diff line change
Expand Up @@ -11,5 +11,8 @@ public interface ITokenStore
Task<IEnumerable<string>> GetTokens();
Task<string> GetTokenByTeamId(string teamId);
Task Delete(string token);
Task Insert(Workspace slackTeam);
}
}

public record Workspace(string TeamId, string TeamName, string Scope, string Token);
}
13 changes: 13 additions & 0 deletions source/src/Slackbot.Net.Endpoints/Hosting/IAppBuilderExtensions.cs
Original file line number Diff line number Diff line change
Expand Up @@ -20,6 +20,19 @@ public static IApplicationBuilder UseSlackbot(this IApplicationBuilder app, bool

return app;
}

/// <summary>
/// NB! The path you run this middleware must:
/// - match redirect_uri in your 1st redirect to Slack
/// - be a valid redirect_uri in your Slack app configuration
/// </summary>
/// <param name="app"></param>
/// <returns></returns>
public static IApplicationBuilder UseSlackbotDistribution(this IApplicationBuilder app)
{
app.UseMiddleware<SlackbotCodeTokenExchangeMiddleware>();
return app;
}
}
}

Original file line number Diff line number Diff line change
@@ -1,6 +1,9 @@
using System;
using System.Threading.Tasks;
using Microsoft.Extensions.DependencyInjection;
using Slackbot.Net.Abstractions.Hosting;
using Slackbot.Net.Endpoints.Abstractions;
using Slackbot.Net.Endpoints.OAuth;

namespace Slackbot.Net.Endpoints.Hosting
{
Expand All @@ -12,5 +15,28 @@ public static ISlackbotHandlersBuilder AddSlackBotEvents<T>(this IServiceCollect
services.AddSingleton<ISelectAppMentionEventHandlers, AppMentionEventHandlerSelector>();
return new SlackBotHandlersBuilder(services);
}

public static IServiceCollection AddSlackbotDistribution(this IServiceCollection services, Action<OAuthOptions> action)
{
services.Configure<OAuthOptions>(action);
services.AddHttpClient<OAuthClient>((s, c) =>
{
c.BaseAddress = new Uri("https://slack.com/api/");
c.Timeout = TimeSpan.FromSeconds(15);
});
return services;
}
}

public class OAuthOptions
{
public OAuthOptions()
{
OnSuccess = (_,_,_) => Task.CompletedTask;
}
public string CLIENT_ID { get; set; }
public string CLIENT_SECRET { get; set; }
public string SuccessRedirectUri { get; set; } = "/success?default=1";
public Func<string, string, IServiceProvider, Task> OnSuccess { get; set; }
}
}
}
Original file line number Diff line number Diff line change
@@ -0,0 +1,60 @@
using System;
using System.Linq;
using System.Threading.Tasks;
using Microsoft.AspNetCore.Http;
using Microsoft.Extensions.Logging;
using Microsoft.Extensions.Options;
using Slackbot.Net.Abstractions.Hosting;
using Slackbot.Net.Endpoints.Hosting;
using Slackbot.Net.Endpoints.OAuth;

namespace Slackbot.Net.Endpoints.Middlewares
{
internal class SlackbotCodeTokenExchangeMiddleware
{
private readonly RequestDelegate _next;

public SlackbotCodeTokenExchangeMiddleware(RequestDelegate next)
{
_next = next;
}

public async Task Invoke(HttpContext ctx, OAuthClient oAuthAccessClient, IServiceProvider provider, IOptions<OAuthOptions> options, ITokenStore slackTeamRepository, ILogger<SlackbotCodeTokenExchangeMiddleware> logger)
{
logger.LogInformation("Installing!");
var redirect_uri = new Uri($"{ctx.Request.Scheme}://{ctx.Request.Host.Value.ToString()}{ctx.Request.PathBase.Value}");
var code = ctx.Request.Query["code"].FirstOrDefault();

if(code == null)
await _next(ctx);

var response = await oAuthAccessClient.OAuthAccessV2(new OAuthClient.OauthAccessV2Request(
code,
options.Value.CLIENT_ID,
options.Value.CLIENT_SECRET,
redirect_uri.ToString()
));

if (response.Ok)
{
logger.LogInformation($"Oauth response! ok:{response.Ok}");
await slackTeamRepository.Insert(new Workspace
(
response.Team.Id,
response.Team.Name,
response.Scope,
response.Access_Token
));
await options.Value.OnSuccess(response.Team.Id, response.Team.Name, provider);

ctx.Response.Redirect(options.Value.SuccessRedirectUri);
}
else
{
logger.LogError($"Bad Oauth response! {response}");
ctx.Response.StatusCode = StatusCodes.Status500InternalServerError;
await ctx.Response.WriteAsync(response.Error);
}
}
}
}
106 changes: 106 additions & 0 deletions source/src/Slackbot.Net.Endpoints/OAuth/OAuthClient.cs
Original file line number Diff line number Diff line change
@@ -0,0 +1,106 @@
using System;
using System.Collections.Generic;
using System.Linq;
using System.Net.Http;
using System.Text;
using System.Text.Json;
using System.Text.Json.Serialization;
using System.Threading.Tasks;
using Microsoft.Extensions.Logging;

namespace Slackbot.Net.Endpoints.OAuth
{
internal record Response(bool Ok, string Error);

internal class OAuthClient
{
private readonly HttpClient _client;
private readonly ILogger<OAuthClient> _logger;

internal record OauthAccessV2Request(string Code, string ClientId, string ClientSecret, string RedirectUri);

internal record OAuthAccessV2Response(string Access_Token, string Scope, Team Team, string App_Id, OAuthUser Authed_User, bool Ok, string Error) : Response(Ok, Error);
internal record Team(string Id, string Name);
internal record OAuthUser(string User_Id, string App_Home);


public OAuthClient(HttpClient client, ILogger<OAuthClient> logger)
{
_client = client;
_logger = logger;
}

public async Task<OAuthAccessV2Response> OAuthAccessV2(OauthAccessV2Request oauthAccessRequest)
{
var parameters = new List<KeyValuePair<string, string>>
{
new("code", oauthAccessRequest.Code)
};

if (!string.IsNullOrEmpty(oauthAccessRequest.RedirectUri))
{
parameters.Add(new KeyValuePair<string, string>("redirect_uri", oauthAccessRequest.RedirectUri));
}

if (!string.IsNullOrEmpty(oauthAccessRequest.ClientId))
{
parameters.Add(new KeyValuePair<string, string>("client_id", oauthAccessRequest.ClientId));
}

if (!string.IsNullOrEmpty(oauthAccessRequest.ClientSecret))
{
parameters.Add(new KeyValuePair<string, string>("client_secret", oauthAccessRequest.ClientSecret));
}

return await _client.PostParametersAsForm<OAuthAccessV2Response>(parameters,"oauth.v2.access", s => _logger.LogInformation(s));
}
}

internal static class HttpClientExtensions
{
internal static async Task<T> PostParametersAsForm<T>(this HttpClient httpClient, IEnumerable<KeyValuePair<string, string>> parameters, string api, Action<string> logger = null) where T: Response
{
var request = new HttpRequestMessage(HttpMethod.Post, api);

if (parameters != null && parameters.Any())
{
var formUrlEncodedContent = new FormUrlEncodedContent(parameters);
var requestContent = await formUrlEncodedContent.ReadAsStringAsync();
var httpContent = new StringContent(requestContent, Encoding.UTF8, "application/x-www-form-urlencoded");
httpContent.Headers.ContentType.CharSet = string.Empty;
request.Content = httpContent;
}

var response = await httpClient.SendAsync(request);
var responseContent = await response.Content.ReadAsStringAsync();

if (!response.IsSuccessStatusCode)
{
logger?.Invoke($"{response.StatusCode} \n {responseContent}");
}

response.EnsureSuccessStatusCode();

var resObj = JsonSerializer.Deserialize<T>(responseContent, new JsonSerializerOptions(JsonSerializerDefaults.Web));

if(!resObj.Ok)
throw new SlackApiException(error: $"{resObj.Error}", responseContent:responseContent);

return resObj;
}
}

internal class SlackApiException : Exception
{
public string Error { get; }
public string ResponseContent { get; }

public SlackApiException(string error, string responseContent): base(responseContent)
{
Error = error;
ResponseContent = responseContent;
}
}


}
Original file line number Diff line number Diff line change
@@ -1,7 +1,7 @@
<Project Sdk="Microsoft.NET.Sdk">

<PropertyGroup>
<TargetFrameworks>netcoreapp3.1;net5.0;net6.0</TargetFrameworks>
<TargetFrameworks>net5.0;net6.0</TargetFrameworks>
<RootNamespace>Slackbot.Net.Endpoints</RootNamespace>
<PackageId>Slackbot.Net.Endpoints</PackageId>
<Authors>John Korsnes</Authors>
Expand Down
2 changes: 1 addition & 1 deletion source/src/Slackbot.Net.Shared/Slackbot.Net.Shared.csproj
Original file line number Diff line number Diff line change
@@ -1,7 +1,7 @@
<Project Sdk="Microsoft.NET.Sdk">

<PropertyGroup>
<TargetFrameworks>netcoreapp3.1;net5.0</TargetFrameworks>
<TargetFrameworks>net5.0;net6.0</TargetFrameworks>
</PropertyGroup>

</Project>
Original file line number Diff line number Diff line change
@@ -1,7 +1,7 @@
<Project Sdk="Microsoft.NET.Sdk">

<PropertyGroup>
<TargetFrameworks>netcoreapp3.1;net5.0;net6.0</TargetFrameworks>
<TargetFrameworks>net5.0;net6.0</TargetFrameworks>
<RootNamespace>Slackbot.Net.SlackClients.Http</RootNamespace>
<PackageId>Slackbot.Net.SlackClients.Http</PackageId>
<Authors>John Korsnes</Authors>
Expand Down