remove ref to OWin & changes to AspNet.OAuth.Server

main
Paul Schneider 10 years ago
parent 4b8c5cc984
commit 729e7648ff
26 changed files with 7097 additions and 1451 deletions

@ -1,14 +0,0 @@
public interface IApplication
{
string ApplicationID { get; set; }
string DisplayName { get; set; }
string RedirectUri { get; set; }
string LogoutRedirectUri { get; set; }
string Secret { get; set; }
}
public interface IApplicationStore
{
IApplication FindApplication(string clientId);
}

@ -17,12 +17,6 @@ namespace OAuth.AspNet.AuthServer
public class OAuthAuthorizationServerHandler : AuthenticationHandler<OAuthAuthorizationServerOptions> public class OAuthAuthorizationServerHandler : AuthenticationHandler<OAuthAuthorizationServerOptions>
{ {
public OAuthAuthorizationServerHandler(IApplicationStore applicationStore)
{
ApplicationStore = applicationStore;
}
public IApplicationStore ApplicationStore { get; private set;}
#region non-Public Members #region non-Public Members
private AuthorizeEndpointRequest _authorizeEndpointRequest; private AuthorizeEndpointRequest _authorizeEndpointRequest;
@ -335,7 +329,7 @@ namespace OAuth.AspNet.AuthServer
{ {
var authorizeRequest = new AuthorizeEndpointRequest(Request.Query); var authorizeRequest = new AuthorizeEndpointRequest(Request.Query);
var clientContext = new OAuthValidateClientRedirectUriContext(ApplicationStore,Context, Options, authorizeRequest.ClientId, authorizeRequest.RedirectUri); var clientContext = new OAuthValidateClientRedirectUriContext(Context, Options, authorizeRequest.ClientId, authorizeRequest.RedirectUri);
if (!string.IsNullOrEmpty(authorizeRequest.RedirectUri)) if (!string.IsNullOrEmpty(authorizeRequest.RedirectUri))
{ {
@ -423,7 +417,7 @@ namespace OAuth.AspNet.AuthServer
IFormCollection form = await Request.ReadFormAsync(); IFormCollection form = await Request.ReadFormAsync();
var clientContext = new OAuthValidateClientAuthenticationContext(Context, Options, form, ApplicationStore); var clientContext = new OAuthValidateClientAuthenticationContext(Context, Options, form);
await Options.Provider.ValidateClientAuthentication(clientContext); await Options.Provider.ValidateClientAuthentication(clientContext);

@ -1,10 +1,11 @@
 using Microsoft.AspNet.Authentication;
using Microsoft.AspNet.Authentication;
using Microsoft.AspNet.Builder; using Microsoft.AspNet.Builder;
using Microsoft.AspNet.DataProtection; using Microsoft.AspNet.DataProtection;
using Microsoft.Extensions.Logging; using Microsoft.Extensions.Logging;
using Microsoft.Extensions.WebEncoders; using Microsoft.Extensions.WebEncoders;
using System; using System;
using System.IO;
using Yavsc.Auth;
namespace OAuth.AspNet.AuthServer namespace OAuth.AspNet.AuthServer
{ {
@ -21,21 +22,8 @@ namespace OAuth.AspNet.AuthServer
/// called by application code directly, instead it is added by calling the the IAppBuilder UseOAuthAuthorizationServer /// called by application code directly, instead it is added by calling the the IAppBuilder UseOAuthAuthorizationServer
/// extension method. /// extension method.
/// </summary> /// </summary>
public OAuthAuthorizationServerMiddleware( public OAuthAuthorizationServerMiddleware(RequestDelegate next, OAuthAuthorizationServerOptions options, ILoggerFactory loggerFactory, IDataProtectionProvider dataProtectionProvider, IUrlEncoder encoder) : base(next, options, loggerFactory, encoder)
RequestDelegate next,
OAuthAuthorizationServerOptions options,
ILoggerFactory loggerFactory,
IDataProtectionProvider dataProtectionProvider,
IUrlEncoder encoder,
IApplicationStore applicationStore
) : base(next, options, loggerFactory, encoder)
{ {
if (applicationStore == null )
{
throw new InvalidOperationException("No application store");
}
ApplicationStore = applicationStore;
if (Options.Provider == null) if (Options.Provider == null)
{ {
Options.Provider = new OAuthAuthorizationServerProvider(); Options.Provider = new OAuthAuthorizationServerProvider();
@ -57,8 +45,11 @@ namespace OAuth.AspNet.AuthServer
if (Options.TokenDataProtector == null) if (Options.TokenDataProtector == null)
{ {
Options.TokenDataProtector = dataProtectionProvider.CreateProtector("OAuth.AspNet.AuthServer"); #if DNXCORE50
Options.TokenDataProtector = new DataProtectionProvider(new DirectoryInfo(Environment.GetEnvironmentVariable("Temp"))).CreateProtector("OAuth.AspNet.AuthServer");
#else
Options.TokenDataProtector = new MonoDataProtectionProvider("OAuth.AspNet.AuthServer").CreateProtector("OAuth.Data.Protector");
#endif
} }
if (Options.AccessTokenFormat == null) if (Options.AccessTokenFormat == null)
@ -82,17 +73,15 @@ namespace OAuth.AspNet.AuthServer
{ {
Options.RefreshTokenProvider = new AuthenticationTokenProvider(); Options.RefreshTokenProvider = new AuthenticationTokenProvider();
} }
} }
private IApplicationStore ApplicationStore { get; set; }
/// <summary> /// <summary>
/// Called by the AuthenticationMiddleware base class to create a per-request handler. /// Called by the AuthenticationMiddleware base class to create a per-request handler.
/// </summary> /// </summary>
/// <returns>A new instance of the request handler</returns> /// <returns>A new instance of the request handler</returns>
protected override AuthenticationHandler<OAuthAuthorizationServerOptions> CreateHandler() protected override AuthenticationHandler<OAuthAuthorizationServerOptions> CreateHandler()
{ {
return new OAuthAuthorizationServerHandler(ApplicationStore); return new OAuthAuthorizationServerHandler();
} }
} }

@ -1,3 +1,4 @@
using Microsoft.AspNet.Authentication;
using Microsoft.AspNet.Http; using Microsoft.AspNet.Http;
namespace OAuth.AspNet.AuthServer namespace OAuth.AspNet.AuthServer

@ -16,14 +16,11 @@ namespace OAuth.AspNet.AuthServer
/// <param name="context"></param> /// <param name="context"></param>
/// <param name="options"></param> /// <param name="options"></param>
/// <param name="parameters"></param> /// <param name="parameters"></param>
public OAuthValidateClientAuthenticationContext(HttpContext context, OAuthAuthorizationServerOptions options, IReadableStringCollection parameters, IApplicationStore applicationStore) : base(context, options, null) public OAuthValidateClientAuthenticationContext(HttpContext context, OAuthAuthorizationServerOptions options, IReadableStringCollection parameters) : base(context, options, null)
{ {
Parameters = parameters; Parameters = parameters;
ApplicationStore = applicationStore;
} }
public IApplicationStore ApplicationStore { get; private set;}
/// <summary> /// <summary>
/// Gets the set of form parameters from the request. /// Gets the set of form parameters from the request.
/// </summary> /// </summary>

@ -1,14 +0,0 @@
public class OAuthValidateClientCredentialsContext { 
public OAuthValidateClientCredentialsContext(string clientId,string clientSecret,IApplicationStore applicationStore)
{
ClientId = clientId;
ClientSecret = clientSecret;
ApplicationStore = applicationStore;
}
public string ClientId { get; private set; }
public string ClientSecret { get; private set; }
public IApplicationStore ApplicationStore { get; private set; }
}

@ -17,10 +17,9 @@ namespace OAuth.AspNet.AuthServer
/// <param name="clientId"></param> /// <param name="clientId"></param>
/// <param name="redirectUri"></param> /// <param name="redirectUri"></param>
[System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Design", "CA1054:UriParametersShouldNotBeStrings", MessageId = "3#", Justification = "redirect_uri is a string parameter")] [System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Design", "CA1054:UriParametersShouldNotBeStrings", MessageId = "3#", Justification = "redirect_uri is a string parameter")]
public OAuthValidateClientRedirectUriContext(IApplicationStore applicationStore, HttpContext context, OAuthAuthorizationServerOptions options, string clientId, string redirectUri) : base(context, options, clientId) public OAuthValidateClientRedirectUriContext(HttpContext context, OAuthAuthorizationServerOptions options, string clientId, string redirectUri) : base(context, options, clientId)
{ {
RedirectUri = redirectUri; RedirectUri = redirectUri;
ApplicationStore = applicationStore;
} }
/// <summary> /// <summary>
@ -29,8 +28,6 @@ namespace OAuth.AspNet.AuthServer
[System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Design", "CA1056:UriPropertiesShouldNotBeStrings", Justification = "redirect_uri is a string parameter")] [System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Design", "CA1056:UriPropertiesShouldNotBeStrings", Justification = "redirect_uri is a string parameter")]
public string RedirectUri { get; private set; } public string RedirectUri { get; private set; }
public IApplicationStore ApplicationStore { get; private set;}
/// <summary> /// <summary>
/// Marks this context as validated by the application. IsValidated becomes true and HasError becomes false as a result of calling. /// Marks this context as validated by the application. IsValidated becomes true and HasError becomes false as a result of calling.
/// </summary> /// </summary>

@ -2,6 +2,7 @@
using System; using System;
using System.IO;
using Microsoft.AspNet.DataProtection; using Microsoft.AspNet.DataProtection;
namespace Yavsc.Auth namespace Yavsc.Auth
{ {
@ -13,10 +14,14 @@ public class MonoDataProtectionProvider : IDataProtectionProvider
: this(Guid.NewGuid().ToString()) : this(Guid.NewGuid().ToString())
{ } { }
public MonoDataProtectionProvider(DirectoryInfo dataProtectionDirInfo)
: this(Guid.NewGuid().ToString())
{
}
public MonoDataProtectionProvider(string appName) public MonoDataProtectionProvider(string appName)
{ {
if (appName == null) { throw new ArgumentNullException("appName"); } if (appName == null) { throw new ArgumentNullException("appName"); }
this.appName = appName; this.appName = appName;
} }

@ -29,7 +29,7 @@ namespace Yavsc.Auth
{ {
public class MonoDataProtector : IDataProtector public class MonoDataProtector : IDataProtector
{ {
private const string PRIMARY_PURPOSE = "Microsoft.Owin.Security.IDataProtector"; private const string PRIMARY_PURPOSE = "IDataProtector";
private readonly string appName; private readonly string appName;
private readonly DataProtectionScope dataProtectionScope; private readonly DataProtectionScope dataProtectionScope;

@ -4,15 +4,17 @@ namespace Yavsc
public static class Constants public static class Constants
{ {
public const string AccessDeniedPath = "~/forbidden"; public const string AccessDeniedPath = "~/signin";
public const string AuthorizePath = "~/authorize"; public const string AuthorizePath = "~/authorize";
public const string TokenPath = "~/token"; public const string TokenPath = "~/token";
public const string LocalLoginPath = "~/login";
public const string LoginPath = "~/signin"; public const string LoginPath = "~/signin";
public const string ExternalLoginPath = "~/extsign";
public const string LogoutPath = "~/signout"; public const string LogoutPath = "~/signout";
public const string MePath = "~/api/Me"; public const string MePath = "~/api/Me";
public const string ExternalAuthenticationSheme = "ExternalCookie";
public const string ExternalAuthenticationSheme = "External"; public const string ApplicationAuthenticationSheme = "ServerCookie";
public const string ApplicationAuthenticationSheme = "Server";
public static readonly Scope[] SiteScopes = {  public static readonly Scope[] SiteScopes = { 
new Scope { Id = "profile", Description = "Your profile informations" },   new Scope { Id = "profile", Description = "Your profile informations" },  
new Scope { Id = "book" , Description ="Your booking interface"},   new Scope { Id = "book" , Description ="Your booking interface"},  

@ -10,11 +10,12 @@ using Microsoft.AspNet.Mvc;
using Microsoft.AspNet.Mvc.Rendering; using Microsoft.AspNet.Mvc.Rendering;
using Microsoft.Extensions.Logging; using Microsoft.Extensions.Logging;
using Microsoft.Extensions.OptionsModel; using Microsoft.Extensions.OptionsModel;
using Microsoft.AspNet.Http;
using Yavsc.Extensions; using Yavsc.Extensions;
using Yavsc.Models; using Yavsc.Models;
using Yavsc.Services; using Yavsc.Services;
using Yavsc.ViewModels.Account; using Yavsc.ViewModels.Account;
using Microsoft.AspNet.Http.Authentication;
namespace Yavsc.Controllers namespace Yavsc.Controllers
{ {
@ -50,14 +51,15 @@ namespace Yavsc.Controllers
_twilioSettings = twilioSettings.Value; _twilioSettings = twilioSettings.Value;
_logger = loggerFactory.CreateLogger<AccountController>(); _logger = loggerFactory.CreateLogger<AccountController>();
} }
[HttpGet(Constants.LoginPath)] [HttpGet(Constants.LoginPath)]
public ActionResult Login(string returnUrl = null) public ActionResult SignIn(string returnUrl = null)
{ {
// Note: the "returnUrl" parameter corresponds to the endpoint the user agent // Note: the "returnUrl" parameter corresponds to the endpoint the user agent
// will be redirected to after a successful authentication and not // will be redirected to after a successful authentication and not
// the redirect_uri of the requesting client application against the third // the redirect_uri of the requesting client application against the third
// party identity provider. // party identity provider.
return View("Login", new LoginViewModel return View(new SignInViewModel
{ {
ReturnUrl = returnUrl, ReturnUrl = returnUrl,
ExternalProviders = HttpContext.GetExternalProviders() ExternalProviders = HttpContext.GetExternalProviders()
@ -68,7 +70,21 @@ namespace Yavsc.Controllers
*/ */
} }
[HttpPost(Constants.LoginPath)]
public async Task<IActionResult> SignIn(SignInViewModel model)
{
if (Request.Method == "POST")
{
if (model.Provider=="LOCAL")
{
return await Login(model);
}
}
model.ExternalProviders = HttpContext.GetExternalProviders();
return View(model);
}
[HttpPost(Constants.ExternalLoginPath)]
public IActionResult ExternalLogin(string Provider, string ReturnUrl) public IActionResult ExternalLogin(string Provider, string ReturnUrl)
{ {
// Note: the "provider" parameter corresponds to the external // Note: the "provider" parameter corresponds to the external
@ -104,8 +120,7 @@ namespace Yavsc.Controllers
return new ChallengeResult(Provider, properties); return new ChallengeResult(Provider, properties);
} }
[HttpPost(Constants.LoginPath)] public async Task<IActionResult> Login(SignInViewModel model)
public async Task<IActionResult> Login(LoginViewModel model)
{ {
if (ModelState.IsValid) if (ModelState.IsValid)
{ {
@ -194,6 +209,7 @@ namespace Yavsc.Controllers
var info = await _signInManager.GetExternalLoginInfoAsync(); var info = await _signInManager.GetExternalLoginInfoAsync();
if (info == null) if (info == null)
{ {
_logger.LogWarning("No external provider info found.");
return Redirect("~/signin"); // RedirectToAction(nameof(OAuthController.SignIn)); return Redirect("~/signin"); // RedirectToAction(nameof(OAuthController.SignIn));
} }

@ -47,14 +47,6 @@ namespace Yavsc.Controllers
_logger = loggerFactory.CreateLogger<OAuthController>(); _logger = loggerFactory.CreateLogger<OAuthController>();
} }
[HttpGet(Constants.AccessDeniedPath)]
public ActionResult Forbidden(string returnUrl = null)
{
return View("Forbidden", returnUrl);
}
/* /*
private async Task<string> GetToken(string purpose, string userid, DateTime? expires) private async Task<string> GetToken(string purpose, string userid, DateTime? expires)
{ {

@ -4,7 +4,7 @@ using Owin;
using System; using System;
using System.Collections.Generic; using System.Collections.Generic;
using System.Threading.Tasks; using System.Threading.Tasks;
#if OWIN
namespace Yavsc namespace Yavsc
{ {
using Microsoft.AspNet.SignalR; using Microsoft.AspNet.SignalR;
@ -43,3 +43,4 @@ namespace Yavsc
} }
} }
} }
#endif

@ -10,7 +10,7 @@ using Yavsc.Models.Booking;
namespace Yavsc.Models namespace Yavsc.Models
{ {
public class ApplicationDbContext : IdentityDbContext<ApplicationUser>, IApplicationStore public class ApplicationDbContext : IdentityDbContext<ApplicationUser>
{ {
protected override void OnModelCreating(ModelBuilder builder) protected override void OnModelCreating(ModelBuilder builder)
{ {
@ -151,7 +151,7 @@ namespace Yavsc.Models
return Task.FromResult(0); return Task.FromResult(0);
} }
IApplication IApplicationStore.FindApplication(string clientId) Application FindApplication(string clientId)
{ {
return Applications.FirstOrDefault( return Applications.FirstOrDefault(
app=>app.ApplicationID == clientId); app=>app.ApplicationID == clientId);

@ -2,7 +2,7 @@ using System.ComponentModel.DataAnnotations;
namespace Yavsc namespace Yavsc
{ {
public class Application : IApplication public class Application
{ {
[Key] [Key]
public string ApplicationID { get; set; } public string ApplicationID { get; set; }

@ -4,6 +4,8 @@ using Microsoft.AspNet.Authentication;
using Microsoft.AspNet.Authentication.OAuth; using Microsoft.AspNet.Authentication.OAuth;
using Microsoft.AspNet.Builder; using Microsoft.AspNet.Builder;
using Microsoft.AspNet.Http; using Microsoft.AspNet.Http;
using Microsoft.AspNet.Identity;
using Microsoft.AspNet.Identity.EntityFramework;
using Microsoft.Extensions.DependencyInjection; using Microsoft.Extensions.DependencyInjection;
using Microsoft.Extensions.OptionsModel; using Microsoft.Extensions.OptionsModel;
using Microsoft.Extensions.WebEncoders; using Microsoft.Extensions.WebEncoders;
@ -19,10 +21,7 @@ namespace Yavsc
private void ConfigureOAuthServices(IServiceCollection services) private void ConfigureOAuthServices(IServiceCollection services)
{ {
services.Configure<SharedAuthenticationOptions>(options => options.SignInScheme = Constants.ExternalAuthenticationSheme); services.Configure<SharedAuthenticationOptions>(options => options.SignInScheme = Constants.ExternalAuthenticationSheme);
services.AddAuthentication(options =>
{
options.SignInScheme = Constants.ExternalAuthenticationSheme;
});
services.Add(ServiceDescriptor.Singleton(typeof(IOptions<OAuth2AppSettings>), typeof(OptionsManager<OAuth2AppSettings>))); services.Add(ServiceDescriptor.Singleton(typeof(IOptions<OAuth2AppSettings>), typeof(OptionsManager<OAuth2AppSettings>)));
// used by the YavscGoogleOAuth middelware (TODO drop it) // used by the YavscGoogleOAuth middelware (TODO drop it)
services.AddTransient<Microsoft.Extensions.WebEncoders.UrlEncoder, UrlEncoder>(); services.AddTransient<Microsoft.Extensions.WebEncoders.UrlEncoder, UrlEncoder>();
@ -43,6 +42,40 @@ namespace Yavsc
new SigningCredentials(key, SecurityAlgorithms.RsaSha256Signature); new SigningCredentials(key, SecurityAlgorithms.RsaSha256Signature);
} }
); */ ); */
services.AddAuthentication(options =>
{
options.SignInScheme = Constants.ApplicationAuthenticationSheme;
});
var protector = new MonoDataProtectionProvider(Configuration["Site:Title"]);;
services.AddInstance<MonoDataProtectionProvider>(
protector
);
services.AddIdentity<ApplicationUser, IdentityRole>(
option =>
{
option.User.AllowedUserNameCharacters += " ";
option.User.RequireUniqueEmail = true;
option.Cookies.ApplicationCookie.DataProtectionProvider = protector;
option.Cookies.ApplicationCookie.LoginPath = new PathString(Constants.LoginPath.Substring(1));
option.Cookies.ApplicationCookie.AccessDeniedPath = new PathString(Constants.AccessDeniedPath.Substring(1));
option.Cookies.ApplicationCookie.AutomaticAuthenticate = true;
option.Cookies.ApplicationCookie.AuthenticationScheme = Constants.ApplicationAuthenticationSheme;
option.Cookies.ApplicationCookieAuthenticationScheme = Constants.ApplicationAuthenticationSheme;
option.Cookies.TwoFactorRememberMeCookie.ExpireTimeSpan = TimeSpan.FromDays(30);
option.Cookies.TwoFactorRememberMeCookie.DataProtectionProvider = protector;
option.Cookies.ExternalCookieAuthenticationScheme = Constants.ExternalAuthenticationSheme;
option.Cookies.ExternalCookie.AutomaticAuthenticate = true;
option.Cookies.ExternalCookie.AuthenticationScheme = Constants.ExternalAuthenticationSheme;
option.Cookies.ExternalCookie.DataProtectionProvider = protector;
}
).AddEntityFrameworkStores<ApplicationDbContext>()
.AddTokenProvider<EmailTokenProvider<ApplicationUser>>(Constants.EMailFactor)
.AddTokenProvider<UserTokenProvider>(Constants.DefaultFactor)
;
} }
private void ConfigureOAuthApp(IApplicationBuilder app) private void ConfigureOAuthApp(IApplicationBuilder app)
{ {
@ -51,9 +84,10 @@ namespace Yavsc
app.UseCookieAuthentication(options => app.UseCookieAuthentication(options =>
{ {
options.AuthenticationScheme = Constants.ExternalAuthenticationSheme; options.AuthenticationScheme = Constants.ExternalAuthenticationSheme;
options.AutomaticAuthenticate = false; options.AutomaticAuthenticate = true;
options.ExpireTimeSpan = TimeSpan.FromMinutes(5); options.ExpireTimeSpan = TimeSpan.FromMinutes(5);
options.LoginPath = new PathString(Constants.LoginPath.Substring(1)); options.LoginPath = new PathString(Constants.LoginPath.Substring(1));
options.AccessDeniedPath = new PathString(Constants.AccessDeniedPath.Substring(1));
}); });
var gvents = new OAuthEvents(); var gvents = new OAuthEvents();
@ -134,6 +168,7 @@ namespace Yavsc
context.Identity = identity; context.Identity = identity;
} }
}; */ }; */
/*
app.UseOAuthAuthorizationServer( app.UseOAuthAuthorizationServer(
options => options =>
@ -141,10 +176,8 @@ namespace Yavsc
options.AuthorizeEndpointPath = new PathString(Constants.AuthorizePath.Substring(1)); options.AuthorizeEndpointPath = new PathString(Constants.AuthorizePath.Substring(1));
options.TokenEndpointPath = new PathString(Constants.TokenPath.Substring(1)); options.TokenEndpointPath = new PathString(Constants.TokenPath.Substring(1));
options.ApplicationCanDisplayErrors = true; options.ApplicationCanDisplayErrors = true;
#if DEBUG
options.AllowInsecureHttp = true; options.AllowInsecureHttp = true;
#endif options.AuthenticationScheme = Constants.ApplicationAuthenticationSheme;
options.Provider = new OAuthAuthorizationServerProvider options.Provider = new OAuthAuthorizationServerProvider
{ {
@ -166,9 +199,10 @@ namespace Yavsc
OnReceive = ReceiveRefreshToken, OnReceive = ReceiveRefreshToken,
}; };
options.AutomaticAuthenticate = false; options.AutomaticAuthenticate = true;
options.AutomaticChallenge = true;
} }
); );*/
} }
} }
} }

@ -4,21 +4,29 @@ using System.Linq;
using System.Security.Claims; using System.Security.Claims;
using System.Security.Principal; using System.Security.Principal;
using System.Threading.Tasks; using System.Threading.Tasks;
using Microsoft.Extensions.Logging;
using OAuth.AspNet.AuthServer; using OAuth.AspNet.AuthServer;
using Yavsc.Models;
namespace Yavsc namespace Yavsc
{ {
public partial class Startup public partial class Startup
{ {
private Application GetApplication(string clientId)
{
var dbContext = new ApplicationDbContext();
var app = dbContext.Applications.FirstOrDefault(x=>x.ApplicationID == clientId);
return app;
}
private readonly ConcurrentDictionary<string, string> _authenticationCodes = new ConcurrentDictionary<string, string>(StringComparer.Ordinal); private readonly ConcurrentDictionary<string, string> _authenticationCodes = new ConcurrentDictionary<string, string>(StringComparer.Ordinal);
private Task ValidateClientRedirectUri(OAuthValidateClientRedirectUriContext context) private Task ValidateClientRedirectUri(OAuthValidateClientRedirectUriContext context)
{ {
var app = context.ApplicationStore.FindApplication(context.ClientId); if (context==null) throw new InvalidOperationException("context == null");
if (app!=null) var app = GetApplication(context.ClientId);
{ if (app == null) return Task.FromResult(0);
Startup.logger.LogInformation($"ValidateClientRedirectUri: Validated ({app.RedirectUri})");
context.Validated(app.RedirectUri); context.Validated(app.RedirectUri);
}
return Task.FromResult(0); return Task.FromResult(0);
} }
@ -28,24 +36,17 @@ namespace Yavsc
if (context.TryGetBasicCredentials(out clientId, out clientSecret) || if (context.TryGetBasicCredentials(out clientId, out clientSecret) ||
context.TryGetFormCredentials(out clientId, out clientSecret)) context.TryGetFormCredentials(out clientId, out clientSecret))
{ {
if (ValidateClientCredentials( var app = GetApplication(clientId);
new OAuthValidateClientCredentialsContext(clientId,clientSecret,context.ApplicationStore) if (app != null && app.Secret == clientSecret)
))
{ {
Startup.logger.LogInformation($"ValidateClientAuthentication: Validated ({clientId})");
context.Validated(); context.Validated();
} else Startup.logger.LogInformation($"ValidateClientAuthentication: KO ({clientId})");
} }
} else Startup.logger.LogInformation($"ValidateClientAuthentication: nor Basic neither Form credential found");
return Task.FromResult(0); return Task.FromResult(0);
} }
private bool ValidateClientCredentials(OAuthValidateClientCredentialsContext context)
{
var authapp = context.ApplicationStore.FindApplication(context.ClientId);
if (authapp == null) return false;
if (authapp.Secret == context.ClientSecret) return true;
return false;
}
private Task GrantResourceOwnerCredentials(OAuthGrantResourceOwnerCredentialsContext context) private Task GrantResourceOwnerCredentials(OAuthGrantResourceOwnerCredentialsContext context)
{ {
ClaimsPrincipal principal = new ClaimsPrincipal(new ClaimsIdentity(new GenericIdentity(context.UserName, OAuthDefaults.AuthenticationType), context.Scope.Select(x => new Claim("urn:oauth:scope", x)))); ClaimsPrincipal principal = new ClaimsPrincipal(new ClaimsIdentity(new GenericIdentity(context.UserName, OAuthDefaults.AuthenticationType), context.Scope.Select(x => new Claim("urn:oauth:scope", x))));
@ -66,6 +67,7 @@ namespace Yavsc
private void CreateAuthenticationCode(AuthenticationTokenCreateContext context) private void CreateAuthenticationCode(AuthenticationTokenCreateContext context)
{ {
Startup.logger.LogInformation("CreateAuthenticationCode");
context.SetToken(Guid.NewGuid().ToString("n") + Guid.NewGuid().ToString("n")); context.SetToken(Guid.NewGuid().ToString("n") + Guid.NewGuid().ToString("n"));
_authenticationCodes[context.Token] = context.SerializeTicket(); _authenticationCodes[context.Token] = context.SerializeTicket();
} }
@ -81,11 +83,15 @@ namespace Yavsc
private void CreateRefreshToken(AuthenticationTokenCreateContext context) private void CreateRefreshToken(AuthenticationTokenCreateContext context)
{ {
var uid = context.Ticket.Principal.GetUserId();
Startup.logger.LogInformation($"CreateRefreshToken for {uid}");
context.SetToken(context.SerializeTicket()); context.SetToken(context.SerializeTicket());
} }
private void ReceiveRefreshToken(AuthenticationTokenReceiveContext context) private void ReceiveRefreshToken(AuthenticationTokenReceiveContext context)
{ {
var uid = context.Ticket.Principal.GetUserId();
Startup.logger.LogInformation($"ReceiveRefreshToken for {uid}");
context.DeserializeTicket(context.Token); context.DeserializeTicket(context.Token);
} }
} }

@ -33,6 +33,7 @@ namespace Yavsc
public partial class Startup public partial class Startup
{ {
public static string ConnectionString { get; private set; } public static string ConnectionString { get; private set; }
private static ILogger logger;
public Startup(IHostingEnvironment env, IApplicationEnvironment appEnv) public Startup(IHostingEnvironment env, IApplicationEnvironment appEnv)
{ {
// Set up configuration sources. // Set up configuration sources.
@ -108,7 +109,7 @@ namespace Yavsc
//})); //}));
}); });
ConfigureOAuthServices(services);
services.Add(ServiceDescriptor.Singleton(typeof(IOptions<SiteSettings>), typeof(OptionsManager<SiteSettings>))); services.Add(ServiceDescriptor.Singleton(typeof(IOptions<SiteSettings>), typeof(OptionsManager<SiteSettings>)));
services.Add(ServiceDescriptor.Singleton(typeof(IOptions<SmtpSettings>), typeof(OptionsManager<SmtpSettings>))); services.Add(ServiceDescriptor.Singleton(typeof(IOptions<SmtpSettings>), typeof(OptionsManager<SmtpSettings>)));
@ -124,22 +125,9 @@ namespace Yavsc
.AddDbContext<ApplicationDbContext>(options => options.UseNpgsql(ConnectionString)) .AddDbContext<ApplicationDbContext>(options => options.UseNpgsql(ConnectionString))
; ;
services.AddIdentity<ApplicationUser, IdentityRole>(
option =>
{
option.User.AllowedUserNameCharacters += " ";
option.User.RequireUniqueEmail = true;
option.Cookies.ApplicationCookie.DataProtectionProvider =
new MonoDataProtectionProvider(Configuration["Site:Title"]);
option.Cookies.ApplicationCookie.LoginPath = new PathString(Constants.LoginPath.Substring(1));
option.Cookies.ApplicationCookie.AccessDeniedPath = new PathString(Constants.AccessDeniedPath.Substring(1));
}
).AddEntityFrameworkStores<ApplicationDbContext>()
.AddTokenProvider<EmailTokenProvider<ApplicationUser>>(Constants.EMailFactor)
.AddTokenProvider<UserTokenProvider>(Constants.DefaultFactor)
;
ConfigureOAuthServices(services);
// .AddTokenProvider<UserTokenProvider>(Constants.SMSFactor) // .AddTokenProvider<UserTokenProvider>(Constants.SMSFactor)
// //
@ -217,8 +205,6 @@ namespace Yavsc
services.AddTransient<Microsoft.AspNet.Authentication.ISecureDataFormat<AuthenticationTicket>, Microsoft.AspNet.Authentication.SecureDataFormat<AuthenticationTicket>>(); services.AddTransient<Microsoft.AspNet.Authentication.ISecureDataFormat<AuthenticationTicket>, Microsoft.AspNet.Authentication.SecureDataFormat<AuthenticationTicket>>();
services.AddTransient<ISecureDataFormat<AuthenticationTicket>, TicketDataFormat>(); services.AddTransient<ISecureDataFormat<AuthenticationTicket>, TicketDataFormat>();
services.AddTransient<IApplicationStore,ApplicationDbContext>();
// Add application services. // Add application services.
services.AddTransient<IEmailSender, AuthMessageSender>(); services.AddTransient<IEmailSender, AuthMessageSender>();
services.AddTransient<IGoogleCloudMessageSender, AuthMessageSender>(); services.AddTransient<IGoogleCloudMessageSender, AuthMessageSender>();
@ -240,12 +226,13 @@ namespace Yavsc
Startup.UserFilesDirName = siteSettings.Value.UserFiles.DirName; Startup.UserFilesDirName = siteSettings.Value.UserFiles.DirName;
loggerFactory.AddConsole(Configuration.GetSection("Logging")); loggerFactory.AddConsole(Configuration.GetSection("Logging"));
loggerFactory.AddDebug(); loggerFactory.AddDebug();
logger = loggerFactory.CreateLogger<Startup>();
app.UseStatusCodePagesWithReExecute("/Home/Status/{0}");
if (env.IsDevelopment()) if (env.IsDevelopment())
{ {
loggerFactory.MinimumLevel = LogLevel.Debug; loggerFactory.MinimumLevel = LogLevel.Debug;
app.UseDeveloperExceptionPage(); app.UseDeveloperExceptionPage();
app.UseStatusCodePagesWithReExecute("/Home/Status/{0}");
app.UseRuntimeInfoPage(); app.UseRuntimeInfoPage();
var epo = new ErrorPageOptions(); var epo = new ErrorPageOptions();
epo.SourceCodeLineCount = 20; epo.SourceCodeLineCount = 20;
@ -289,7 +276,7 @@ namespace Yavsc
app.UseIISPlatformHandler(options => app.UseIISPlatformHandler(options =>
{ {
options.AuthenticationDescriptions.Clear(); options.AuthenticationDescriptions.Clear();
options.AutomaticAuthentication = true; options.AutomaticAuthentication = false;
}); });
ConfigureOAuthApp(app); ConfigureOAuthApp(app);
@ -306,8 +293,9 @@ namespace Yavsc
name: "default", name: "default",
template: "{controller=Home}/{action=Index}/{id?}"); template: "{controller=Home}/{action=Index}/{id?}");
}); });
#if OWIN
app.UseSignalR(); app.UseSignalR();
#endif
} }
// Entry point for the application. // Entry point for the application.

@ -5,25 +5,50 @@ using Microsoft.AspNet.Http.Authentication;
namespace Yavsc.ViewModels.Account namespace Yavsc.ViewModels.Account
{ {
public class LoginViewModel public class SignInViewModel
{ {
/// <summary>
/// Local user's name.
/// </summary>
/// <returns></returns>
[Required] [Required]
public string UserName { get; set; } public string UserName { get; set; }
/// <summary>
/// Local user's password .
/// </summary>
/// <returns></returns>
[Required] [Required]
[DataType(DataType.Password)] [DataType(DataType.Password)]
public string Password { get; set; } public string Password { get; set; }
/// <summary>
/// When true, asks for a two-factor identification
/// </summary>
/// <returns></returns>
[Display(Name = "Remember me?")] [Display(Name = "Remember me?")]
public bool RememberMe { get; set; } public bool RememberMe { get; set; }
/// <summary> /// <summary>
/// This value indicates the OAuth client method recieving the code, /// Indicates the authentication provider'name chosen to authenticate,
/// in case of. /// contains "LOCAL" to choose the local application identity
/// and user password credentials.
/// </summary>
/// <returns></returns>
public string Provider { get; set; }
/// <summary>
/// This value does NOT indicate the OAuth client method recieving the code,
/// but the one called once authorized.
/// </summary> /// </summary>
/// <returns></returns> /// <returns></returns>
public string ReturnUrl { get; set; } public string ReturnUrl { get; set; }
/// <summary>
/// Lists external identity provider descriptions.
/// </summary>
/// <returns>an enumeration of the descriptions.</returns>
public IEnumerable<AuthenticationDescription> ExternalProviders { get; set; } public IEnumerable<AuthenticationDescription> ExternalProviders { get; set; }
} }
} }

@ -1,5 +1,5 @@
@using Microsoft.AspNet.Http @using Microsoft.AspNet.Http
@using System @using System
@using System.Security.Claims @using System.Security.Claims
@{ @{
var error = Context.Items["oauth.Error"]; var error = Context.Items["oauth.Error"];
@ -12,7 +12,7 @@
<title>Authorize Error</title> <title>Authorize Error</title>
</head> </head>
<body> <body>
<h1>Katana.Sandbox.WebServer</h1> <h1>Identification & Authentication server</h1>
<h2>OAuth2 Authorize Error</h2> <h2>OAuth2 Authorize Error</h2>
<p>Error: @error</p> <p>Error: @error</p>
<p>@errorDescription</p> <p>@errorDescription</p>

@ -1,7 +1,7 @@
 
@using Microsoft.AspNet.Http.Authentication @using Microsoft.AspNet.Http.Authentication
@using Yavsc.ViewModels.Account @using Yavsc.ViewModels.Account
@model LoginViewModel @model SignInViewModel
@{ @{
ViewData["Title"] = SR["Log in"]; ViewData["Title"] = SR["Log in"];
} }
@ -38,7 +38,7 @@
</div> </div>
<div class="form-group"> <div class="form-group">
<div class="col-md-offset-2 col-md-10"> <div class="col-md-offset-2 col-md-10">
<button type="submit" class="btn btn-lg btn-success">@SR["Login"]</button> <button type="submit" class="btn btn-lg btn-success" name="submit.Signin">@SR["Login"]</button>
</div> </div>
</div> </div>
<p> <p>
@ -67,10 +67,10 @@
else else
{ {
@foreach (var description in Model.ExternalProviders) { @foreach (var description in Model.ExternalProviders) {
<form action="@Constants.LoginPath" method="post"> <form action="@Constants.ExternalLoginPath" method="post">
<input type="hidden" name="Provider" value="@description.AuthenticationScheme" /> <input type="hidden" name="Provider" value="@description.AuthenticationScheme" />
<input type="hidden" name="ReturnUrl" value="@Model.ReturnUrl" /> <input type="hidden" name="ReturnUrl" value="@Model.ReturnUrl" />
<button class="btn btn-lg btn-success" type="submit">@SR["Connect using"] @description.DisplayName</button> <button class="btn btn-lg btn-success" type="submit" name="Submit.Login">@SR["Connect using"] @description.DisplayName</button>
@Html.AntiForgeryToken() @Html.AntiForgeryToken()
</form> </form>
} }

@ -2,6 +2,7 @@
@{ @{
ViewBag.Title = "Oops!"; ViewBag.Title = "Oops!";
} }
<h1>@ViewBag.Title</h1>
<h2 class="text-danger">Your request cannot be served</h2> <h2 class="text-danger">Your request cannot be served</h2>
<code> <code>

@ -19,7 +19,7 @@ else
<ul class="nav navbar-nav navbar-right"> <ul class="nav navbar-nav navbar-right">
<li><a class="navbar-link" asp-controller="Account" asp-action="Register" asp-route-returnurl="@Url.Action()" >@SR["Register"]</a></li> <li><a class="navbar-link" asp-controller="Account" asp-action="Register" asp-route-returnurl="@Url.Action()" >@SR["Register"]</a></li>
<li><a class="navbar-link" asp-controller="Account" asp-action="Login" asp-route-returnurl="@Url.Action()" >@SR["Login"]</a></li> <li><a class="navbar-link" asp-controller="Account" asp-action="SignIn" asp-route-returnurl="@Url.Action()" >@SR["Login"]</a></li>
</ul> </ul>
} }

@ -67,9 +67,7 @@
"Microsoft.AspNet.Localization": "1.0.0-rc1-final", "Microsoft.AspNet.Localization": "1.0.0-rc1-final",
"Microsoft.AspNet.Mvc": "6.0.0-rc1-*", "Microsoft.AspNet.Mvc": "6.0.0-rc1-*",
"Microsoft.AspNet.Mvc.TagHelpers": "6.0.0-rc1-*", "Microsoft.AspNet.Mvc.TagHelpers": "6.0.0-rc1-*",
"Microsoft.AspNet.Owin": "1.0.0-rc1-final",
"Microsoft.AspNet.Server.Kestrel": "1.0.0-rc1-final", "Microsoft.AspNet.Server.Kestrel": "1.0.0-rc1-final",
"Microsoft.AspNet.SignalR.Owin": "1.2.2",
"Microsoft.AspNet.SignalR.Core": "2.2.0", "Microsoft.AspNet.SignalR.Core": "2.2.0",
"Microsoft.AspNet.Server.WebListener": "1.0.0-rc1-final", "Microsoft.AspNet.Server.WebListener": "1.0.0-rc1-final",
"Microsoft.AspNet.StaticFiles": "1.0.0-rc1-*", "Microsoft.AspNet.StaticFiles": "1.0.0-rc1-*",

File diff suppressed because it is too large Load Diff
Loading…