do make, from there too.

vnext
Paul Schneider 6 years ago
parent 562d1fcfae
commit e9eb49d112
2 changed files with 187 additions and 157 deletions

@ -1,3 +1,11 @@
test:
make -C scripts/build/make test
web: web:
make -C scripts/build/make watch make -C scripts/build/make watch
push:
make -C src/Yavsc pushInProd

@ -1,31 +1,33 @@
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 Helpers.Google;
using Models; using Models;
using Helpers.Google;
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; }
@ -34,173 +36,193 @@ 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; {
option.User.AllowedUserNameCharacters += " "; IdentityAppOptions = option;
option.User.RequireUniqueEmail = true; option.User.AllowedUserNameCharacters += " ";
// option.Cookies.ApplicationCookieAuthenticationScheme = Constants.ApplicationAuthenticationSheme; option.User.RequireUniqueEmail = true;
option.Cookies.ApplicationCookie.LoginPath = "/signin"; // option.Cookies.ApplicationCookieAuthenticationScheme = Constants.ApplicationAuthenticationSheme;
// option.Cookies.ApplicationCookie.AuthenticationScheme = Constants.ApplicationAuthenticationSheme; option.Cookies.ApplicationCookie.LoginPath = "/signin";
/* // option.Cookies.ApplicationCookie.AuthenticationScheme = Constants.ApplicationAuthenticationSheme;
option.Cookies.ApplicationCookie.DataProtectionProvider = protector; /*
option.Cookies.ApplicationCookie.LoginPath = new PathString(Constants.LoginPath.Substring(1)); option.Cookies.ApplicationCookie.DataProtectionProvider = protector;
option.Cookies.ApplicationCookie.AccessDeniedPath = new PathString(Constants.AccessDeniedPath.Substring(1)); option.Cookies.ApplicationCookie.LoginPath = new PathString(Constants.LoginPath.Substring(1));
option.Cookies.ApplicationCookie.AutomaticAuthenticate = true; option.Cookies.ApplicationCookie.AccessDeniedPath = new PathString(Constants.AccessDeniedPath.Substring(1));
option.Cookies.ApplicationCookie.AuthenticationScheme = Constants.ApplicationAuthenticationSheme; option.Cookies.ApplicationCookie.AutomaticAuthenticate = true;
option.Cookies.ApplicationCookieAuthenticationScheme = Constants.ApplicationAuthenticationSheme; option.Cookies.ApplicationCookie.AuthenticationScheme = Constants.ApplicationAuthenticationSheme;
option.Cookies.TwoFactorRememberMeCookie.ExpireTimeSpan = TimeSpan.FromDays(30); option.Cookies.ApplicationCookieAuthenticationScheme = Constants.ApplicationAuthenticationSheme;
option.Cookies.TwoFactorRememberMeCookie.DataProtectionProvider = protector; option.Cookies.TwoFactorRememberMeCookie.ExpireTimeSpan = TimeSpan.FromDays(30);
option.Cookies.ExternalCookieAuthenticationScheme = Constants.ExternalAuthenticationSheme; option.Cookies.TwoFactorRememberMeCookie.DataProtectionProvider = protector;
option.Cookies.ExternalCookie.AutomaticAuthenticate = true; option.Cookies.ExternalCookieAuthenticationScheme = Constants.ExternalAuthenticationSheme;
option.Cookies.ExternalCookie.AuthenticationScheme = Constants.ExternalAuthenticationSheme; option.Cookies.ExternalCookie.AutomaticAuthenticate = true;
option.Cookies.ExternalCookie.DataProtectionProvider = protector; option.Cookies.ExternalCookie.AuthenticationScheme = Constants.ExternalAuthenticationSheme;
*/ option.Cookies.ExternalCookie.DataProtectionProvider = protector;
} */
).AddEntityFrameworkStores<ApplicationDbContext> () }
.AddTokenProvider<EmailTokenProvider<ApplicationUser>> (Constants.DefaultFactor) ).AddEntityFrameworkStores<ApplicationDbContext>()
// .AddTokenProvider<UserTokenProvider>(Constants.DefaultFactor) .AddTokenProvider<EmailTokenProvider<ApplicationUser>>(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.UseWhen (context => context.Request.Path.StartsWithSegments ("/api"), app.UseIdentity();
branch => { app.UseWhen(context => context.Request.Path.StartsWithSegments("/api"),
branch.UseJwtBearerAuthentication ( branch =>
options => { {
options.AuthenticationScheme = JwtBearerDefaults.AuthenticationScheme; branch.UseJwtBearerAuthentication(
options.AutomaticAuthenticate = true; options =>
options.SecurityTokenValidators.Clear (); {
options.SecurityTokenValidators.Add (new TicketDataFormatTokenValidator ( options.AuthenticationScheme = JwtBearerDefaults.AuthenticationScheme;
ProtectionProvider options.AutomaticAuthenticate = true;
)); options.SecurityTokenValidators.Clear();
} options.SecurityTokenValidators.Add(new TicketDataFormatTokenValidator(
); ProtectionProvider
));
// External authentication shared cookie: }
branch.UseCookieAuthentication (options => { );
ExternalCookieAppOptions = options;
options.AuthenticationScheme = Constants.ExternalAuthenticationSheme; });
options.AutomaticAuthenticate = true; app.UseWhen(context => !context.Request.Path.StartsWithSegments("/api"),
options.ExpireTimeSpan = TimeSpan.FromMinutes (5); branch =>
options.LoginPath = new PathString (Constants.LoginPath.Substring (1)); {
// TODO implement an access denied page // External authentication shared cookie:
options.AccessDeniedPath = new PathString (Constants.LoginPath.Substring (1)); branch.UseCookieAuthentication(options =>
}); {
ExternalCookieAppOptions = options;
YavscGoogleAppOptions = new YavscGoogleOptions { options.AuthenticationScheme = Constants.ExternalAuthenticationSheme;
ClientId = GoogleWebClientConfiguration["web:client_id"], options.AutomaticAuthenticate = true;
ClientSecret = GoogleWebClientConfiguration["web:client_secret"], options.ExpireTimeSpan = TimeSpan.FromMinutes(5);
AccessType = "offline", options.LoginPath = new PathString(Constants.LoginPath.Substring(1));
Scope = { // TODO implement an access denied page
"profile", options.AccessDeniedPath = new PathString(Constants.LoginPath.Substring(1));
"https://www.googleapis.com/auth/plus.login", });
"https://www.googleapis.com/auth/admin.directory.resource.calendar",
"https://www.googleapis.com/auth/calendar",
"https://www.googleapis.com/auth/calendar.events"
}, YavscGoogleAppOptions = new YavscGoogleOptions
SaveTokensAsClaims = true, {
UserInformationEndpoint = "https://www.googleapis.com/plus/v1/people/me", ClientId = GoogleWebClientConfiguration ["web:client_id"],
Events = new OAuthEvents { ClientSecret = GoogleWebClientConfiguration ["web:client_secret"],
OnCreatingTicket = async context => { AccessType = "offline",
using (var serviceScope = app.ApplicationServices.GetRequiredService<IServiceScopeFactory> () Scope = { "profile", "https://www.googleapis.com/auth/plus.login",
.CreateScope ()) { "https://www.googleapis.com/auth/admin.directory.resource.calendar",
var gcontext = context as GoogleOAuthCreatingTicketContext; "https://www.googleapis.com/auth/calendar",
context.Identity.AddClaim (new Claim (YavscClaimTypes.GoogleUserId, gcontext.GoogleUserId)); "https://www.googleapis.com/auth/calendar.events"},
var dbContext = serviceScope.ServiceProvider.GetService<ApplicationDbContext> (); SaveTokensAsClaims = true,
UserInformationEndpoint = "https://www.googleapis.com/plus/v1/people/me",
var store = serviceScope.ServiceProvider.GetService<IDataStore> (); Events = new OAuthEvents
await store.StoreAsync (gcontext.GoogleUserId, new TokenResponse { {
AccessToken = gcontext.TokenResponse.AccessToken, OnCreatingTicket = async context =>
RefreshToken = gcontext.TokenResponse.RefreshToken, {
TokenType = gcontext.TokenResponse.TokenType, using (var serviceScope = app.ApplicationServices.GetRequiredService<IServiceScopeFactory>()
ExpiresInSeconds = int.Parse (gcontext.TokenResponse.ExpiresIn), .CreateScope())
IssuedUtc = DateTime.Now {
}); var gcontext = context as GoogleOAuthCreatingTicketContext;
await dbContext.StoreTokenAsync (gcontext.GoogleUserId, context.Identity.AddClaim(new Claim(YavscClaimTypes.GoogleUserId, gcontext.GoogleUserId));
gcontext.TokenResponse.Response, var dbContext = serviceScope.ServiceProvider.GetService<ApplicationDbContext>();
gcontext.TokenResponse.AccessToken,
gcontext.TokenResponse.TokenType, var store = serviceScope.ServiceProvider.GetService<IDataStore>();
gcontext.TokenResponse.RefreshToken, await store.StoreAsync(gcontext.GoogleUserId, new TokenResponse {
gcontext.TokenResponse.ExpiresIn); AccessToken = gcontext.TokenResponse.AccessToken,
RefreshToken = gcontext.TokenResponse.RefreshToken,
} TokenType = gcontext.TokenResponse.TokenType,
} ExpiresInSeconds = int.Parse(gcontext.TokenResponse.ExpiresIn),
} IssuedUtc = DateTime.Now
}; });
await dbContext.StoreTokenAsync (gcontext.GoogleUserId,
branch.UseMiddleware<Yavsc.Auth.GoogleMiddleware> (YavscGoogleAppOptions); gcontext.TokenResponse.Response,
/* FIXME 403 gcontext.TokenResponse.AccessToken,
gcontext.TokenResponse.TokenType,
branch.UseTwitterAuthentication(options=> gcontext.TokenResponse.RefreshToken,
{ gcontext.TokenResponse.ExpiresIn);
TwitterAppOptions = options;
options.ConsumerKey = Configuration["Authentication:Twitter:ClientId"]; }
options.ConsumerSecret = Configuration["Authentication:Twitter:ClientSecret"]; }
}); */ }
};
branch.UseOAuthAuthorizationServer (
branch.UseMiddleware<Yavsc.Auth.GoogleMiddleware>(YavscGoogleAppOptions);
options => { /* FIXME 403
OAuthServerAppOptions = options;
options.AuthorizeEndpointPath = new PathString (Constants.AuthorizePath.Substring (1)); branch.UseTwitterAuthentication(options=>
options.TokenEndpointPath = new PathString (Constants.TokenPath.Substring (1)); {
options.ApplicationCanDisplayErrors = true; TwitterAppOptions = options;
options.AllowInsecureHttp = true; options.ConsumerKey = Configuration["Authentication:Twitter:ClientId"];
options.AuthenticationScheme = OAuthDefaults.AuthenticationType; options.ConsumerSecret = Configuration["Authentication:Twitter:ClientSecret"];
options.TokenDataProtector = ProtectionProvider.CreateProtector ("Bearer protection"); }); */
options.Provider = new OAuthAuthorizationServerProvider {
OnValidateClientRedirectUri = ValidateClientRedirectUri, branch.UseOAuthAuthorizationServer(
OnValidateClientAuthentication = ValidateClientAuthentication,
OnGrantResourceOwnerCredentials = GrantResourceOwnerCredentials, options =>
OnGrantClientCredentials = GrantClientCredetails {
}; OAuthServerAppOptions = options;
options.AuthorizeEndpointPath = new PathString(Constants.AuthorizePath.Substring(1));
options.AuthorizationCodeProvider = new AuthenticationTokenProvider { options.TokenEndpointPath = new PathString(Constants.TokenPath.Substring(1));
OnCreate = CreateAuthenticationCode, options.ApplicationCanDisplayErrors = true;
OnReceive = ReceiveAuthenticationCode, options.AllowInsecureHttp = true;
}; options.AuthenticationScheme = OAuthDefaults.AuthenticationType;
options.TokenDataProtector = ProtectionProvider.CreateProtector("Bearer protection");
options.RefreshTokenProvider = new AuthenticationTokenProvider {
OnCreate = CreateRefreshToken, options.Provider = new OAuthAuthorizationServerProvider
OnReceive = ReceiveRefreshToken, {
}; OnValidateClientRedirectUri = ValidateClientRedirectUri,
OnValidateClientAuthentication = ValidateClientAuthentication,
options.AutomaticAuthenticate = true; OnGrantResourceOwnerCredentials = GrantResourceOwnerCredentials,
options.AutomaticChallenge = true; OnGrantClientCredentials = GrantClientCredetails
} };
);
}); options.AuthorizationCodeProvider = new AuthenticationTokenProvider
{
Environment.SetEnvironmentVariable ("GOOGLE_APPLICATION_CREDENTIALS", "google-secret.json"); OnCreate = CreateAuthenticationCode,
OnReceive = ReceiveAuthenticationCode,
};
options.RefreshTokenProvider = new AuthenticationTokenProvider
{
OnCreate = CreateRefreshToken,
OnReceive = ReceiveRefreshToken,
};
options.AutomaticAuthenticate = true;
options.AutomaticChallenge = true;
}
);
});
Environment.SetEnvironmentVariable ("GOOGLE_APPLICATION_CREDENTIALS", "google-secret.json");
} }
} }

Loading…