@@ -206,6 +206,15 @@
|
||||
<Compile Include="TripIt\TripItAuthenticationHandler.cs" />
|
||||
<Compile Include="TripIt\TripItAuthenticationMiddleware.cs" />
|
||||
<Compile Include="TripIt\TripItAuthenticationOptions.cs" />
|
||||
<Compile Include="Twitch\Constants.cs" />
|
||||
<Compile Include="Twitch\TwitchAuthenticationExtensions.cs" />
|
||||
<Compile Include="Twitch\TwitchAuthenticationHandler.cs" />
|
||||
<Compile Include="Twitch\TwitchAuthenticationMiddleware.cs" />
|
||||
<Compile Include="Twitch\TwitchAuthenticationOptions.cs" />
|
||||
<Compile Include="Twitch\Provider\TwitchAuthenticatedContext.cs" />
|
||||
<Compile Include="Twitch\Provider\TwitchAuthenticationProvider.cs" />
|
||||
<Compile Include="Twitch\Provider\TwitchReturnEndpointContext.cs" />
|
||||
<Compile Include="Twitch\Provider\ITwitchAuthenticationProvider.cs" />
|
||||
<Compile Include="WordPress\WordPressAuthenticationExtensions.cs" />
|
||||
<Compile Include="WordPress\WordPressAuthenticationHandler.cs" />
|
||||
<Compile Include="WordPress\WordPressAuthenticationMiddleware.cs" />
|
||||
|
||||
7
Owin.Security.Providers/Twitch/Constants.cs
Normal file
7
Owin.Security.Providers/Twitch/Constants.cs
Normal file
@@ -0,0 +1,7 @@
|
||||
namespace Owin.Security.Providers.Twitch
|
||||
{
|
||||
internal static class Constants
|
||||
{
|
||||
public const string DefaultAuthenticationType = "Twitch";
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,24 @@
|
||||
using System.Threading.Tasks;
|
||||
|
||||
namespace Owin.Security.Providers.Twitch
|
||||
{
|
||||
/// <summary>
|
||||
/// Specifies callback methods which the <see cref="TwitchAuthenticationMiddleware"></see> invokes to enable developer control over the authentication process. />
|
||||
/// </summary>
|
||||
public interface ITwitchAuthenticationProvider
|
||||
{
|
||||
/// <summary>
|
||||
/// Invoked whenever Twitch 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(TwitchAuthenticatedContext 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(TwitchReturnEndpointContext context);
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,89 @@
|
||||
// Copyright (c) Microsoft Open Technologies, Inc. All rights reserved. See License.txt in the project root for license information.
|
||||
|
||||
using System;
|
||||
using System.Globalization;
|
||||
using System.Security.Claims;
|
||||
using Microsoft.Owin;
|
||||
using Microsoft.Owin.Security;
|
||||
using Microsoft.Owin.Security.Provider;
|
||||
using Newtonsoft.Json.Linq;
|
||||
|
||||
namespace Owin.Security.Providers.Twitch
|
||||
{
|
||||
/// <summary>
|
||||
/// Contains information about the login session as well as the user <see cref="System.Security.Claims.ClaimsIdentity"/>.
|
||||
/// </summary>
|
||||
public class TwitchAuthenticatedContext : BaseContext
|
||||
{
|
||||
/// <summary>
|
||||
/// Initializes a <see cref="TwitchAuthenticatedContext"/>
|
||||
/// </summary>
|
||||
/// <param name="context">The OWIN environment</param>
|
||||
/// <param name="user">The JSON-serialized user</param>
|
||||
/// <param name="accessToken">Twitch Access token</param>
|
||||
public TwitchAuthenticatedContext(IOwinContext context, JObject user, string accessToken)
|
||||
: base(context)
|
||||
{
|
||||
User = user;
|
||||
AccessToken = accessToken;
|
||||
|
||||
Id = TryGetValue(user, "_id");
|
||||
Name = TryGetValue(user, "name");
|
||||
Link = TryGetValue(user, "url");
|
||||
UserName = TryGetValue(user, "name");
|
||||
Email = TryGetValue(user, "email");
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Gets the JSON-serialized user
|
||||
/// </summary>
|
||||
/// <remarks>
|
||||
/// Contains the Twitch user obtained from the User Info endpoint. By default this is https://api.Twitch.com/user but it can be
|
||||
/// overridden in the options
|
||||
/// </remarks>
|
||||
public JObject User { get; private set; }
|
||||
|
||||
/// <summary>
|
||||
/// Gets the Twitch access token
|
||||
/// </summary>
|
||||
public string AccessToken { get; private set; }
|
||||
|
||||
/// <summary>
|
||||
/// Gets the Twitch user ID
|
||||
/// </summary>
|
||||
public string Id { get; private set; }
|
||||
|
||||
/// <summary>
|
||||
/// Gets the user's name
|
||||
/// </summary>
|
||||
public string Name { get; private set; }
|
||||
|
||||
public string Link { get; private set; }
|
||||
|
||||
/// <summary>
|
||||
/// Gets the Twitch username
|
||||
/// </summary>
|
||||
public string UserName { get; private set; }
|
||||
|
||||
/// <summary>
|
||||
/// Gets the Twitch email
|
||||
/// </summary>
|
||||
public string Email { 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;
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,50 @@
|
||||
using System;
|
||||
using System.Threading.Tasks;
|
||||
|
||||
namespace Owin.Security.Providers.Twitch
|
||||
{
|
||||
/// <summary>
|
||||
/// Default <see cref="ITwitchAuthenticationProvider"/> implementation.
|
||||
/// </summary>
|
||||
public class TwitchAuthenticationProvider : ITwitchAuthenticationProvider
|
||||
{
|
||||
/// <summary>
|
||||
/// Initializes a <see cref="TwitchAuthenticationProvider"/>
|
||||
/// </summary>
|
||||
public TwitchAuthenticationProvider()
|
||||
{
|
||||
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<TwitchAuthenticatedContext, Task> OnAuthenticated { get; set; }
|
||||
|
||||
/// <summary>
|
||||
/// Gets or sets the function that is invoked when the ReturnEndpoint method is invoked.
|
||||
/// </summary>
|
||||
public Func<TwitchReturnEndpointContext, Task> OnReturnEndpoint { get; set; }
|
||||
|
||||
/// <summary>
|
||||
/// Invoked whenever Twitch 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(TwitchAuthenticatedContext 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(TwitchReturnEndpointContext context)
|
||||
{
|
||||
return OnReturnEndpoint(context);
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,26 @@
|
||||
// Copyright (c) Microsoft Open Technologies, Inc. All rights reserved. See License.txt in the project root for license information.
|
||||
|
||||
using Microsoft.Owin;
|
||||
using Microsoft.Owin.Security;
|
||||
using Microsoft.Owin.Security.Provider;
|
||||
|
||||
namespace Owin.Security.Providers.Twitch
|
||||
{
|
||||
/// <summary>
|
||||
/// Provides context information to middleware providers.
|
||||
/// </summary>
|
||||
public class TwitchReturnEndpointContext : ReturnEndpointContext
|
||||
{
|
||||
/// <summary>
|
||||
///
|
||||
/// </summary>
|
||||
/// <param name="context">OWIN environment</param>
|
||||
/// <param name="ticket">The authentication ticket</param>
|
||||
public TwitchReturnEndpointContext(
|
||||
IOwinContext context,
|
||||
AuthenticationTicket ticket)
|
||||
: base(context, ticket)
|
||||
{
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,41 @@
|
||||
using System;
|
||||
|
||||
namespace Owin.Security.Providers.Twitch
|
||||
{
|
||||
public static class TwitchAuthenticationExtensions
|
||||
{
|
||||
/// <summary>
|
||||
/// Login with Twitch. http://yourUrl/signin-Twitch will be used as the redirect URI
|
||||
/// </summary>
|
||||
/// <param name="app"></param>
|
||||
/// <param name="options"></param>
|
||||
/// <returns></returns>
|
||||
public static IAppBuilder UseTwitchAuthentication(this IAppBuilder app,
|
||||
TwitchAuthenticationOptions options)
|
||||
{
|
||||
if (app == null)
|
||||
throw new ArgumentNullException("app");
|
||||
if (options == null)
|
||||
throw new ArgumentNullException("options");
|
||||
|
||||
app.Use(typeof(TwitchAuthenticationMiddleware), app, options);
|
||||
|
||||
return app;
|
||||
}
|
||||
/// <summary>
|
||||
/// Login with Twitch. http://yourUrl/signin-Twitch will be used as the redirect URI
|
||||
/// </summary>
|
||||
/// <param name="app"></param>
|
||||
/// <param name="clientId"></param>
|
||||
/// <param name="clientSecret"></param>
|
||||
/// <returns></returns>
|
||||
public static IAppBuilder UseTwitchAuthentication(this IAppBuilder app, string clientId, string clientSecret)
|
||||
{
|
||||
return app.UseTwitchAuthentication(new TwitchAuthenticationOptions
|
||||
{
|
||||
ClientId = clientId,
|
||||
ClientSecret = clientSecret
|
||||
});
|
||||
}
|
||||
}
|
||||
}
|
||||
241
Owin.Security.Providers/Twitch/TwitchAuthenticationHandler.cs
Normal file
241
Owin.Security.Providers/Twitch/TwitchAuthenticationHandler.cs
Normal file
@@ -0,0 +1,241 @@
|
||||
using System;
|
||||
using System.Collections.Generic;
|
||||
using System.Linq;
|
||||
using System.Net.Http;
|
||||
using System.Net.Http.Headers;
|
||||
using System.Security.Claims;
|
||||
using System.Text;
|
||||
using System.Threading.Tasks;
|
||||
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;
|
||||
|
||||
namespace Owin.Security.Providers.Twitch
|
||||
{
|
||||
public class TwitchAuthenticationHandler : AuthenticationHandler<TwitchAuthenticationOptions>
|
||||
{
|
||||
private const string XmlSchemaString = "http://www.w3.org/2001/XMLSchema#string";
|
||||
|
||||
private readonly ILogger logger;
|
||||
private readonly HttpClient httpClient;
|
||||
|
||||
public TwitchAuthenticationHandler(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 = string.Copy(values.First());
|
||||
}
|
||||
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);
|
||||
}
|
||||
|
||||
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>("grant_type", "authorization_code"));
|
||||
body.Add(new KeyValuePair<string, string>("redirect_uri", redirectUri));
|
||||
body.Add(new KeyValuePair<string, string>("code", code));
|
||||
|
||||
// Request the token
|
||||
var requestMessage = new HttpRequestMessage(HttpMethod.Post, Options.Endpoints.TokenEndpoint);
|
||||
requestMessage.Content = new FormUrlEncodedContent(body);
|
||||
requestMessage.Headers.Accept.Add(new MediaTypeWithQualityHeaderValue("application/json"));
|
||||
HttpResponseMessage tokenResponse = await httpClient.SendAsync(requestMessage);
|
||||
tokenResponse.EnsureSuccessStatusCode();
|
||||
string text = await tokenResponse.Content.ReadAsStringAsync();
|
||||
|
||||
// Deserializes the token response
|
||||
dynamic response = JsonConvert.DeserializeObject<dynamic>(text);
|
||||
string accessToken = (string)response.access_token;
|
||||
|
||||
// Get the Twitch user
|
||||
HttpRequestMessage userRequest = new HttpRequestMessage(HttpMethod.Get, Options.Endpoints.UserInfoEndpoint + "?oauth_token=" + Uri.EscapeDataString(accessToken));
|
||||
userRequest.Headers.Accept.Add(new MediaTypeWithQualityHeaderValue("application/json"));
|
||||
HttpResponseMessage userResponse = await httpClient.SendAsync(userRequest, Request.CallCancelled);
|
||||
userResponse.EnsureSuccessStatusCode();
|
||||
text = await userResponse.Content.ReadAsStringAsync();
|
||||
JObject user = JObject.Parse(text);
|
||||
|
||||
var context = new TwitchAuthenticatedContext(Context, user, accessToken);
|
||||
context.Identity = new ClaimsIdentity(
|
||||
Options.AuthenticationType,
|
||||
ClaimsIdentity.DefaultNameClaimType,
|
||||
ClaimsIdentity.DefaultRoleClaimType);
|
||||
if (!string.IsNullOrEmpty(context.Id))
|
||||
{
|
||||
context.Identity.AddClaim(new Claim(ClaimTypes.NameIdentifier, context.Id, XmlSchemaString, Options.AuthenticationType));
|
||||
}
|
||||
if (!string.IsNullOrEmpty(context.UserName))
|
||||
{
|
||||
context.Identity.AddClaim(new Claim(ClaimsIdentity.DefaultNameClaimType, context.UserName, XmlSchemaString, Options.AuthenticationType));
|
||||
}
|
||||
if (!string.IsNullOrEmpty(context.Email))
|
||||
{
|
||||
context.Identity.AddClaim(new Claim(ClaimTypes.Email, context.Email, XmlSchemaString, Options.AuthenticationType));
|
||||
}
|
||||
if (!string.IsNullOrEmpty(context.Name))
|
||||
{
|
||||
context.Identity.AddClaim(new Claim("urn:Twitch:name", context.Name, XmlSchemaString, Options.AuthenticationType));
|
||||
}
|
||||
if (!string.IsNullOrEmpty(context.Link))
|
||||
{
|
||||
context.Identity.AddClaim(new Claim("urn:Twitch:url", context.Link, 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 =
|
||||
Options.Endpoints.AuthorizationEndpoint +
|
||||
"?client_id=" + Uri.EscapeDataString(Options.ClientId) +
|
||||
"&redirect_uri=" + Uri.EscapeDataString(redirectUri) +
|
||||
"&scope=" + Uri.EscapeDataString(scope) +
|
||||
"&response_type=" + "code" +
|
||||
"&state=" + Uri.EscapeDataString(state);
|
||||
|
||||
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 TwitchReturnEndpointContext(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;
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,87 @@
|
||||
using System;
|
||||
using System.Globalization;
|
||||
using System.Net.Http;
|
||||
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;
|
||||
|
||||
namespace Owin.Security.Providers.Twitch
|
||||
{
|
||||
public class TwitchAuthenticationMiddleware : AuthenticationMiddleware<TwitchAuthenticationOptions>
|
||||
{
|
||||
private readonly HttpClient httpClient;
|
||||
private readonly ILogger logger;
|
||||
|
||||
public TwitchAuthenticationMiddleware(OwinMiddleware next, IAppBuilder app,
|
||||
TwitchAuthenticationOptions options)
|
||||
: base(next, options)
|
||||
{
|
||||
if (String.IsNullOrWhiteSpace(Options.ClientId))
|
||||
throw new ArgumentException(String.Format(CultureInfo.CurrentCulture,
|
||||
Resources.Exception_OptionMustBeProvided, "ClientId"));
|
||||
if (String.IsNullOrWhiteSpace(Options.ClientSecret))
|
||||
throw new ArgumentException(String.Format(CultureInfo.CurrentCulture,
|
||||
Resources.Exception_OptionMustBeProvided, "ClientSecret"));
|
||||
|
||||
logger = app.CreateLogger<TwitchAuthenticationMiddleware>();
|
||||
|
||||
if (Options.Provider == null)
|
||||
Options.Provider = new TwitchAuthenticationProvider();
|
||||
|
||||
if (Options.StateDataFormat == null)
|
||||
{
|
||||
IDataProtector dataProtector = app.CreateDataProtector(
|
||||
typeof (TwitchAuthenticationMiddleware).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 Twitch 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:Owin.Security.Providers.Twitch.TwitchAuthenticationOptions" /> supplied to the constructor.
|
||||
/// </returns>
|
||||
protected override AuthenticationHandler<TwitchAuthenticationOptions> CreateHandler()
|
||||
{
|
||||
return new TwitchAuthenticationHandler(httpClient, logger);
|
||||
}
|
||||
|
||||
private HttpMessageHandler ResolveHttpMessageHandler(TwitchAuthenticationOptions 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;
|
||||
}
|
||||
}
|
||||
}
|
||||
145
Owin.Security.Providers/Twitch/TwitchAuthenticationOptions.cs
Normal file
145
Owin.Security.Providers/Twitch/TwitchAuthenticationOptions.cs
Normal file
@@ -0,0 +1,145 @@
|
||||
using System;
|
||||
using System.Collections.Generic;
|
||||
using System.Net.Http;
|
||||
using Microsoft.Owin;
|
||||
using Microsoft.Owin.Security;
|
||||
|
||||
namespace Owin.Security.Providers.Twitch
|
||||
{
|
||||
public class TwitchAuthenticationOptions : AuthenticationOptions
|
||||
{
|
||||
public class TwitchAuthenticationEndpoints
|
||||
{
|
||||
/// <summary>
|
||||
/// Endpoint which is used to redirect users to request Twitch access
|
||||
/// </summary>
|
||||
/// <remarks>
|
||||
/// Defaults to https://api.twitch.tv/kraken/oauth2/authorize
|
||||
/// </remarks>
|
||||
public string AuthorizationEndpoint { get; set; }
|
||||
|
||||
/// <summary>
|
||||
/// Endpoint which is used to exchange code for access token
|
||||
/// </summary>
|
||||
/// <remarks>
|
||||
/// Defaults to https://api.twitch.tv/kraken/oauth2/token
|
||||
/// </remarks>
|
||||
public string TokenEndpoint { get; set; }
|
||||
|
||||
/// <summary>
|
||||
/// Endpoint which is used to obtain user information after authentication
|
||||
/// </summary>
|
||||
/// <remarks>
|
||||
/// Defaults to https://api.twitch.tv/kraken/user
|
||||
/// </remarks>
|
||||
public string UserInfoEndpoint { get; set; }
|
||||
}
|
||||
|
||||
private const string AuthorizationEndPoint = "https://api.twitch.tv/kraken/oauth2/authorize";
|
||||
private const string TokenEndpoint = "https://api.twitch.tv/kraken/oauth2/token";
|
||||
private const string UserInfoEndpoint = "https://api.twitch.tv/kraken/user";
|
||||
|
||||
/// <summary>
|
||||
/// Gets or sets the a pinned certificate validator to use to validate the endpoints used
|
||||
/// in back channel communications belong to Twitch.
|
||||
/// </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 Twitch.
|
||||
/// 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 Twitch.
|
||||
/// </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-Twitch".
|
||||
/// </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 Twitch supplied Client ID
|
||||
/// </summary>
|
||||
public string ClientId { get; set; }
|
||||
|
||||
/// <summary>
|
||||
/// Gets or sets the Twitch supplied Client Secret
|
||||
/// </summary>
|
||||
public string ClientSecret { get; set; }
|
||||
|
||||
/// <summary>
|
||||
/// Gets the sets of OAuth endpoints used to authenticate against Twitch. Overriding these endpoints allows you to use Twitch Enterprise for
|
||||
/// authentication.
|
||||
/// </summary>
|
||||
public TwitchAuthenticationEndpoints Endpoints { get; set; }
|
||||
|
||||
/// <summary>
|
||||
/// Gets or sets the <see cref="ITwitchAuthenticationProvider" /> used in the authentication events
|
||||
/// </summary>
|
||||
public ITwitchAuthenticationProvider Provider { get; set; }
|
||||
|
||||
/// <summary>
|
||||
/// A list of permissions to request.
|
||||
/// </summary>
|
||||
public IList<string> Scope { get; private 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>
|
||||
/// Initializes a new <see cref="TwitchAuthenticationOptions" />
|
||||
/// </summary>
|
||||
public TwitchAuthenticationOptions()
|
||||
: base("Twitch")
|
||||
{
|
||||
Caption = Constants.DefaultAuthenticationType;
|
||||
CallbackPath = new PathString("/signin-Twitch");
|
||||
AuthenticationMode = AuthenticationMode.Passive;
|
||||
Scope = new List<string>
|
||||
{
|
||||
"user_read"
|
||||
};
|
||||
BackchannelTimeout = TimeSpan.FromSeconds(60);
|
||||
Endpoints = new TwitchAuthenticationEndpoints
|
||||
{
|
||||
AuthorizationEndpoint = AuthorizationEndPoint,
|
||||
TokenEndpoint = TokenEndpoint,
|
||||
UserInfoEndpoint = UserInfoEndpoint
|
||||
};
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -1,4 +1,5 @@
|
||||
using System;
|
||||
using System.Security.Claims;
|
||||
using Microsoft.AspNet.Identity;
|
||||
using Microsoft.Owin;
|
||||
using Microsoft.Owin.Security.Cookies;
|
||||
@@ -17,6 +18,7 @@ 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.Steam;
|
||||
@@ -87,6 +89,46 @@ namespace OwinOAuthProvidersDemo
|
||||
//options.MomentTypes.Add("http://schemas.google.com/BuyActivity");
|
||||
//app.UseGooglePlusAuthentication(options);
|
||||
|
||||
/*
|
||||
* Twitch sign-ins use /signin-Twitch as the URL for authentication
|
||||
*
|
||||
|
||||
*/
|
||||
|
||||
////Simple Twitch Sign-in
|
||||
//app.UseTwitchAuthentication("", "");
|
||||
|
||||
////More complex Twitch Sign-in
|
||||
//var opt = new TwitchAuthenticationOptions()
|
||||
//{
|
||||
// ClientId = "",
|
||||
// ClientSecret = "",
|
||||
// Provider = new TwitchAuthenticationProvider()
|
||||
// {
|
||||
|
||||
// OnAuthenticated = async z =>
|
||||
// {
|
||||
//// Getting the twitch users picture
|
||||
// z.Identity.AddClaim(new Claim("Picture", z.User.GetValue("logo").ToString()));
|
||||
// }
|
||||
//// You should be able to access these claims with HttpContext.GetOwinContext().Authentication.GetExternalLoginInfoAsync().Claims in your Account Controller
|
||||
// // Commonly used in the ExternalLoginCallback() in AccountController.cs
|
||||
// /*
|
||||
|
||||
// if (user != null)
|
||||
// {
|
||||
// var claim = (await AuthenticationManager.GetExternalLoginInfoAsync()).ExternalIdentity.Claims.First(
|
||||
// a => a.Type == "Picture");
|
||||
// user.Claims.Add(new IdentityUserClaim() { ClaimType = claim.Type, ClaimValue = claim.Value });
|
||||
// await SignInAsync(user, isPersistent: false);
|
||||
// return RedirectToLocal(returnUrl);
|
||||
// }
|
||||
// */
|
||||
// }
|
||||
//};
|
||||
//app.UseTwitchAuthentication(opt);
|
||||
|
||||
|
||||
|
||||
//app.UseOpenIDAuthentication("http://me.yahoo.com/", "Yahoo");
|
||||
|
||||
|
||||
Reference in New Issue
Block a user