Add Slack provider

This commit is contained in:
mjknowles
2015-05-29 22:55:31 -05:00
parent 9f9b3e94aa
commit d0783c35c1
11 changed files with 691 additions and 6 deletions

View File

@@ -238,6 +238,15 @@
<Compile Include="Salesforce\SalesforceAuthenticationHandler.cs" />
<Compile Include="Salesforce\SalesforceAuthenticationMiddleware.cs" />
<Compile Include="Salesforce\SalesforceAuthenticationOptions.cs" />
<Compile Include="Slack\Constants.cs" />
<Compile Include="Slack\Provider\ISlackAuthenticationProvider.cs" />
<Compile Include="Slack\Provider\SlackAuthenticatedContext.cs" />
<Compile Include="Slack\Provider\SlackAuthenticationProvider.cs" />
<Compile Include="Slack\Provider\SlackReturnEndpointContext.cs" />
<Compile Include="Slack\SlackAuthenticationExtensions.cs" />
<Compile Include="Slack\SlackAuthenticationHandler.cs" />
<Compile Include="Slack\SlackAuthenticationMiddleware.cs" />
<Compile Include="Slack\SlackAuthenticationOptions.cs" />
<Compile Include="SoundCloud\Constants.cs" />
<Compile Include="SoundCloud\Provider\ISoundCloudAuthenticationProvider.cs" />
<Compile Include="SoundCloud\Provider\SoundCloudAuthenticatedContext.cs" />

View File

@@ -0,0 +1,7 @@
namespace Owin.Security.Providers.Slack
{
internal static class Constants
{
public const string DefaultAuthenticationType = "Slack";
}
}

View File

@@ -0,0 +1,21 @@
using System.Threading.Tasks;
namespace Owin.Security.Providers.Slack.Provider
{
public interface ISlackAuthenticationProvider
{
/// <summary>
/// Invoked whenever Slack succesfully authenticates a user
/// </summary>
/// <param name="context">Contains information about the login session as well as the user <see cref="System.Security.Claims.ClaimsIdentity"/>.</param>
/// <returns>A <see cref="Task"/> representing the completed operation.</returns>
Task Authenticated(SlackAuthenticatedContext context);
/// <summary>
/// Invoked prior to the <see cref="System.Security.Claims.ClaimsIdentity"/> being saved in a local cookie and the browser being redirected to the originally requested URL.
/// </summary>
/// <param name="context"></param>
/// <returns>A <see cref="Task"/> representing the completed operation.</returns>
Task ReturnEndpoint(SlackReturnEndpointContext context);
}
}

View File

@@ -0,0 +1,92 @@
using Microsoft.Owin;
using Microsoft.Owin.Security;
using Microsoft.Owin.Security.Provider;
using Newtonsoft.Json.Linq;
using System.Collections.Generic;
using System.Security.Claims;
namespace Owin.Security.Providers.Slack.Provider
{
public class SlackAuthenticatedContext : BaseContext
{
/// <summary>
/// Initializes a <see cref="SlackAuthenticatedContext"/>
/// </summary>
/// <param name="context">The OWIN environment</param>
/// <param name="user">The JSON-serialized user</param>
/// <param name="accessToken">Slack Access token</param>
/// <param name="scope">Indicates access level of application</param>
public SlackAuthenticatedContext(IOwinContext context, JObject user, string accessToken, string scope)
: base(context)
{
User = user;
AccessToken = accessToken;
Scope = scope.Split(',');
UserId = TryGetValue(user, "user_id");
UserName = TryGetValue(user, "user");
TeamId = TryGetValue(user, "team_id");
TeamName = TryGetValue(user, "team");
TeamUrl = TryGetValue(user, "url");
}
/// <summary>
/// Gets the JSON-serialized user
/// </summary>
/// <remarks>
/// Contains the Slack user
/// </remarks>
public JObject User { get; private set; }
/// <summary>
/// Gets the Slack access token
/// </summary>
public string AccessToken { get; private set; }
/// <summary>
/// Gets the scope of the application's access to user info
/// </summary>
public IList<string> Scope { get; private set; }
/// <summary>
/// Gets the Slack team ID
/// </summary>
public string TeamId { get; private set; }
/// <summary>
/// Gets the Slack team name
/// </summary>
public string TeamName { get; private set; }
/// <summary>
/// Gets the Slack user's team URL
/// </summary>
public string TeamUrl { get; private set; }
/// <summary>
/// Gets the Slack user ID
/// </summary>
public string UserId { get; private set; }
/// <summary>
/// Gets the Slack username
/// </summary>
public string UserName { get; private set; }
/// <summary>
/// Gets the <see cref="ClaimsIdentity"/> representing the user
/// </summary>
public ClaimsIdentity Identity { get; set; }
/// <summary>
/// Gets or sets a property bag for common authentication properties
/// </summary>
public AuthenticationProperties Properties { get; set; }
private static string TryGetValue(JObject user, string propertyName)
{
JToken value;
return user.TryGetValue(propertyName, out value) ? value.ToString() : null;
}
}
}

View File

@@ -0,0 +1,47 @@
using System;
using System.Threading.Tasks;
namespace Owin.Security.Providers.Slack.Provider
{
public class SlackAuthenticationProvider : ISlackAuthenticationProvider
{
/// <summary>
/// Initializes a <see cref="SlackAuthenticationProvider"/>
/// </summary>
public SlackAuthenticationProvider()
{
OnAuthenticated = context => Task.FromResult<object>(null);
OnReturnEndpoint = context => Task.FromResult<object>(null);
}
/// <summary>
/// Gets or sets the function that is invoked when the Authenticated method is invoked.
/// </summary>
public Func<SlackAuthenticatedContext, Task> OnAuthenticated { get; set; }
/// <summary>
/// Gets or sets the function that is invoked when the ReturnEndpoint method is invoked.
/// </summary>
public Func<SlackReturnEndpointContext, Task> OnReturnEndpoint { get; set; }
/// <summary>
/// Invoked whenever Slack succesfully authenticates a user
/// </summary>
/// <param name="context">Contains information about the login session as well as the user <see cref="System.Security.Claims.ClaimsIdentity"/>.</param>
/// <returns>A <see cref="Task"/> representing the completed operation.</returns>
public virtual Task Authenticated(SlackAuthenticatedContext context)
{
return OnAuthenticated(context);
}
/// <summary>
/// Invoked prior to the <see cref="System.Security.Claims.ClaimsIdentity"/> being saved in a local cookie and the browser being redirected to the originally requested URL.
/// </summary>
/// <param name="context"></param>
/// <returns>A <see cref="Task"/> representing the completed operation.</returns>
public virtual Task ReturnEndpoint(SlackReturnEndpointContext context)
{
return OnReturnEndpoint(context);
}
}
}

View File

@@ -0,0 +1,21 @@
using Microsoft.Owin;
using Microsoft.Owin.Security;
using Microsoft.Owin.Security.Provider;
namespace Owin.Security.Providers.Slack.Provider
{
public class SlackReturnEndpointContext : ReturnEndpointContext
{
/// <summary>
///
/// </summary>
/// <param name="context">OWIN environment</param>
/// <param name="ticket">The authentication ticket</param>
public SlackReturnEndpointContext(
IOwinContext context,
AuthenticationTicket ticket)
: base(context, ticket)
{
}
}
}

View File

@@ -0,0 +1,28 @@
using System;
namespace Owin.Security.Providers.Slack
{
public static class SlackAuthenticationExtensions
{
public static IAppBuilder UseSlackAuthentication(this IAppBuilder app, SlackAuthenticationOptions options)
{
if (app == null)
throw new ArgumentNullException("app");
if (options == null)
throw new ArgumentNullException("options");
app.Use(typeof(SlackAuthenticationMiddleware), app, options);
return app;
}
public static IAppBuilder UseSlackAuthentication(this IAppBuilder app, string clientId, string clientSecret)
{
return app.UseSlackAuthentication(new SlackAuthenticationOptions
{
ClientId = clientId,
ClientSecret = clientSecret,
});
}
}
}

View File

@@ -0,0 +1,252 @@
using Microsoft.Owin;
using Microsoft.Owin.Infrastructure;
using Microsoft.Owin.Logging;
using Microsoft.Owin.Security;
using Microsoft.Owin.Security.Infrastructure;
using Newtonsoft.Json;
using Newtonsoft.Json.Linq;
using Owin.Security.Providers.Slack.Provider;
using System;
using System.Collections.Generic;
using System.Net.Http;
using System.Net.Http.Headers;
using System.Security.Claims;
using System.Text;
using System.Threading.Tasks;
namespace Owin.Security.Providers.Slack
{
public class SlackAuthenticationHandler : AuthenticationHandler<SlackAuthenticationOptions>
{
private const string XmlSchemaString = "http://www.w3.org/2001/XMLSchema#string";
private const string TokenEndpoint = "https://slack.com/api/oauth.access";
private const string UserInfoEndpoint = "https://slack.com/api/auth.test";
private readonly ILogger logger;
private readonly HttpClient httpClient;
public SlackAuthenticationHandler(HttpClient httpClient, ILogger logger)
{
this.httpClient = httpClient;
this.logger = logger;
}
protected override async Task<AuthenticationTicket> AuthenticateCoreAsync()
{
AuthenticationProperties properties = null;
try
{
string code = null;
string state = null;
IReadableStringCollection query = Request.Query;
IList<string> values = query.GetValues("code");
if (values != null && values.Count == 1)
{
code = values[0];
}
values = query.GetValues("state");
if (values != null && values.Count == 1)
{
state = values[0];
}
properties = Options.StateDataFormat.Unprotect(state);
if (properties == null)
{
return null;
}
// OAuth2 10.12 CSRF
if (!ValidateCorrelationId(properties, logger))
{
return new AuthenticationTicket(null, properties);
}
// Check for error
if (Request.Query.Get("error") != null)
return new AuthenticationTicket(null, properties);
string requestPrefix = Request.Scheme + "://" + Request.Host;
string redirectUri = requestPrefix + Request.PathBase + Options.CallbackPath;
// Build up the body for the token request
var body = new List<KeyValuePair<string, string>>();
body.Add(new KeyValuePair<string, string>("client_id", Options.ClientId));
body.Add(new KeyValuePair<string, string>("client_secret", Options.ClientSecret));
body.Add(new KeyValuePair<string, string>("code", code));
body.Add(new KeyValuePair<string, string>("redirect_uri", redirectUri));
string secret = Options.ClientId + ":" + Options.ClientSecret;
var secretBase64 = Convert.ToBase64String(Encoding.UTF8.GetBytes(secret));
HttpRequestMessage tokenRequest = new HttpRequestMessage(HttpMethod.Post, TokenEndpoint);
tokenRequest.Headers.Authorization = new AuthenticationHeaderValue("Basic", secretBase64);
tokenRequest.Content = new FormUrlEncodedContent(body);
// Request the token
HttpResponseMessage tokenResponse = await httpClient.SendAsync(tokenRequest);
tokenResponse.EnsureSuccessStatusCode();
string text = await tokenResponse.Content.ReadAsStringAsync();
// Deserializes the token response
dynamic response = JsonConvert.DeserializeObject<dynamic>(text);
string accessToken = (string)response.access_token;
string scope = (string)response.scope;
// Get the Slack user
HttpRequestMessage userRequest = new HttpRequestMessage(HttpMethod.Get, UserInfoEndpoint + "?token=" + Uri.EscapeDataString(accessToken));
HttpResponseMessage userResponse = await httpClient.SendAsync(userRequest, Request.CallCancelled);
userResponse.EnsureSuccessStatusCode();
text = await userResponse.Content.ReadAsStringAsync();
JObject user = JObject.Parse(text);
var context = new SlackAuthenticatedContext(Context, user, accessToken, scope);
context.Identity = new ClaimsIdentity(
Options.AuthenticationType,
ClaimsIdentity.DefaultNameClaimType,
ClaimsIdentity.DefaultRoleClaimType);
if (!string.IsNullOrEmpty(context.UserId))
{
context.Identity.AddClaim(new Claim(ClaimTypes.NameIdentifier, context.UserId, XmlSchemaString, Options.AuthenticationType));
}
if (!string.IsNullOrEmpty(context.UserName))
{
context.Identity.AddClaim(new Claim(ClaimsIdentity.DefaultNameClaimType, context.UserName, XmlSchemaString, Options.AuthenticationType));
}
if (!string.IsNullOrEmpty(context.TeamId))
{
context.Identity.AddClaim(new Claim("urn:slack:teamid", context.TeamId, XmlSchemaString, Options.AuthenticationType));
}
if (!string.IsNullOrEmpty(context.TeamName))
{
context.Identity.AddClaim(new Claim("urn:slack:teamname", context.TeamName, XmlSchemaString, Options.AuthenticationType));
}
if (!string.IsNullOrEmpty(context.TeamUrl))
{
context.Identity.AddClaim(new Claim(ClaimTypes.Webpage, context.TeamUrl, XmlSchemaString, Options.AuthenticationType));
}
context.Properties = properties;
await Options.Provider.Authenticated(context);
return new AuthenticationTicket(context.Identity, context.Properties);
}
catch (Exception ex)
{
logger.WriteError(ex.Message);
}
return new AuthenticationTicket(null, properties);
}
protected override Task ApplyResponseChallengeAsync()
{
if (Response.StatusCode != 401)
{
return Task.FromResult<object>(null);
}
AuthenticationResponseChallenge challenge = Helper.LookupChallenge(Options.AuthenticationType, Options.AuthenticationMode);
if (challenge != null)
{
string baseUri =
Request.Scheme +
Uri.SchemeDelimiter +
Request.Host +
Request.PathBase;
string currentUri =
baseUri +
Request.Path +
Request.QueryString;
string redirectUri =
baseUri +
Options.CallbackPath;
AuthenticationProperties properties = challenge.Properties;
if (string.IsNullOrEmpty(properties.RedirectUri))
{
properties.RedirectUri = currentUri;
}
// OAuth2 10.12 CSRF
GenerateCorrelationId(properties);
// comma separated
string scope = string.Join(",", Options.Scope);
string state = Options.StateDataFormat.Protect(properties);
string authorizationEndpoint =
"https://slack.com/oauth/authorize" +
"?response_type=code" +
"&client_id=" + Uri.EscapeDataString(Options.ClientId) +
"&redirect_uri=" + Uri.EscapeDataString(redirectUri) +
"&scope=" + Uri.EscapeDataString(scope) +
"&state=" + Uri.EscapeDataString(state) +
"&team=" + Uri.EscapeDataString(Options.TeamId);
Response.Redirect(authorizationEndpoint);
}
return Task.FromResult<object>(null);
}
public override async Task<bool> InvokeAsync()
{
return await InvokeReplyPathAsync();
}
private async Task<bool> InvokeReplyPathAsync()
{
if (Options.CallbackPath.HasValue && Options.CallbackPath == Request.Path)
{
// TODO: error responses
AuthenticationTicket ticket = await AuthenticateAsync();
if (ticket == null)
{
logger.WriteWarning("Invalid return state, unable to redirect.");
Response.StatusCode = 500;
return true;
}
var context = new SlackReturnEndpointContext(Context, ticket);
context.SignInAsAuthenticationType = Options.SignInAsAuthenticationType;
context.RedirectUri = ticket.Properties.RedirectUri;
await Options.Provider.ReturnEndpoint(context);
if (context.SignInAsAuthenticationType != null &&
context.Identity != null)
{
ClaimsIdentity grantIdentity = context.Identity;
if (!string.Equals(grantIdentity.AuthenticationType, context.SignInAsAuthenticationType, StringComparison.Ordinal))
{
grantIdentity = new ClaimsIdentity(grantIdentity.Claims, context.SignInAsAuthenticationType, grantIdentity.NameClaimType, grantIdentity.RoleClaimType);
}
Context.Authentication.SignIn(context.Properties, grantIdentity);
}
if (!context.IsRequestCompleted && context.RedirectUri != null)
{
string redirectUri = context.RedirectUri;
if (context.Identity == null)
{
// add a redirect hint that sign-in failed in some way
redirectUri = WebUtilities.AddQueryString(redirectUri, "error", "access_denied");
}
Response.Redirect(redirectUri);
context.RequestCompleted();
}
return context.IsRequestCompleted;
}
return false;
}
}
}

View File

@@ -0,0 +1,89 @@
using Microsoft.Owin;
using Microsoft.Owin.Logging;
using Microsoft.Owin.Security;
using Microsoft.Owin.Security.DataHandler;
using Microsoft.Owin.Security.DataProtection;
using Microsoft.Owin.Security.Infrastructure;
using Owin.Security.Providers.Properties;
using Owin.Security.Providers.Slack.Provider;
using System;
using System.Globalization;
using System.Net.Http;
namespace Owin.Security.Providers.Slack
{
public class SlackAuthenticationMiddleware : AuthenticationMiddleware<SlackAuthenticationOptions>
{
private readonly HttpClient httpClient;
private readonly ILogger logger;
public SlackAuthenticationMiddleware(OwinMiddleware next, IAppBuilder app,
SlackAuthenticationOptions options)
: base(next, options)
{
if (String.IsNullOrWhiteSpace(Options.ClientId))
throw new ArgumentException(String.Format(CultureInfo.CurrentCulture,
"Option must be provided {0}", "ClientId"));
if (String.IsNullOrWhiteSpace(Options.ClientSecret))
throw new ArgumentException(String.Format(CultureInfo.CurrentCulture,
"Option must be provided {0}", "ClientSecret"));
logger = app.CreateLogger<SlackAuthenticationMiddleware>();
if (Options.Provider == null)
Options.Provider = new SlackAuthenticationProvider();
if (Options.StateDataFormat == null)
{
IDataProtector dataProtector = app.CreateDataProtector(
typeof(SlackAuthenticationMiddleware).FullName,
Options.AuthenticationType, "v1");
Options.StateDataFormat = new PropertiesDataFormat(dataProtector);
}
if (String.IsNullOrEmpty(Options.SignInAsAuthenticationType))
Options.SignInAsAuthenticationType = app.GetDefaultSignInAsAuthenticationType();
httpClient = new HttpClient(ResolveHttpMessageHandler(Options))
{
Timeout = Options.BackchannelTimeout,
MaxResponseContentBufferSize = 1024 * 1024 * 10
};
httpClient.DefaultRequestHeaders.UserAgent.ParseAdd("Microsoft Owin Slack middleware");
httpClient.DefaultRequestHeaders.ExpectContinue = false;
}
/// <summary>
/// Provides the <see cref="T:Microsoft.Owin.Security.Infrastructure.AuthenticationHandler" /> object for processing
/// authentication-related requests.
/// </summary>
/// <returns>
/// An <see cref="T:Microsoft.Owin.Security.Infrastructure.AuthenticationHandler" /> configured with the
/// <see cref="T:SlackAuthenticationOptions" /> supplied to the constructor.
/// </returns>
protected override AuthenticationHandler<SlackAuthenticationOptions> CreateHandler()
{
return new SlackAuthenticationHandler(httpClient, logger);
}
private HttpMessageHandler ResolveHttpMessageHandler(SlackAuthenticationOptions options)
{
HttpMessageHandler handler = options.BackchannelHttpHandler ?? new WebRequestHandler();
// If they provided a validator, apply it or fail.
if (options.BackchannelCertificateValidator != null)
{
// Set the cert validate callback
var webRequestHandler = handler as WebRequestHandler;
if (webRequestHandler == null)
{
throw new InvalidOperationException(Resources.Exception_ValidatorHandlerMismatch);
}
webRequestHandler.ServerCertificateValidationCallback = options.BackchannelCertificateValidator.Validate;
}
return handler;
}
}
}

View File

@@ -0,0 +1,107 @@
using Microsoft.Owin;
using Microsoft.Owin.Security;
using Owin.Security.Providers.Slack.Provider;
using System;
using System.Collections.Generic;
using System.Net.Http;
namespace Owin.Security.Providers.Slack
{
public class SlackAuthenticationOptions : AuthenticationOptions
{
/// <summary>
/// Gets or sets the a pinned certificate validator to use to validate the endpoints used
/// in back channel communications belong to Slack.
/// </summary>
/// <value>
/// The pinned certificate validator.
/// </value>
/// <remarks>
/// If this property is null then the default certificate checks are performed,
/// validating the subject name and if the signing chain is a trusted party.
/// </remarks>
public ICertificateValidator BackchannelCertificateValidator { get; set; }
/// <summary>
/// The HttpMessageHandler used to communicate with Slack.
/// This cannot be set at the same time as BackchannelCertificateValidator unless the value
/// can be downcast to a WebRequestHandler.
/// </summary>
public HttpMessageHandler BackchannelHttpHandler { get; set; }
/// <summary>
/// Gets or sets timeout value in milliseconds for back channel communications with Slack.
/// </summary>
/// <value>
/// The back channel timeout in milliseconds.
/// </value>
public TimeSpan BackchannelTimeout { get; set; }
/// <summary>
/// The request path within the application's base path where the user-agent will be returned.
/// The middleware will process this request when it arrives.
/// Default value is "/signin-slack".
/// </summary>
public PathString CallbackPath { get; set; }
/// <summary>
/// Get or sets the text that the user can display on a sign in user interface.
/// </summary>
public string Caption
{
get { return Description.Caption; }
set { Description.Caption = value; }
}
/// <summary>
/// Gets or sets the Slack supplied Client ID
/// </summary>
public string ClientId { get; set; }
/// <summary>
/// Gets or sets the Slack supplied Client Secret
/// </summary>
public string ClientSecret { get; set; }
/// <summary>
/// Gets or sets the <see cref="ISlackAuthenticationProvider" /> used in the authentication events
/// </summary>
public ISlackAuthenticationProvider Provider { get; set; }
/// <summary>
/// Determines the permissions granted from the application to Slack.
/// Options include: identify, read, post, client, and/or admin
/// </summary>
public IList<string> Scope { get; set; }
/// <summary>
/// Gets or sets the name of another authentication middleware which will be responsible for actually issuing a user
/// <see cref="System.Security.Claims.ClaimsIdentity" />.
/// </summary>
public string SignInAsAuthenticationType { get; set; }
/// <summary>
/// Gets or sets the type used to secure data handled by the middleware.
/// </summary>
public ISecureDataFormat<AuthenticationProperties> StateDataFormat { get; set; }
/// <summary>
/// Gets or sets the Slack team ID to restrict to. Not required by Slack API.
/// </summary>
public string TeamId { get; set; }
/// <summary>
/// Initializes a new <see cref="SlackAuthenticationOptions" />
/// </summary>
public SlackAuthenticationOptions()
: base("Slack")
{
Caption = Constants.DefaultAuthenticationType;
CallbackPath = new PathString("/signin-slack");
AuthenticationMode = AuthenticationMode.Passive;
Scope = new List<string>();
BackchannelTimeout = TimeSpan.FromSeconds(60);
TeamId = "";
}
}
}

View File

@@ -19,18 +19,21 @@ using Owin.Security.Providers.GooglePlus.Provider;
using Owin.Security.Providers.HealthGraph;
using Owin.Security.Providers.Instagram;
using Owin.Security.Providers.LinkedIn;
using Owin.Security.Providers.OpenID;
using Owin.Security.Providers.PayPal;
using Owin.Security.Providers.Reddit;
using Owin.Security.Providers.Salesforce;
using Owin.Security.Providers.StackExchange;
using Owin.Security.Providers.TripIt;
using Owin.Security.Providers.Twitch;
using Owin.Security.Providers.Yahoo;
using Owin.Security.Providers.OpenID;
using Owin.Security.Providers.Slack;
using Owin.Security.Providers.SoundCloud;
using Owin.Security.Providers.Spotify;
using Owin.Security.Providers.StackExchange;
using Owin.Security.Providers.Steam;
using Owin.Security.Providers.Wargaming;using Owin.Security.Providers.Untappd;using Owin.Security.Providers.WordPress;
using Owin.Security.Providers.TripIt;
using Owin.Security.Providers.Twitch;
using Owin.Security.Providers.Untappd;
using Owin.Security.Providers.Wargaming;
using Owin.Security.Providers.WordPress;
using Owin.Security.Providers.Yahoo;
namespace OwinOAuthProvidersDemo
{
@@ -230,6 +233,15 @@ namespace OwinOAuthProvidersDemo
//app.UseSpotifyAuthentication(
// clientId: "",
// clientSecret: "");
//var options = new SlackAuthenticationOptions
//{
// ClientId = "",
// ClientSecret = "",
// TeamId = "" // optional
//};
//options.Scope.Add("identify");
//app.UseSlackAuthentication(options);
}
}
}