Merge branch 'vnext' of github.com:pazof/yavsc into vnext

main
Paul Schneider 7 years ago
commit 242a18f7b8
1 changed files with 160 additions and 180 deletions

@ -1,33 +1,31 @@
using System; using System;
using System.Security.Claims; using System.Security.Claims;
using Google.Apis.Auth.OAuth2.Responses;
using Google.Apis.Util.Store;
using Microsoft.AspNet.Authentication; using Microsoft.AspNet.Authentication;
using Microsoft.AspNet.Authentication.Cookies; using Microsoft.AspNet.Authentication.Cookies;
using Microsoft.AspNet.Authentication.Facebook; using Microsoft.AspNet.Authentication.Facebook;
using Microsoft.AspNet.Authentication.Twitter;
using Microsoft.AspNet.Authentication.JwtBearer; using Microsoft.AspNet.Authentication.JwtBearer;
using Microsoft.AspNet.Authentication.OAuth; using Microsoft.AspNet.Authentication.OAuth;
using Microsoft.AspNet.Authentication.Twitter;
using Microsoft.AspNet.Builder; using Microsoft.AspNet.Builder;
using Microsoft.AspNet.Http; using Microsoft.AspNet.Http;
using Microsoft.AspNet.Identity; using Microsoft.AspNet.Identity;
using Microsoft.AspNet.Identity.EntityFramework; using Microsoft.AspNet.Identity.EntityFramework;
using Microsoft.Extensions.DependencyInjection; using Microsoft.Extensions.DependencyInjection;
using Microsoft.Extensions.Logging;
using Microsoft.Extensions.OptionsModel; using Microsoft.Extensions.OptionsModel;
using Microsoft.Extensions.WebEncoders; using Microsoft.Extensions.WebEncoders;
using OAuth.AspNet.AuthServer; using OAuth.AspNet.AuthServer;
using OAuth.AspNet.Tokens; using OAuth.AspNet.Tokens;
using Google.Apis.Util.Store;
using Microsoft.Extensions.Logging;
using Google.Apis.Auth.OAuth2.Responses;
namespace Yavsc namespace Yavsc {
{
using Auth; using Auth;
using Extensions; using Extensions;
using Models;
using Helpers.Google; using Helpers.Google;
using Models;
public partial class Startup public partial class Startup {
{
public static CookieAuthenticationOptions ExternalCookieAppOptions { get; private set; } public static CookieAuthenticationOptions ExternalCookieAppOptions { get; private set; }
public static IdentityOptions IdentityAppOptions { get; set; } public static IdentityOptions IdentityAppOptions { get; set; }
@ -36,194 +34,176 @@ namespace Yavsc
public static TwitterOptions TwitterAppOptions { get; private set; } public static TwitterOptions TwitterAppOptions { get; private set; }
public static OAuthAuthorizationServerOptions OAuthServerAppOptions { get; private set; } public static OAuthAuthorizationServerOptions OAuthServerAppOptions { get; private set; }
public static YavscGoogleOptions YavscGoogleAppOptions { get; private set; } public static YavscGoogleOptions YavscGoogleAppOptions { get; private set; }
public static MonoDataProtectionProvider ProtectionProvider { get; private set; } public static MonoDataProtectionProvider ProtectionProvider { get; private set; }
// public static CookieAuthenticationOptions BearerCookieOptions { get; private set; } // public static CookieAuthenticationOptions BearerCookieOptions { get; private set; }
private void ConfigureOAuthServices(IServiceCollection services) private void ConfigureOAuthServices (IServiceCollection services) {
{ services.Configure<SharedAuthenticationOptions> (options => options.SignInScheme = Constants.ApplicationAuthenticationSheme);
services.Configure<SharedAuthenticationOptions>(options => options.SignInScheme = Constants.ApplicationAuthenticationSheme);
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> ();
services.AddAuthentication(options => services.AddAuthentication (options => {
{
options.SignInScheme = Constants.ExternalAuthenticationSheme; options.SignInScheme = Constants.ExternalAuthenticationSheme;
}); });
ProtectionProvider = new MonoDataProtectionProvider(Configuration["Site:Title"]); ; ProtectionProvider = new MonoDataProtectionProvider (Configuration["Site:Title"]);;
services.AddInstance<MonoDataProtectionProvider> services.AddInstance<MonoDataProtectionProvider>
(ProtectionProvider); (ProtectionProvider);
services.AddIdentity<ApplicationUser, IdentityRole>( services.AddIdentity<ApplicationUser, IdentityRole> (
option => option => {
{ IdentityAppOptions = option;
IdentityAppOptions = option; option.User.AllowedUserNameCharacters += " ";
option.User.AllowedUserNameCharacters += " "; option.User.RequireUniqueEmail = true;
option.User.RequireUniqueEmail = true; // option.Cookies.ApplicationCookieAuthenticationScheme = Constants.ApplicationAuthenticationSheme;
// option.Cookies.ApplicationCookieAuthenticationScheme = Constants.ApplicationAuthenticationSheme; option.Cookies.ApplicationCookie.LoginPath = "/signin";
option.Cookies.ApplicationCookie.LoginPath = "/signin"; // option.Cookies.ApplicationCookie.AuthenticationScheme = Constants.ApplicationAuthenticationSheme;
// option.Cookies.ApplicationCookie.AuthenticationScheme = Constants.ApplicationAuthenticationSheme; /*
/* option.Cookies.ApplicationCookie.DataProtectionProvider = protector;
option.Cookies.ApplicationCookie.DataProtectionProvider = protector; option.Cookies.ApplicationCookie.LoginPath = new PathString(Constants.LoginPath.Substring(1));
option.Cookies.ApplicationCookie.LoginPath = new PathString(Constants.LoginPath.Substring(1)); option.Cookies.ApplicationCookie.AccessDeniedPath = new PathString(Constants.AccessDeniedPath.Substring(1));
option.Cookies.ApplicationCookie.AccessDeniedPath = new PathString(Constants.AccessDeniedPath.Substring(1)); option.Cookies.ApplicationCookie.AutomaticAuthenticate = true;
option.Cookies.ApplicationCookie.AutomaticAuthenticate = true; option.Cookies.ApplicationCookie.AuthenticationScheme = Constants.ApplicationAuthenticationSheme;
option.Cookies.ApplicationCookie.AuthenticationScheme = Constants.ApplicationAuthenticationSheme; option.Cookies.ApplicationCookieAuthenticationScheme = Constants.ApplicationAuthenticationSheme;
option.Cookies.ApplicationCookieAuthenticationScheme = Constants.ApplicationAuthenticationSheme; option.Cookies.TwoFactorRememberMeCookie.ExpireTimeSpan = TimeSpan.FromDays(30);
option.Cookies.TwoFactorRememberMeCookie.ExpireTimeSpan = TimeSpan.FromDays(30); option.Cookies.TwoFactorRememberMeCookie.DataProtectionProvider = protector;
option.Cookies.TwoFactorRememberMeCookie.DataProtectionProvider = protector; option.Cookies.ExternalCookieAuthenticationScheme = Constants.ExternalAuthenticationSheme;
option.Cookies.ExternalCookieAuthenticationScheme = Constants.ExternalAuthenticationSheme; option.Cookies.ExternalCookie.AutomaticAuthenticate = true;
option.Cookies.ExternalCookie.AutomaticAuthenticate = true; option.Cookies.ExternalCookie.AuthenticationScheme = Constants.ExternalAuthenticationSheme;
option.Cookies.ExternalCookie.AuthenticationScheme = Constants.ExternalAuthenticationSheme; option.Cookies.ExternalCookie.DataProtectionProvider = protector;
option.Cookies.ExternalCookie.DataProtectionProvider = protector; */
*/ }
} ).AddEntityFrameworkStores<ApplicationDbContext> ()
).AddEntityFrameworkStores<ApplicationDbContext>() .AddTokenProvider<EmailTokenProvider<ApplicationUser>> (Constants.DefaultFactor)
.AddTokenProvider<EmailTokenProvider<ApplicationUser>>(Constants.DefaultFactor) // .AddTokenProvider<UserTokenProvider>(Constants.DefaultFactor)
// .AddTokenProvider<UserTokenProvider>(Constants.DefaultFactor)
// .AddTokenProvider<UserTokenProvider>(Constants.SMSFactor) // .AddTokenProvider<UserTokenProvider>(Constants.SMSFactor)
// .AddTokenProvider<UserTokenProvider>(Constants.EMailFactor) // .AddTokenProvider<UserTokenProvider>(Constants.EMailFactor)
// .AddTokenProvider<UserTokenProvider>(Constants.AppFactor) // .AddTokenProvider<UserTokenProvider>(Constants.AppFactor)
// .AddDefaultTokenProviders() // .AddDefaultTokenProviders()
; ;
} }
private void ConfigureOAuthApp(IApplicationBuilder app, private void ConfigureOAuthApp (IApplicationBuilder app,
SiteSettings settingsOptions, ILogger logger) SiteSettings settingsOptions, ILogger logger) {
{
app.UseIdentity ();
app.UseIdentity(); app.UseWhen (context => context.Request.Path.StartsWithSegments ("/api"),
app.UseWhen(context => context.Request.Path.StartsWithSegments("/api"), branch => {
branch => branch.UseJwtBearerAuthentication (
{ options => {
branch.UseJwtBearerAuthentication( options.AuthenticationScheme = JwtBearerDefaults.AuthenticationScheme;
options => options.AutomaticAuthenticate = true;
{ options.SecurityTokenValidators.Clear ();
options.AuthenticationScheme = JwtBearerDefaults.AuthenticationScheme; options.SecurityTokenValidators.Add (new TicketDataFormatTokenValidator (
options.AutomaticAuthenticate = true; ProtectionProvider
options.SecurityTokenValidators.Clear(); ));
options.SecurityTokenValidators.Add(new TicketDataFormatTokenValidator( }
ProtectionProvider );
));
} });
); app.UseWhen (context => !context.Request.Path.StartsWithSegments ("/api"),
branch => {
}); // External authentication shared cookie:
app.UseWhen(context => !context.Request.Path.StartsWithSegments("/api"), branch.UseCookieAuthentication (options => {
branch => ExternalCookieAppOptions = options;
{ options.AuthenticationScheme = Constants.ExternalAuthenticationSheme;
// External authentication shared cookie: options.AutomaticAuthenticate = true;
branch.UseCookieAuthentication(options => options.ExpireTimeSpan = TimeSpan.FromMinutes (5);
{ options.LoginPath = new PathString (Constants.LoginPath.Substring (1));
ExternalCookieAppOptions = options; // TODO implement an access denied page
options.AuthenticationScheme = Constants.ExternalAuthenticationSheme; options.AccessDeniedPath = new PathString (Constants.LoginPath.Substring (1));
options.AutomaticAuthenticate = true; });
options.ExpireTimeSpan = TimeSpan.FromMinutes(5);
options.LoginPath = new PathString(Constants.LoginPath.Substring(1)); YavscGoogleAppOptions = new YavscGoogleOptions {
// TODO implement an access denied page ClientId = GoogleWebClientConfiguration["web:client_id"],
options.AccessDeniedPath = new PathString(Constants.LoginPath.Substring(1)); ClientSecret = GoogleWebClientConfiguration["web:client_secret"],
}); AccessType = "offline",
Scope = {
"profile",
"https://www.googleapis.com/auth/plus.login",
YavscGoogleAppOptions = new YavscGoogleOptions "https://www.googleapis.com/auth/admin.directory.resource.calendar",
{ "https://www.googleapis.com/auth/calendar",
ClientId = GoogleWebClientConfiguration ["web:client_id"], "https://www.googleapis.com/auth/calendar.events"
ClientSecret = GoogleWebClientConfiguration ["web:client_secret"], },
AccessType = "offline", SaveTokensAsClaims = true,
Scope = { "profile", "https://www.googleapis.com/auth/plus.login", UserInformationEndpoint = "https://www.googleapis.com/plus/v1/people/me",
"https://www.googleapis.com/auth/admin.directory.resource.calendar", Events = new OAuthEvents {
"https://www.googleapis.com/auth/calendar", OnCreatingTicket = async context => {
"https://www.googleapis.com/auth/calendar.events"}, using (var serviceScope = app.ApplicationServices.GetRequiredService<IServiceScopeFactory> ()
SaveTokensAsClaims = true, .CreateScope ()) {
UserInformationEndpoint = "https://www.googleapis.com/plus/v1/people/me", var gcontext = context as GoogleOAuthCreatingTicketContext;
Events = new OAuthEvents context.Identity.AddClaim (new Claim (YavscClaimTypes.GoogleUserId, gcontext.GoogleUserId));
{ var dbContext = serviceScope.ServiceProvider.GetService<ApplicationDbContext> ();
OnCreatingTicket = async context =>
{ var store = serviceScope.ServiceProvider.GetService<IDataStore> ();
using (var serviceScope = app.ApplicationServices.GetRequiredService<IServiceScopeFactory>() await store.StoreAsync (gcontext.GoogleUserId, new TokenResponse {
.CreateScope()) AccessToken = gcontext.TokenResponse.AccessToken,
{ RefreshToken = gcontext.TokenResponse.RefreshToken,
var gcontext = context as GoogleOAuthCreatingTicketContext; TokenType = gcontext.TokenResponse.TokenType,
context.Identity.AddClaim(new Claim(YavscClaimTypes.GoogleUserId, gcontext.GoogleUserId)); ExpiresInSeconds = int.Parse (gcontext.TokenResponse.ExpiresIn),
var dbContext = serviceScope.ServiceProvider.GetService<ApplicationDbContext>(); IssuedUtc = DateTime.Now
});
var store = serviceScope.ServiceProvider.GetService<IDataStore>(); await dbContext.StoreTokenAsync (gcontext.GoogleUserId,
await store.StoreAsync(gcontext.GoogleUserId, new TokenResponse { gcontext.TokenResponse.Response,
AccessToken = gcontext.TokenResponse.AccessToken, gcontext.TokenResponse.AccessToken,
RefreshToken = gcontext.TokenResponse.RefreshToken, gcontext.TokenResponse.TokenType,
TokenType = gcontext.TokenResponse.TokenType, gcontext.TokenResponse.RefreshToken,
ExpiresInSeconds = int.Parse(gcontext.TokenResponse.ExpiresIn), gcontext.TokenResponse.ExpiresIn);
IssuedUtc = DateTime.Now
}); }
await dbContext.StoreTokenAsync (gcontext.GoogleUserId, }
gcontext.TokenResponse.Response, }
gcontext.TokenResponse.AccessToken, };
gcontext.TokenResponse.TokenType,
gcontext.TokenResponse.RefreshToken, branch.UseMiddleware<Yavsc.Auth.GoogleMiddleware> (YavscGoogleAppOptions);
gcontext.TokenResponse.ExpiresIn); /* FIXME 403
} branch.UseTwitterAuthentication(options=>
} {
} TwitterAppOptions = options;
}; options.ConsumerKey = Configuration["Authentication:Twitter:ClientId"];
options.ConsumerSecret = Configuration["Authentication:Twitter:ClientSecret"];
branch.UseMiddleware<Yavsc.Auth.GoogleMiddleware>(YavscGoogleAppOptions); }); */
/* FIXME 403
branch.UseOAuthAuthorizationServer (
branch.UseTwitterAuthentication(options=>
{ options => {
TwitterAppOptions = options; OAuthServerAppOptions = options;
options.ConsumerKey = Configuration["Authentication:Twitter:ClientId"]; options.AuthorizeEndpointPath = new PathString (Constants.AuthorizePath.Substring (1));
options.ConsumerSecret = Configuration["Authentication:Twitter:ClientSecret"]; options.TokenEndpointPath = new PathString (Constants.TokenPath.Substring (1));
}); */ options.ApplicationCanDisplayErrors = true;
options.AllowInsecureHttp = true;
options.AuthenticationScheme = OAuthDefaults.AuthenticationType;
branch.UseOAuthAuthorizationServer( options.TokenDataProtector = ProtectionProvider.CreateProtector ("Bearer protection");
options => options.Provider = new OAuthAuthorizationServerProvider {
{ OnValidateClientRedirectUri = ValidateClientRedirectUri,
OAuthServerAppOptions = options; OnValidateClientAuthentication = ValidateClientAuthentication,
options.AuthorizeEndpointPath = new PathString(Constants.AuthorizePath.Substring(1)); OnGrantResourceOwnerCredentials = GrantResourceOwnerCredentials,
options.TokenEndpointPath = new PathString(Constants.TokenPath.Substring(1)); OnGrantClientCredentials = GrantClientCredetails
options.ApplicationCanDisplayErrors = true; };
options.AllowInsecureHttp = true;
options.AuthenticationScheme = OAuthDefaults.AuthenticationType; options.AuthorizationCodeProvider = new AuthenticationTokenProvider {
options.TokenDataProtector = ProtectionProvider.CreateProtector("Bearer protection"); OnCreate = CreateAuthenticationCode,
OnReceive = ReceiveAuthenticationCode,
options.Provider = new OAuthAuthorizationServerProvider };
{
OnValidateClientRedirectUri = ValidateClientRedirectUri, options.RefreshTokenProvider = new AuthenticationTokenProvider {
OnValidateClientAuthentication = ValidateClientAuthentication, OnCreate = CreateRefreshToken,
OnGrantResourceOwnerCredentials = GrantResourceOwnerCredentials, OnReceive = ReceiveRefreshToken,
OnGrantClientCredentials = GrantClientCredetails };
};
options.AutomaticAuthenticate = true;
options.AuthorizationCodeProvider = new AuthenticationTokenProvider options.AutomaticChallenge = true;
{ }
OnCreate = CreateAuthenticationCode, );
OnReceive = ReceiveAuthenticationCode, });
};
Environment.SetEnvironmentVariable ("GOOGLE_APPLICATION_CREDENTIALS", "google-secret.json");
options.RefreshTokenProvider = new AuthenticationTokenProvider
{
OnCreate = CreateRefreshToken,
OnReceive = ReceiveRefreshToken,
};
options.AutomaticAuthenticate = true;
options.AutomaticChallenge = true;
}
);
});
Environment.SetEnvironmentVariable ("GOOGLE_APPLICATION_CREDENTIALS", "google-secret.json");
} }
} }
} }
Loading…