Circles, pub & auth

* Adds a boolean to each Circle, saying that
  it is public, and its existence may be known by any interested in
* Adds claims of type "YavscClaimTypes.CircleMembership" at
  login, in order to implement some faster authorisation processes and file restricted accesses.
This commit is contained in:
Paul Schneider 2019-07-30 18:42:22 +02:00
commit cdc18fd547
12 changed files with 3158 additions and 92 deletions

View file

@ -19,14 +19,16 @@ using Microsoft.Extensions.WebEncoders;
using OAuth.AspNet.AuthServer;
using OAuth.AspNet.Tokens;
namespace Yavsc {
namespace Yavsc
{
using System.Threading.Tasks;
using Auth;
using Extensions;
using Models;
using Yavsc.Helpers.Auth;
public partial class Startup {
public partial class Startup
{
public static CookieAuthenticationOptions ExternalCookieAppOptions { get; private set; }
public static IdentityOptions IdentityAppOptions { get; set; }
@ -40,23 +42,26 @@ namespace Yavsc {
// public static CookieAuthenticationOptions BearerCookieOptions { get; private set; }
private void ConfigureOAuthServices (IServiceCollection services) {
services.Configure<SharedAuthenticationOptions> (options => options.SignInScheme = Constants.ApplicationAuthenticationSheme);
private void ConfigureOAuthServices(IServiceCollection services)
{
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)
services.AddTransient<Microsoft.Extensions.WebEncoders.UrlEncoder, UrlEncoder> ();
services.AddTransient<Microsoft.Extensions.WebEncoders.UrlEncoder, UrlEncoder>();
services.AddAuthentication (options => {
services.AddAuthentication(options =>
{
options.SignInScheme = Constants.ExternalAuthenticationSheme;
});
ProtectionProvider = new MonoDataProtectionProvider (Configuration["Site:Title"]);;
ProtectionProvider = new MonoDataProtectionProvider(Configuration["Site:Title"]); ;
services.AddInstance<MonoDataProtectionProvider>
(ProtectionProvider);
services.AddIdentity<ApplicationUser, IdentityRole> (
option => {
services.AddIdentity<ApplicationUser, IdentityRole>(
option =>
{
IdentityAppOptions = option;
option.User.AllowedUserNameCharacters += " ";
option.User.RequireUniqueEmail = true;
@ -78,8 +83,8 @@ namespace Yavsc {
option.Cookies.ExternalCookie.DataProtectionProvider = protector;
*/
}
).AddEntityFrameworkStores<ApplicationDbContext> ()
.AddTokenProvider<EmailTokenProvider<ApplicationUser>> (Constants.DefaultFactor)
).AddEntityFrameworkStores<ApplicationDbContext>()
.AddTokenProvider<EmailTokenProvider<ApplicationUser>>(Constants.DefaultFactor)
// .AddTokenProvider<UserTokenProvider>(Constants.DefaultFactor)
// .AddTokenProvider<UserTokenProvider>(Constants.SMSFactor)
// .AddTokenProvider<UserTokenProvider>(Constants.EMailFactor)
@ -87,92 +92,103 @@ namespace Yavsc {
// .AddDefaultTokenProviders()
;
}
private void ConfigureOAuthApp (IApplicationBuilder app,
SiteSettings settingsOptions, ILogger logger) {
private void ConfigureOAuthApp(IApplicationBuilder app,
SiteSettings settingsOptions, ILogger logger)
{
app.UseIdentity ();
app.UseWhen ( context => context.Request.Path.StartsWithSegments ("/api")
|| context.Request.Path.StartsWithSegments ("/live") ,
branchLiveOrApi =>
app.UseIdentity();
app.UseWhen(context => context.Request.Path.StartsWithSegments("/api")
|| context.Request.Path.StartsWithSegments("/live"),
branchLiveOrApi =>
{
branchLiveOrApi.UseJwtBearerAuthentication (
options => {
branchLiveOrApi.UseJwtBearerAuthentication(
options =>
{
options.AuthenticationScheme = JwtBearerDefaults.AuthenticationScheme;
options.AutomaticAuthenticate = true;
options.SecurityTokenValidators.Clear ();
options.SecurityTokenValidators.Add (new TicketDataFormatTokenValidator (
options.SecurityTokenValidators.Clear();
var tickeDataProtector = new TicketDataFormatTokenValidator(
ProtectionProvider
));
);
options.SecurityTokenValidators.Add(tickeDataProtector);
options.Events = new JwtBearerEvents
{
OnReceivingToken = context =>
{
return Task.Run( () => {
var signalRTokenHeader = context.Request.Query["signalRTokenHeader"];
OnReceivingToken = context =>
{
return Task.Run(() =>
{
var signalRTokenHeader = context.Request.Query["signalRTokenHeader"];
if (!string.IsNullOrEmpty(signalRTokenHeader) &&
(context.HttpContext.WebSockets.IsWebSocketRequest || context.Request.Headers["Accept"] == "text/event-stream"))
{
context.Token = context.Request.Query["signalRTokenHeader"];
}
});
}
if (!string.IsNullOrEmpty(signalRTokenHeader) &&
(context.HttpContext.WebSockets.IsWebSocketRequest || context.Request.Headers["Accept"] == "text/event-stream"))
{
context.Token = context.Request.Query["signalRTokenHeader"];
}
});
}
};
});
});
app.UseWhen (context => !context.Request.Path.StartsWithSegments ("/api") && !context.Request.Path.StartsWithSegments ("/live"),
branch => {
app.UseWhen(context => !context.Request.Path.StartsWithSegments("/api") && !context.Request.Path.StartsWithSegments("/live"),
branch =>
{
// External authentication shared cookie:
branch.UseCookieAuthentication (options => {
branch.UseCookieAuthentication(options =>
{
ExternalCookieAppOptions = options;
options.AuthenticationScheme = Constants.ExternalAuthenticationSheme;
options.AutomaticAuthenticate = true;
options.ExpireTimeSpan = TimeSpan.FromMinutes (5);
options.LoginPath = new PathString (Constants.LoginPath.Substring (1));
options.AccessDeniedPath = new PathString (Constants.LoginPath.Substring (1));
options.ExpireTimeSpan = TimeSpan.FromMinutes(5);
options.LoginPath = new PathString(Constants.LoginPath.Substring(1));
options.AccessDeniedPath = new PathString(Constants.LoginPath.Substring(1));
});
YavscGoogleAppOptions = new YavscGoogleOptions {
YavscGoogleAppOptions = new YavscGoogleOptions
{
ClientId = GoogleWebClientConfiguration["web:client_id"],
ClientSecret = GoogleWebClientConfiguration["web:client_secret"],
AccessType = "offline",
Scope = {
ClientSecret = GoogleWebClientConfiguration["web:client_secret"],
AccessType = "offline",
Scope = {
"profile",
"https://www.googleapis.com/auth/admin.directory.resource.calendar",
"https://www.googleapis.com/auth/calendar",
"https://www.googleapis.com/auth/calendar.events"
},
SaveTokensAsClaims = true,
UserInformationEndpoint = "https://www.googleapis.com/plus/v1/people/me",
Events = new OAuthEvents {
OnCreatingTicket = async context => {
using (var serviceScope = app.ApplicationServices.GetRequiredService<IServiceScopeFactory> ()
.CreateScope ()) {
var gcontext = context as GoogleOAuthCreatingTicketContext;
context.Identity.AddClaim (new Claim (YavscClaimTypes.GoogleUserId, gcontext.GoogleUserId));
var dbContext = serviceScope.ServiceProvider.GetService<ApplicationDbContext> ();
SaveTokensAsClaims = true,
UserInformationEndpoint = "https://www.googleapis.com/plus/v1/people/me",
Events = new OAuthEvents
{
OnCreatingTicket = async context =>
{
using (var serviceScope = app.ApplicationServices.GetRequiredService<IServiceScopeFactory>()
.CreateScope())
{
var gcontext = context as GoogleOAuthCreatingTicketContext;
context.Identity.AddClaim(new Claim(YavscClaimTypes.GoogleUserId, gcontext.GoogleUserId));
var dbContext = serviceScope.ServiceProvider.GetService<ApplicationDbContext>();
var store = serviceScope.ServiceProvider.GetService<IDataStore> ();
await store.StoreAsync (gcontext.GoogleUserId, new TokenResponse {
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,
gcontext.TokenResponse.Response,
gcontext.TokenResponse.AccessToken,
gcontext.TokenResponse.TokenType,
gcontext.TokenResponse.RefreshToken,
gcontext.TokenResponse.ExpiresIn);
var store = serviceScope.ServiceProvider.GetService<IDataStore>();
await store.StoreAsync(gcontext.GoogleUserId, new TokenResponse
{
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,
gcontext.TokenResponse.Response,
gcontext.TokenResponse.AccessToken,
gcontext.TokenResponse.TokenType,
gcontext.TokenResponse.RefreshToken,
gcontext.TokenResponse.ExpiresIn);
}
}
}
}
};
branch.UseMiddleware<Yavsc.Auth.GoogleMiddleware> (YavscGoogleAppOptions);
branch.UseMiddleware<Yavsc.Auth.GoogleMiddleware>(YavscGoogleAppOptions);
/* FIXME 403
branch.UseTwitterAuthentication(options=>
@ -182,30 +198,34 @@ namespace Yavsc {
options.ConsumerSecret = Configuration["Authentication:Twitter:ClientSecret"];
}); */
branch.UseOAuthAuthorizationServer (
branch.UseOAuthAuthorizationServer(
options => {
options =>
{
OAuthServerAppOptions = options;
options.AuthorizeEndpointPath = new PathString (Constants.AuthorizePath.Substring (1));
options.TokenEndpointPath = new PathString (Constants.TokenPath.Substring (1));
options.AuthorizeEndpointPath = new PathString(Constants.AuthorizePath.Substring(1));
options.TokenEndpointPath = new PathString(Constants.TokenPath.Substring(1));
options.ApplicationCanDisplayErrors = true;
options.AllowInsecureHttp = true;
options.AuthenticationScheme = OAuthDefaults.AuthenticationType;
options.TokenDataProtector = ProtectionProvider.CreateProtector ("Bearer protection");
options.TokenDataProtector = ProtectionProvider.CreateProtector("Bearer protection");
options.Provider = new OAuthAuthorizationServerProvider {
options.Provider = new OAuthAuthorizationServerProvider
{
OnValidateClientRedirectUri = ValidateClientRedirectUri,
OnValidateClientAuthentication = ValidateClientAuthentication,
OnGrantResourceOwnerCredentials = GrantResourceOwnerCredentials,
OnGrantClientCredentials = GrantClientCredetails
};
options.AuthorizationCodeProvider = new AuthenticationTokenProvider {
options.AuthorizationCodeProvider = new AuthenticationTokenProvider
{
OnCreate = CreateAuthenticationCode,
OnReceive = ReceiveAuthenticationCode,
};
options.RefreshTokenProvider = new AuthenticationTokenProvider {
options.RefreshTokenProvider = new AuthenticationTokenProvider
{
OnCreate = CreateRefreshToken,
OnReceive = ReceiveRefreshToken,
};
@ -216,8 +236,8 @@ namespace Yavsc {
);
});
Environment.SetEnvironmentVariable ("GOOGLE_APPLICATION_CREDENTIALS", "google-secret.json");
Environment.SetEnvironmentVariable("GOOGLE_APPLICATION_CREDENTIALS", "google-secret.json");
}
}
}
}

View file

@ -6,6 +6,7 @@ using System.Security.Claims;
using System.Security.Principal;
using System.Threading.Tasks;
using Microsoft.AspNet.Identity;
using Microsoft.Data.Entity;
using Microsoft.Extensions.Logging;
using OAuth.AspNet.AuthServer;
using Yavsc.Models;
@ -24,6 +25,7 @@ namespace Yavsc
_logger.LogError($"no app for <{clientId}>");
return app;
}
private readonly ConcurrentDictionary<string, string> _authenticationCodes = new ConcurrentDictionary<string, string>(StringComparer.Ordinal);
private Task ValidateClientRedirectUri(OAuthValidateClientRedirectUriContext context)
@ -88,6 +90,7 @@ namespace Yavsc
else _logger.LogWarning($"ValidateClientAuthentication: neither Basic nor Form credential were found");
return Task.FromResult(0);
}
UserManager<ApplicationUser> _usermanager;
private async Task<Task> GrantResourceOwnerCredentials(OAuthGrantResourceOwnerCredentialsContext context)
@ -95,7 +98,8 @@ namespace Yavsc
_logger.LogWarning($"GrantResourceOwnerCredentials task ... {context.UserName}");
ApplicationUser user = null;
user = await _usermanager.FindByNameAsync(context.UserName);
user = _dbContext.Users.Include(u=>u.Membership).First(u=>u.UserName == context.UserName);
if (await _usermanager.CheckPasswordAsync(user, context.Password))
{
@ -106,15 +110,16 @@ namespace Yavsc
claims.Add(new Claim(ClaimTypes.Email, user.Email));
claims.AddRange((await _usermanager.GetRolesAsync(user)).Select(
r => new Claim(ClaimTypes.Role, r)
));
));
claims.AddRange(user.Membership.Select(
m => new Claim(YavscClaimTypes.CircleMembership, m.CircleId.ToString())
));
ClaimsPrincipal principal = new ClaimsPrincipal(
new ClaimsIdentity(
new GenericIdentity(context.UserName, OAuthDefaults.AuthenticationType),
claims)
);
// TODO set a NameIdentifier, roles and scopes claims
context.HttpContext.User = principal;
context.Validated(principal);
}
@ -123,7 +128,10 @@ namespace Yavsc
private Task GrantClientCredetails(OAuthGrantClientCredentialsContext context)
{
ClaimsPrincipal principal = new ClaimsPrincipal(new ClaimsIdentity(new GenericIdentity(context.ClientId, OAuthDefaults.AuthenticationType), context.Scope.Select(x => new Claim("urn:oauth:scope", x))));
var id = new GenericIdentity(context.ClientId, OAuthDefaults.AuthenticationType);
var claims = context.Scope.Select(x => new Claim("urn:oauth:scope", x));
var cid = new ClaimsIdentity(id, claims);
ClaimsPrincipal principal = new ClaimsPrincipal(cid);
context.Validated(principal);