OAuth OK!
This commit is contained in:
@ -1,6 +1,8 @@
|
||||
using System;
|
||||
using System.Security.Claims;
|
||||
using Microsoft.AspNet.Authentication;
|
||||
using Microsoft.AspNet.Authentication.Cookies;
|
||||
using Microsoft.AspNet.Authentication.Facebook;
|
||||
using Microsoft.AspNet.Authentication.OAuth;
|
||||
using Microsoft.AspNet.Builder;
|
||||
using Microsoft.AspNet.Http;
|
||||
@ -18,10 +20,21 @@ namespace Yavsc
|
||||
|
||||
public partial class Startup
|
||||
{
|
||||
public static CookieAuthenticationOptions ExternalCookieAppOptions { get; private set; }
|
||||
|
||||
public static IdentityOptions IdentityAppOptions { get; set; }
|
||||
public static FacebookOptions FacebookAppOptions { get; private set; }
|
||||
public static OAuthAuthorizationServerOptions OAuthServerAppOptions { get; private set; }
|
||||
|
||||
public static YavscGoogleOptions YavscGoogleAppOptions { get; private set; }
|
||||
public static MonoDataProtectionProvider ProtectionProvider { get; private set; }
|
||||
|
||||
// public static CookieAuthenticationOptions BearerCookieOptions { get; private set; }
|
||||
|
||||
private void ConfigureOAuthServices(IServiceCollection services)
|
||||
{
|
||||
services.Configure<SharedAuthenticationOptions>(options => options.SignInScheme = Constants.ApplicationAuthenticationSheme);
|
||||
|
||||
|
||||
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>();
|
||||
@ -42,143 +55,69 @@ namespace Yavsc
|
||||
new SigningCredentials(key, SecurityAlgorithms.RsaSha256Signature);
|
||||
}
|
||||
); */
|
||||
services.AddAuthentication(options =>
|
||||
services.AddAuthentication(options =>
|
||||
{
|
||||
options.SignInScheme = Constants.ApplicationAuthenticationSheme;
|
||||
options.SignInScheme = Constants.ExternalAuthenticationSheme;
|
||||
});
|
||||
|
||||
var protector = new MonoDataProtectionProvider(Configuration["Site:Title"]);;
|
||||
services.AddInstance<MonoDataProtectionProvider>(
|
||||
protector
|
||||
);
|
||||
ProtectionProvider = new MonoDataProtectionProvider(Configuration["Site:Title"]); ;
|
||||
services.AddInstance<MonoDataProtectionProvider>
|
||||
(ProtectionProvider);
|
||||
|
||||
services.AddIdentity<ApplicationUser, IdentityRole>(
|
||||
option =>
|
||||
{
|
||||
IdentityAppOptions = 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.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;
|
||||
// option.Cookies.ApplicationCookieAuthenticationScheme = 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.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)
|
||||
{
|
||||
app.UseIdentity();
|
||||
// External authentication shared cookie:
|
||||
app.UseCookieAuthentication(options =>
|
||||
{
|
||||
//options.AuthenticationScheme = Constants.ExternalAuthenticationSheme;
|
||||
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.AccessDeniedPath.Substring(1));
|
||||
options.AuthenticationScheme = Constants.ApplicationAuthenticationSheme;
|
||||
});
|
||||
|
||||
var gvents = new OAuthEvents();
|
||||
var googleOptions = new YavscGoogleOptions
|
||||
{
|
||||
ClientId = Configuration["Authentication:Google:ClientId"],
|
||||
ClientSecret = Configuration["Authentication:Google:ClientSecret"],
|
||||
AccessType = "offline",
|
||||
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 service =
|
||||
serviceScope.ServiceProvider.GetService<ApplicationDbContext>();
|
||||
await service.StoreTokenAsync(gcontext.GoogleUserId, context.TokenResponse);
|
||||
}
|
||||
}
|
||||
}
|
||||
};
|
||||
googleOptions.Scope.Add("https://www.googleapis.com/auth/calendar");
|
||||
app.UseMiddleware<Yavsc.Auth.GoogleMiddleware>(googleOptions);
|
||||
|
||||
// Facebook
|
||||
app.UseFacebookAuthentication(options =>
|
||||
{
|
||||
options.AppId = Configuration["Authentication:Facebook:AppId"];
|
||||
options.AppSecret = Configuration["Authentication:Facebook:AppSecret"];
|
||||
options.Scope.Add("email");
|
||||
options.UserInformationEndpoint = "https://graph.facebook.com/v2.5/me?fields=id,name,email,first_name,last_name";
|
||||
});
|
||||
/* Generic OAuth (here GitHub): options.Notifications = new OAuthAuthenticationNotifications
|
||||
{
|
||||
OnGetUserInformationAsync = async context =>
|
||||
{
|
||||
// Get the GitHub user
|
||||
HttpRequestMessage userRequest = new HttpRequestMessage(HttpMethod.Get, context.Options.UserInformationEndpoint);
|
||||
userRequest.Headers.Authorization = new AuthenticationHeaderValue("Bearer", context.AccessToken);
|
||||
userRequest.Headers.Accept.Add(new MediaTypeWithQualityHeaderValue("application/json"));
|
||||
HttpResponseMessage userResponse = await context.Backchannel.SendAsync(userRequest, context.HttpContext.RequestAborted);
|
||||
userResponse.EnsureSuccessStatusCode();
|
||||
var text = await userResponse.Content.ReadAsStringAsync();
|
||||
JObject user = JObject.Parse(text);
|
||||
|
||||
var identity = new ClaimsIdentity(
|
||||
context.Options.AuthenticationType,
|
||||
ClaimsIdentity.DefaultNameClaimType,
|
||||
ClaimsIdentity.DefaultRoleClaimType);
|
||||
|
||||
JToken value;
|
||||
var id = user.TryGetValue("id", out value) ? value.ToString() : null;
|
||||
if (!string.IsNullOrEmpty(id))
|
||||
{
|
||||
identity.AddClaim(new Claim(ClaimTypes.NameIdentifier, id, ClaimValueTypes.String, context.Options.AuthenticationType));
|
||||
}
|
||||
var userName = user.TryGetValue("login", out value) ? value.ToString() : null;
|
||||
if (!string.IsNullOrEmpty(userName))
|
||||
{
|
||||
identity.AddClaim(new Claim(ClaimsIdentity.DefaultNameClaimType, userName, ClaimValueTypes.String, context.Options.AuthenticationType));
|
||||
}
|
||||
var name = user.TryGetValue("name", out value) ? value.ToString() : null;
|
||||
if (!string.IsNullOrEmpty(name))
|
||||
{
|
||||
identity.AddClaim(new Claim("urn:github:name", name, ClaimValueTypes.String, context.Options.AuthenticationType));
|
||||
}
|
||||
var link = user.TryGetValue("url", out value) ? value.ToString() : null;
|
||||
if (!string.IsNullOrEmpty(link))
|
||||
{
|
||||
identity.AddClaim(new Claim("urn:github:url", link, ClaimValueTypes.String, context.Options.AuthenticationType));
|
||||
}
|
||||
|
||||
context.Identity = identity;
|
||||
}
|
||||
}; */
|
||||
|
||||
app.UseOAuthAuthorizationServer(
|
||||
|
||||
options =>
|
||||
{
|
||||
OAuthServerAppOptions = options;
|
||||
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.Provider = new OAuthAuthorizationServerProvider
|
||||
{
|
||||
OnValidateClientRedirectUri = ValidateClientRedirectUri,
|
||||
@ -201,8 +140,48 @@ namespace Yavsc
|
||||
|
||||
options.AutomaticAuthenticate = true;
|
||||
options.AutomaticChallenge = true;
|
||||
}
|
||||
}
|
||||
);
|
||||
|
||||
app.UseIdentity();
|
||||
|
||||
var gvents = new OAuthEvents();
|
||||
YavscGoogleAppOptions = new YavscGoogleOptions
|
||||
{
|
||||
ClientId = Configuration["Authentication:Google:ClientId"],
|
||||
ClientSecret = Configuration["Authentication:Google:ClientSecret"],
|
||||
AccessType = "offline",
|
||||
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 service =
|
||||
serviceScope.ServiceProvider.GetService<ApplicationDbContext>();
|
||||
await service.StoreTokenAsync(gcontext.GoogleUserId, context.TokenResponse);
|
||||
}
|
||||
}
|
||||
}
|
||||
};
|
||||
YavscGoogleAppOptions.Scope.Add("https://www.googleapis.com/auth/calendar");
|
||||
app.UseMiddleware<Yavsc.Auth.GoogleMiddleware>(YavscGoogleAppOptions);
|
||||
|
||||
// Facebook
|
||||
app.UseFacebookAuthentication(options =>
|
||||
{
|
||||
FacebookAppOptions = options;
|
||||
options.AppId = Configuration["Authentication:Facebook:AppId"];
|
||||
options.AppSecret = Configuration["Authentication:Facebook:AppSecret"];
|
||||
options.Scope.Add("email");
|
||||
options.UserInformationEndpoint = "https://graph.facebook.com/v2.5/me?fields=id,name,email,first_name,last_name";
|
||||
});
|
||||
|
||||
}
|
||||
}
|
||||
}
|
||||
|
@ -6,23 +6,25 @@ using System.Security.Principal;
|
||||
using System.Threading.Tasks;
|
||||
using Microsoft.Extensions.Logging;
|
||||
using OAuth.AspNet.AuthServer;
|
||||
using Yavsc.Helpers;
|
||||
using Yavsc.Models;
|
||||
using Yavsc.Models.Auth;
|
||||
|
||||
namespace Yavsc
|
||||
{
|
||||
public partial class Startup
|
||||
{
|
||||
private Application GetApplication(string clientId)
|
||||
private Client GetApplication(string clientId)
|
||||
{
|
||||
var dbContext = new ApplicationDbContext();
|
||||
var app = dbContext.Applications.FirstOrDefault(x=>x.ApplicationID == clientId);
|
||||
var app = dbContext.Applications.FirstOrDefault(x => x.Id == clientId);
|
||||
return app;
|
||||
}
|
||||
private readonly ConcurrentDictionary<string, string> _authenticationCodes = new ConcurrentDictionary<string, string>(StringComparer.Ordinal);
|
||||
|
||||
private Task ValidateClientRedirectUri(OAuthValidateClientRedirectUriContext context)
|
||||
{
|
||||
if (context==null) throw new InvalidOperationException("context == null");
|
||||
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})");
|
||||
@ -32,16 +34,40 @@ namespace Yavsc
|
||||
|
||||
private Task ValidateClientAuthentication(OAuthValidateClientAuthenticationContext context)
|
||||
{
|
||||
string clientId,clientSecret;
|
||||
string clientId, clientSecret;
|
||||
if (context.TryGetBasicCredentials(out clientId, out clientSecret) ||
|
||||
context.TryGetFormCredentials(out clientId, out clientSecret))
|
||||
{
|
||||
var app = GetApplication(clientId);
|
||||
if (app != null && app.Secret == clientSecret)
|
||||
var client = GetApplication(clientId);
|
||||
if (client.Type == ApplicationTypes.NativeConfidential)
|
||||
{
|
||||
Startup.logger.LogInformation($"ValidateClientAuthentication: Validated ({clientId})");
|
||||
if (string.IsNullOrWhiteSpace(clientSecret))
|
||||
{
|
||||
context.SetError("invalid_clientId", "Client secret should be sent.");
|
||||
return Task.FromResult<object>(null);
|
||||
}
|
||||
else
|
||||
{
|
||||
if (client.Secret != Helper.GetHash(clientSecret))
|
||||
{
|
||||
context.SetError("invalid_clientId", "Client secret is invalid.");
|
||||
return Task.FromResult<object>(null);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
if (!client.Active)
|
||||
{
|
||||
context.SetError("invalid_clientId", "Client is inactive.");
|
||||
return Task.FromResult<object>(null);
|
||||
}
|
||||
|
||||
if (client != null && client.Secret == clientSecret)
|
||||
{
|
||||
logger.LogInformation($"\\o/ ValidateClientAuthentication: Validated ({clientId})");
|
||||
context.Validated();
|
||||
} else Startup.logger.LogInformation($"ValidateClientAuthentication: KO ({clientId})");
|
||||
}
|
||||
else Startup.logger.LogInformation($"ValidateClientAuthentication: KO ({clientId})");
|
||||
}
|
||||
else Startup.logger.LogInformation($"ValidateClientAuthentication: nor Basic neither Form credential found");
|
||||
return Task.FromResult(0);
|
||||
@ -49,7 +75,12 @@ namespace Yavsc
|
||||
|
||||
private Task GrantResourceOwnerCredentials(OAuthGrantResourceOwnerCredentialsContext context)
|
||||
{
|
||||
logger.LogWarning($"GrantResourceOwnerCredentials task ... {context.UserName}");
|
||||
|
||||
// var user = ValidateUser(context.UserName, context.Password)
|
||||
|
||||
ClaimsPrincipal principal = new ClaimsPrincipal(new ClaimsIdentity(new GenericIdentity(context.UserName, OAuthDefaults.AuthenticationType), context.Scope.Select(x => new Claim("urn:oauth:scope", x))));
|
||||
// TODO set a NameIdentifier, roles and scopes claims
|
||||
|
||||
context.Validated(principal);
|
||||
|
||||
@ -67,7 +98,7 @@ namespace Yavsc
|
||||
|
||||
private void CreateAuthenticationCode(AuthenticationTokenCreateContext context)
|
||||
{
|
||||
Startup.logger.LogInformation("CreateAuthenticationCode");
|
||||
logger.LogInformation("CreateAuthenticationCode");
|
||||
context.SetToken(Guid.NewGuid().ToString("n") + Guid.NewGuid().ToString("n"));
|
||||
_authenticationCodes[context.Token] = context.SerializeTicket();
|
||||
}
|
||||
@ -78,20 +109,21 @@ namespace Yavsc
|
||||
if (_authenticationCodes.TryRemove(context.Token, out value))
|
||||
{
|
||||
context.DeserializeTicket(value);
|
||||
logger.LogInformation("ReceiveAuthenticationCode: Success");
|
||||
}
|
||||
}
|
||||
|
||||
private void CreateRefreshToken(AuthenticationTokenCreateContext context)
|
||||
{
|
||||
var uid = context.Ticket.Principal.GetUserId();
|
||||
Startup.logger.LogInformation($"CreateRefreshToken for {uid}");
|
||||
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}");
|
||||
logger.LogInformation($"ReceiveRefreshToken for {uid}");
|
||||
context.DeserializeTicket(context.Token);
|
||||
}
|
||||
}
|
||||
|
@ -8,9 +8,6 @@ using Microsoft.AspNet.Authorization;
|
||||
using Microsoft.AspNet.Builder;
|
||||
using Microsoft.AspNet.Diagnostics;
|
||||
using Microsoft.AspNet.Hosting;
|
||||
using Microsoft.AspNet.Http;
|
||||
using Microsoft.AspNet.Identity;
|
||||
using Microsoft.AspNet.Identity.EntityFramework;
|
||||
using Microsoft.AspNet.Localization;
|
||||
using Microsoft.AspNet.Mvc;
|
||||
using Microsoft.AspNet.Mvc.Filters;
|
||||
@ -22,7 +19,6 @@ using Microsoft.Extensions.Logging;
|
||||
using Microsoft.Extensions.OptionsModel;
|
||||
using Microsoft.Extensions.PlatformAbstractions;
|
||||
using Microsoft.Net.Http.Headers;
|
||||
using Yavsc.Auth;
|
||||
using Yavsc.Formatters;
|
||||
using Yavsc.Models;
|
||||
using Yavsc.Services;
|
||||
|
Reference in New Issue
Block a user