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

This commit is contained in:
2016-06-10 01:14:53 +02:00
parent 4b8c5cc984
commit 729e7648ff
26 changed files with 7069 additions and 1423 deletions

View File

@ -4,6 +4,8 @@ using Microsoft.AspNet.Authentication;
using Microsoft.AspNet.Authentication.OAuth;
using Microsoft.AspNet.Builder;
using Microsoft.AspNet.Http;
using Microsoft.AspNet.Identity;
using Microsoft.AspNet.Identity.EntityFramework;
using Microsoft.Extensions.DependencyInjection;
using Microsoft.Extensions.OptionsModel;
using Microsoft.Extensions.WebEncoders;
@ -19,30 +21,61 @@ namespace Yavsc
private void ConfigureOAuthServices(IServiceCollection services)
{
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>)));
// used by the YavscGoogleOAuth middelware (TODO drop it)
services.AddTransient<Microsoft.Extensions.WebEncoders.UrlEncoder, UrlEncoder>();
/* Obsolete:
var keyParamsFileInfo =
new FileInfo(Configuration["DataProtection:RSAParamFile"]);
var keyParams = (keyParamsFileInfo.Exists) ?
RSAKeyUtils.GetKeyParameters(keyParamsFileInfo.Name) :
RSAKeyUtils.GenerateKeyAndSave(keyParamsFileInfo.Name);
key = new RsaSecurityKey(keyParams);
var keyParamsFileInfo =
new FileInfo(Configuration["DataProtection:RSAParamFile"]);
var keyParams = (keyParamsFileInfo.Exists) ?
RSAKeyUtils.GetKeyParameters(keyParamsFileInfo.Name) :
RSAKeyUtils.GenerateKeyAndSave(keyParamsFileInfo.Name);
key = new RsaSecurityKey(keyParams);
services.Configure<TokenAuthOptions>(
to =>
{
to.Audience = Configuration["Site:Audience"];
to.Issuer = Configuration["Site:Authority"];
to.SigningCredentials =
new SigningCredentials(key, SecurityAlgorithms.RsaSha256Signature);
}
); */
services.Configure<TokenAuthOptions>(
to =>
{
to.Audience = Configuration["Site:Audience"];
to.Issuer = Configuration["Site:Authority"];
to.SigningCredentials =
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)
{
@ -51,9 +84,10 @@ namespace Yavsc
app.UseCookieAuthentication(options =>
{
options.AuthenticationScheme = Constants.ExternalAuthenticationSheme;
options.AutomaticAuthenticate = false;
options.AutomaticAuthenticate = true;
options.ExpireTimeSpan = TimeSpan.FromMinutes(5);
options.LoginPath = new PathString(Constants.LoginPath.Substring(1));
options.AccessDeniedPath = new PathString(Constants.AccessDeniedPath.Substring(1));
});
var gvents = new OAuthEvents();
@ -134,6 +168,7 @@ namespace Yavsc
context.Identity = identity;
}
}; */
/*
app.UseOAuthAuthorizationServer(
options =>
@ -141,10 +176,8 @@ namespace Yavsc
options.AuthorizeEndpointPath = new PathString(Constants.AuthorizePath.Substring(1));
options.TokenEndpointPath = new PathString(Constants.TokenPath.Substring(1));
options.ApplicationCanDisplayErrors = true;
#if DEBUG
options.AllowInsecureHttp = true;
#endif
options.AuthenticationScheme = Constants.ApplicationAuthenticationSheme;
options.Provider = new OAuthAuthorizationServerProvider
{
@ -166,9 +199,10 @@ namespace Yavsc
OnReceive = ReceiveRefreshToken,
};
options.AutomaticAuthenticate = false;
}
);
options.AutomaticAuthenticate = true;
options.AutomaticChallenge = true;
}
);*/
}
}
}

View File

@ -4,21 +4,29 @@ using System.Linq;
using System.Security.Claims;
using System.Security.Principal;
using System.Threading.Tasks;
using Microsoft.Extensions.Logging;
using OAuth.AspNet.AuthServer;
using Yavsc.Models;
namespace Yavsc
{
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 Task ValidateClientRedirectUri(OAuthValidateClientRedirectUriContext context)
{
var app = context.ApplicationStore.FindApplication(context.ClientId);
if (app!=null)
{
context.Validated(app.RedirectUri);
}
if (context==null) throw new InvalidOperationException("context == null");
var app = GetApplication(context.ClientId);
if (app == null) return Task.FromResult(0);
Startup.logger.LogInformation($"ValidateClientRedirectUri: Validated ({app.RedirectUri})");
context.Validated(app.RedirectUri);
return Task.FromResult(0);
}
@ -28,24 +36,17 @@ namespace Yavsc
if (context.TryGetBasicCredentials(out clientId, out clientSecret) ||
context.TryGetFormCredentials(out clientId, out clientSecret))
{
if (ValidateClientCredentials(
new OAuthValidateClientCredentialsContext(clientId,clientSecret,context.ApplicationStore)
))
var app = GetApplication(clientId);
if (app != null && app.Secret == clientSecret)
{
Startup.logger.LogInformation($"ValidateClientAuthentication: Validated ({clientId})");
context.Validated();
}
} else Startup.logger.LogInformation($"ValidateClientAuthentication: KO ({clientId})");
}
else Startup.logger.LogInformation($"ValidateClientAuthentication: nor Basic neither Form credential found");
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)
{
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)
{
Startup.logger.LogInformation("CreateAuthenticationCode");
context.SetToken(Guid.NewGuid().ToString("n") + Guid.NewGuid().ToString("n"));
_authenticationCodes[context.Token] = context.SerializeTicket();
}
@ -81,11 +83,15 @@ namespace Yavsc
private void CreateRefreshToken(AuthenticationTokenCreateContext context)
{
var uid = context.Ticket.Principal.GetUserId();
Startup.logger.LogInformation($"CreateRefreshToken for {uid}");
context.SetToken(context.SerializeTicket());
}
private void ReceiveRefreshToken(AuthenticationTokenReceiveContext context)
{
var uid = context.Ticket.Principal.GetUserId();
Startup.logger.LogInformation($"ReceiveRefreshToken for {uid}");
context.DeserializeTicket(context.Token);
}
}

View File

@ -33,6 +33,7 @@ namespace Yavsc
public partial class Startup
{
public static string ConnectionString { get; private set; }
private static ILogger logger;
public Startup(IHostingEnvironment env, IApplicationEnvironment appEnv)
{
// 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<SmtpSettings>), typeof(OptionsManager<SmtpSettings>)));
@ -124,22 +125,9 @@ namespace Yavsc
.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)
//
@ -217,8 +205,6 @@ namespace Yavsc
services.AddTransient<Microsoft.AspNet.Authentication.ISecureDataFormat<AuthenticationTicket>, Microsoft.AspNet.Authentication.SecureDataFormat<AuthenticationTicket>>();
services.AddTransient<ISecureDataFormat<AuthenticationTicket>, TicketDataFormat>();
services.AddTransient<IApplicationStore,ApplicationDbContext>();
// Add application services.
services.AddTransient<IEmailSender, AuthMessageSender>();
services.AddTransient<IGoogleCloudMessageSender, AuthMessageSender>();
@ -240,12 +226,13 @@ namespace Yavsc
Startup.UserFilesDirName = siteSettings.Value.UserFiles.DirName;
loggerFactory.AddConsole(Configuration.GetSection("Logging"));
loggerFactory.AddDebug();
logger = loggerFactory.CreateLogger<Startup>();
app.UseStatusCodePagesWithReExecute("/Home/Status/{0}");
if (env.IsDevelopment())
{
loggerFactory.MinimumLevel = LogLevel.Debug;
app.UseDeveloperExceptionPage();
app.UseStatusCodePagesWithReExecute("/Home/Status/{0}");
app.UseRuntimeInfoPage();
var epo = new ErrorPageOptions();
epo.SourceCodeLineCount = 20;
@ -289,7 +276,7 @@ namespace Yavsc
app.UseIISPlatformHandler(options =>
{
options.AuthenticationDescriptions.Clear();
options.AutomaticAuthentication = true;
options.AutomaticAuthentication = false;
});
ConfigureOAuthApp(app);
@ -306,8 +293,9 @@ namespace Yavsc
name: "default",
template: "{controller=Home}/{action=Index}/{id?}");
});
#if OWIN
app.UseSignalR();
#endif
}
// Entry point for the application.