remove ref to OWin & changes to AspNet.OAuth.Server
This commit is contained in:
@ -1,14 +0,0 @@
|
||||
|
||||
public interface IApplication
|
||||
{
|
||||
string ApplicationID { get; set; }
|
||||
string DisplayName { get; set; }
|
||||
string RedirectUri { get; set; }
|
||||
string LogoutRedirectUri { get; set; }
|
||||
string Secret { get; set; }
|
||||
}
|
||||
public interface IApplicationStore
|
||||
{
|
||||
IApplication FindApplication(string clientId);
|
||||
|
||||
}
|
@ -17,12 +17,6 @@ namespace OAuth.AspNet.AuthServer
|
||||
|
||||
public class OAuthAuthorizationServerHandler : AuthenticationHandler<OAuthAuthorizationServerOptions>
|
||||
{
|
||||
public OAuthAuthorizationServerHandler(IApplicationStore applicationStore)
|
||||
{
|
||||
ApplicationStore = applicationStore;
|
||||
}
|
||||
|
||||
public IApplicationStore ApplicationStore { get; private set;}
|
||||
#region non-Public Members
|
||||
|
||||
private AuthorizeEndpointRequest _authorizeEndpointRequest;
|
||||
@ -335,7 +329,7 @@ namespace OAuth.AspNet.AuthServer
|
||||
{
|
||||
var authorizeRequest = new AuthorizeEndpointRequest(Request.Query);
|
||||
|
||||
var clientContext = new OAuthValidateClientRedirectUriContext(ApplicationStore,Context, Options, authorizeRequest.ClientId, authorizeRequest.RedirectUri);
|
||||
var clientContext = new OAuthValidateClientRedirectUriContext(Context, Options, authorizeRequest.ClientId, authorizeRequest.RedirectUri);
|
||||
|
||||
if (!string.IsNullOrEmpty(authorizeRequest.RedirectUri))
|
||||
{
|
||||
@ -423,7 +417,7 @@ namespace OAuth.AspNet.AuthServer
|
||||
|
||||
IFormCollection form = await Request.ReadFormAsync();
|
||||
|
||||
var clientContext = new OAuthValidateClientAuthenticationContext(Context, Options, form, ApplicationStore);
|
||||
var clientContext = new OAuthValidateClientAuthenticationContext(Context, Options, form);
|
||||
|
||||
await Options.Provider.ValidateClientAuthentication(clientContext);
|
||||
|
||||
@ -808,7 +802,7 @@ namespace OAuth.AspNet.AuthServer
|
||||
}
|
||||
}
|
||||
|
||||
#endregion
|
||||
#endregion
|
||||
}
|
||||
|
||||
}
|
||||
|
@ -1,10 +1,11 @@
|
||||
|
||||
using Microsoft.AspNet.Authentication;
|
||||
using Microsoft.AspNet.Authentication;
|
||||
using Microsoft.AspNet.Builder;
|
||||
using Microsoft.AspNet.DataProtection;
|
||||
using Microsoft.Extensions.Logging;
|
||||
using Microsoft.Extensions.WebEncoders;
|
||||
using System;
|
||||
using System.IO;
|
||||
using Yavsc.Auth;
|
||||
|
||||
namespace OAuth.AspNet.AuthServer
|
||||
{
|
||||
@ -21,21 +22,8 @@ namespace OAuth.AspNet.AuthServer
|
||||
/// called by application code directly, instead it is added by calling the the IAppBuilder UseOAuthAuthorizationServer
|
||||
/// extension method.
|
||||
/// </summary>
|
||||
public OAuthAuthorizationServerMiddleware(
|
||||
RequestDelegate next,
|
||||
OAuthAuthorizationServerOptions options,
|
||||
ILoggerFactory loggerFactory,
|
||||
IDataProtectionProvider dataProtectionProvider,
|
||||
IUrlEncoder encoder,
|
||||
IApplicationStore applicationStore
|
||||
) : base(next, options, loggerFactory, encoder)
|
||||
public OAuthAuthorizationServerMiddleware(RequestDelegate next, OAuthAuthorizationServerOptions options, ILoggerFactory loggerFactory, IDataProtectionProvider dataProtectionProvider, IUrlEncoder encoder) : base(next, options, loggerFactory, encoder)
|
||||
{
|
||||
if (applicationStore == null )
|
||||
{
|
||||
throw new InvalidOperationException("No application store");
|
||||
}
|
||||
ApplicationStore = applicationStore;
|
||||
|
||||
if (Options.Provider == null)
|
||||
{
|
||||
Options.Provider = new OAuthAuthorizationServerProvider();
|
||||
@ -57,8 +45,11 @@ namespace OAuth.AspNet.AuthServer
|
||||
|
||||
if (Options.TokenDataProtector == null)
|
||||
{
|
||||
Options.TokenDataProtector = dataProtectionProvider.CreateProtector("OAuth.AspNet.AuthServer");
|
||||
|
||||
#if DNXCORE50
|
||||
Options.TokenDataProtector = new DataProtectionProvider(new DirectoryInfo(Environment.GetEnvironmentVariable("Temp"))).CreateProtector("OAuth.AspNet.AuthServer");
|
||||
#else
|
||||
Options.TokenDataProtector = new MonoDataProtectionProvider("OAuth.AspNet.AuthServer").CreateProtector("OAuth.Data.Protector");
|
||||
#endif
|
||||
}
|
||||
|
||||
if (Options.AccessTokenFormat == null)
|
||||
@ -82,17 +73,15 @@ namespace OAuth.AspNet.AuthServer
|
||||
{
|
||||
Options.RefreshTokenProvider = new AuthenticationTokenProvider();
|
||||
}
|
||||
|
||||
}
|
||||
|
||||
private IApplicationStore ApplicationStore { get; set; }
|
||||
/// <summary>
|
||||
/// Called by the AuthenticationMiddleware base class to create a per-request handler.
|
||||
/// </summary>
|
||||
/// <returns>A new instance of the request handler</returns>
|
||||
protected override AuthenticationHandler<OAuthAuthorizationServerOptions> CreateHandler()
|
||||
{
|
||||
return new OAuthAuthorizationServerHandler(ApplicationStore);
|
||||
return new OAuthAuthorizationServerHandler();
|
||||
}
|
||||
}
|
||||
|
||||
|
@ -1,3 +1,4 @@
|
||||
using Microsoft.AspNet.Authentication;
|
||||
using Microsoft.AspNet.Http;
|
||||
|
||||
namespace OAuth.AspNet.AuthServer
|
||||
|
@ -16,14 +16,11 @@ namespace OAuth.AspNet.AuthServer
|
||||
/// <param name="context"></param>
|
||||
/// <param name="options"></param>
|
||||
/// <param name="parameters"></param>
|
||||
public OAuthValidateClientAuthenticationContext(HttpContext context, OAuthAuthorizationServerOptions options, IReadableStringCollection parameters, IApplicationStore applicationStore) : base(context, options, null)
|
||||
public OAuthValidateClientAuthenticationContext(HttpContext context, OAuthAuthorizationServerOptions options, IReadableStringCollection parameters) : base(context, options, null)
|
||||
{
|
||||
Parameters = parameters;
|
||||
ApplicationStore = applicationStore;
|
||||
}
|
||||
|
||||
public IApplicationStore ApplicationStore { get; private set;}
|
||||
|
||||
/// <summary>
|
||||
/// Gets the set of form parameters from the request.
|
||||
/// </summary>
|
||||
|
@ -1,14 +0,0 @@
|
||||
|
||||
|
||||
public class OAuthValidateClientCredentialsContext {
|
||||
public OAuthValidateClientCredentialsContext(string clientId,string clientSecret,IApplicationStore applicationStore)
|
||||
{
|
||||
ClientId = clientId;
|
||||
ClientSecret = clientSecret;
|
||||
ApplicationStore = applicationStore;
|
||||
}
|
||||
public string ClientId { get; private set; }
|
||||
public string ClientSecret { get; private set; }
|
||||
public IApplicationStore ApplicationStore { get; private set; }
|
||||
|
||||
}
|
@ -17,10 +17,9 @@ namespace OAuth.AspNet.AuthServer
|
||||
/// <param name="clientId"></param>
|
||||
/// <param name="redirectUri"></param>
|
||||
[System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Design", "CA1054:UriParametersShouldNotBeStrings", MessageId = "3#", Justification = "redirect_uri is a string parameter")]
|
||||
public OAuthValidateClientRedirectUriContext(IApplicationStore applicationStore, HttpContext context, OAuthAuthorizationServerOptions options, string clientId, string redirectUri) : base(context, options, clientId)
|
||||
public OAuthValidateClientRedirectUriContext(HttpContext context, OAuthAuthorizationServerOptions options, string clientId, string redirectUri) : base(context, options, clientId)
|
||||
{
|
||||
RedirectUri = redirectUri;
|
||||
ApplicationStore = applicationStore;
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
@ -29,8 +28,6 @@ namespace OAuth.AspNet.AuthServer
|
||||
[System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Design", "CA1056:UriPropertiesShouldNotBeStrings", Justification = "redirect_uri is a string parameter")]
|
||||
public string RedirectUri { get; private set; }
|
||||
|
||||
public IApplicationStore ApplicationStore { get; private set;}
|
||||
|
||||
/// <summary>
|
||||
/// Marks this context as validated by the application. IsValidated becomes true and HasError becomes false as a result of calling.
|
||||
/// </summary>
|
||||
|
@ -2,6 +2,7 @@
|
||||
|
||||
|
||||
using System;
|
||||
using System.IO;
|
||||
using Microsoft.AspNet.DataProtection;
|
||||
namespace Yavsc.Auth
|
||||
{
|
||||
@ -13,10 +14,14 @@ public class MonoDataProtectionProvider : IDataProtectionProvider
|
||||
: this(Guid.NewGuid().ToString())
|
||||
{ }
|
||||
|
||||
public MonoDataProtectionProvider(DirectoryInfo dataProtectionDirInfo)
|
||||
: this(Guid.NewGuid().ToString())
|
||||
{
|
||||
|
||||
}
|
||||
public MonoDataProtectionProvider(string appName)
|
||||
{
|
||||
if (appName == null) { throw new ArgumentNullException("appName"); }
|
||||
|
||||
this.appName = appName;
|
||||
}
|
||||
|
||||
|
@ -29,7 +29,7 @@ namespace Yavsc.Auth
|
||||
{
|
||||
public class MonoDataProtector : IDataProtector
|
||||
{
|
||||
private const string PRIMARY_PURPOSE = "Microsoft.Owin.Security.IDataProtector";
|
||||
private const string PRIMARY_PURPOSE = "IDataProtector";
|
||||
|
||||
private readonly string appName;
|
||||
private readonly DataProtectionScope dataProtectionScope;
|
||||
|
@ -4,15 +4,17 @@ namespace Yavsc
|
||||
|
||||
public static class Constants
|
||||
{
|
||||
public const string AccessDeniedPath = "~/forbidden";
|
||||
public const string AccessDeniedPath = "~/signin";
|
||||
public const string AuthorizePath = "~/authorize";
|
||||
public const string TokenPath = "~/token";
|
||||
|
||||
public const string LocalLoginPath = "~/login";
|
||||
public const string LoginPath = "~/signin";
|
||||
public const string ExternalLoginPath = "~/extsign";
|
||||
public const string LogoutPath = "~/signout";
|
||||
public const string MePath = "~/api/Me";
|
||||
|
||||
public const string ExternalAuthenticationSheme = "External";
|
||||
public const string ApplicationAuthenticationSheme = "Server";
|
||||
public const string ExternalAuthenticationSheme = "ExternalCookie";
|
||||
public const string ApplicationAuthenticationSheme = "ServerCookie";
|
||||
public static readonly Scope[] SiteScopes = {
|
||||
new Scope { Id = "profile", Description = "Your profile informations" },
|
||||
new Scope { Id = "book" , Description ="Your booking interface"},
|
||||
|
@ -10,11 +10,12 @@ using Microsoft.AspNet.Mvc;
|
||||
using Microsoft.AspNet.Mvc.Rendering;
|
||||
using Microsoft.Extensions.Logging;
|
||||
using Microsoft.Extensions.OptionsModel;
|
||||
using Microsoft.AspNet.Http;
|
||||
using Yavsc.Extensions;
|
||||
using Yavsc.Models;
|
||||
using Yavsc.Services;
|
||||
using Yavsc.ViewModels.Account;
|
||||
|
||||
using Microsoft.AspNet.Http.Authentication;
|
||||
|
||||
namespace Yavsc.Controllers
|
||||
{
|
||||
@ -50,14 +51,15 @@ namespace Yavsc.Controllers
|
||||
_twilioSettings = twilioSettings.Value;
|
||||
_logger = loggerFactory.CreateLogger<AccountController>();
|
||||
}
|
||||
|
||||
[HttpGet(Constants.LoginPath)]
|
||||
public ActionResult Login(string returnUrl = null)
|
||||
public ActionResult SignIn(string returnUrl = null)
|
||||
{
|
||||
// Note: the "returnUrl" parameter corresponds to the endpoint the user agent
|
||||
// will be redirected to after a successful authentication and not
|
||||
// the redirect_uri of the requesting client application against the third
|
||||
// party identity provider.
|
||||
return View("Login", new LoginViewModel
|
||||
return View(new SignInViewModel
|
||||
{
|
||||
ReturnUrl = returnUrl,
|
||||
ExternalProviders = HttpContext.GetExternalProviders()
|
||||
@ -68,7 +70,21 @@ namespace Yavsc.Controllers
|
||||
*/
|
||||
}
|
||||
|
||||
[HttpPost(Constants.LoginPath)]
|
||||
public async Task<IActionResult> SignIn(SignInViewModel model)
|
||||
{
|
||||
if (Request.Method == "POST")
|
||||
{
|
||||
if (model.Provider=="LOCAL")
|
||||
{
|
||||
return await Login(model);
|
||||
}
|
||||
}
|
||||
model.ExternalProviders = HttpContext.GetExternalProviders();
|
||||
return View(model);
|
||||
}
|
||||
|
||||
[HttpPost(Constants.ExternalLoginPath)]
|
||||
public IActionResult ExternalLogin(string Provider, string ReturnUrl)
|
||||
{
|
||||
// Note: the "provider" parameter corresponds to the external
|
||||
@ -104,8 +120,7 @@ namespace Yavsc.Controllers
|
||||
return new ChallengeResult(Provider, properties);
|
||||
}
|
||||
|
||||
[HttpPost(Constants.LoginPath)]
|
||||
public async Task<IActionResult> Login(LoginViewModel model)
|
||||
public async Task<IActionResult> Login(SignInViewModel model)
|
||||
{
|
||||
if (ModelState.IsValid)
|
||||
{
|
||||
@ -136,7 +151,7 @@ namespace Yavsc.Controllers
|
||||
ModelState.AddModelError(string.Empty, "Unexpected behavior: something failed ... you could try again, or contact me ...");
|
||||
return View(model);
|
||||
}
|
||||
|
||||
|
||||
//
|
||||
// GET: /Account/Register
|
||||
[HttpGet]
|
||||
@ -194,6 +209,7 @@ namespace Yavsc.Controllers
|
||||
var info = await _signInManager.GetExternalLoginInfoAsync();
|
||||
if (info == null)
|
||||
{
|
||||
_logger.LogWarning("No external provider info found.");
|
||||
return Redirect("~/signin"); // RedirectToAction(nameof(OAuthController.SignIn));
|
||||
}
|
||||
|
||||
|
@ -47,14 +47,6 @@ namespace Yavsc.Controllers
|
||||
_logger = loggerFactory.CreateLogger<OAuthController>();
|
||||
}
|
||||
|
||||
|
||||
|
||||
[HttpGet(Constants.AccessDeniedPath)]
|
||||
public ActionResult Forbidden(string returnUrl = null)
|
||||
{
|
||||
return View("Forbidden", returnUrl);
|
||||
}
|
||||
|
||||
/*
|
||||
private async Task<string> GetToken(string purpose, string userid, DateTime? expires)
|
||||
{
|
||||
|
@ -4,7 +4,7 @@ using Owin;
|
||||
using System;
|
||||
using System.Collections.Generic;
|
||||
using System.Threading.Tasks;
|
||||
|
||||
#if OWIN
|
||||
namespace Yavsc
|
||||
{
|
||||
using Microsoft.AspNet.SignalR;
|
||||
@ -43,3 +43,4 @@ namespace Yavsc
|
||||
}
|
||||
}
|
||||
}
|
||||
#endif
|
||||
|
@ -10,7 +10,7 @@ using Yavsc.Models.Booking;
|
||||
namespace Yavsc.Models
|
||||
{
|
||||
|
||||
public class ApplicationDbContext : IdentityDbContext<ApplicationUser>, IApplicationStore
|
||||
public class ApplicationDbContext : IdentityDbContext<ApplicationUser>
|
||||
{
|
||||
protected override void OnModelCreating(ModelBuilder builder)
|
||||
{
|
||||
@ -151,7 +151,7 @@ namespace Yavsc.Models
|
||||
return Task.FromResult(0);
|
||||
}
|
||||
|
||||
IApplication IApplicationStore.FindApplication(string clientId)
|
||||
Application FindApplication(string clientId)
|
||||
{
|
||||
return Applications.FirstOrDefault(
|
||||
app=>app.ApplicationID == clientId);
|
||||
|
@ -2,7 +2,7 @@ using System.ComponentModel.DataAnnotations;
|
||||
|
||||
namespace Yavsc
|
||||
{
|
||||
public class Application : IApplication
|
||||
public class Application
|
||||
{
|
||||
[Key]
|
||||
public string ApplicationID { get; set; }
|
||||
|
@ -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;
|
||||
}
|
||||
);*/
|
||||
}
|
||||
}
|
||||
}
|
||||
|
@ -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);
|
||||
}
|
||||
}
|
||||
|
@ -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.
|
||||
|
@ -5,25 +5,50 @@ using Microsoft.AspNet.Http.Authentication;
|
||||
|
||||
namespace Yavsc.ViewModels.Account
|
||||
{
|
||||
public class LoginViewModel
|
||||
public class SignInViewModel
|
||||
{
|
||||
/// <summary>
|
||||
/// Local user's name.
|
||||
/// </summary>
|
||||
/// <returns></returns>
|
||||
[Required]
|
||||
public string UserName { get; set; }
|
||||
|
||||
/// <summary>
|
||||
/// Local user's password .
|
||||
/// </summary>
|
||||
/// <returns></returns>
|
||||
[Required]
|
||||
[DataType(DataType.Password)]
|
||||
public string Password { get; set; }
|
||||
|
||||
/// <summary>
|
||||
/// When true, asks for a two-factor identification
|
||||
/// </summary>
|
||||
/// <returns></returns>
|
||||
[Display(Name = "Remember me?")]
|
||||
public bool RememberMe { get; set; }
|
||||
|
||||
/// <summary>
|
||||
/// Indicates the authentication provider'name chosen to authenticate,
|
||||
/// contains "LOCAL" to choose the local application identity
|
||||
/// and user password credentials.
|
||||
/// </summary>
|
||||
/// <returns></returns>
|
||||
public string Provider { get; set; }
|
||||
|
||||
|
||||
/// <summary>
|
||||
/// This value indicates the OAuth client method recieving the code,
|
||||
/// in case of.
|
||||
/// This value does NOT indicate the OAuth client method recieving the code,
|
||||
/// but the one called once authorized.
|
||||
/// </summary>
|
||||
/// <returns></returns>
|
||||
public string ReturnUrl { get; set; }
|
||||
|
||||
|
||||
/// <summary>
|
||||
/// Lists external identity provider descriptions.
|
||||
/// </summary>
|
||||
/// <returns>an enumeration of the descriptions.</returns>
|
||||
public IEnumerable<AuthenticationDescription> ExternalProviders { get; set; }
|
||||
}
|
||||
}
|
||||
|
@ -1,5 +1,5 @@
|
||||
@using Microsoft.AspNet.Http
|
||||
@using System
|
||||
@using System
|
||||
@using System.Security.Claims
|
||||
@{
|
||||
var error = Context.Items["oauth.Error"];
|
||||
@ -12,7 +12,7 @@
|
||||
<title>Authorize Error</title>
|
||||
</head>
|
||||
<body>
|
||||
<h1>Katana.Sandbox.WebServer</h1>
|
||||
<h1>Identification & Authentication server</h1>
|
||||
<h2>OAuth2 Authorize Error</h2>
|
||||
<p>Error: @error</p>
|
||||
<p>@errorDescription</p>
|
||||
|
@ -1,7 +1,7 @@
|
||||
|
||||
@using Microsoft.AspNet.Http.Authentication
|
||||
@using Yavsc.ViewModels.Account
|
||||
@model LoginViewModel
|
||||
@model SignInViewModel
|
||||
@{
|
||||
ViewData["Title"] = SR["Log in"];
|
||||
}
|
||||
@ -38,7 +38,7 @@
|
||||
</div>
|
||||
<div class="form-group">
|
||||
<div class="col-md-offset-2 col-md-10">
|
||||
<button type="submit" class="btn btn-lg btn-success">@SR["Login"]</button>
|
||||
<button type="submit" class="btn btn-lg btn-success" name="submit.Signin">@SR["Login"]</button>
|
||||
</div>
|
||||
</div>
|
||||
<p>
|
||||
@ -47,7 +47,7 @@
|
||||
<p>
|
||||
<a asp-action="ForgotPassword" asp-controller="Account">@SR["Forgot your password"]?</a>
|
||||
</p>
|
||||
<input type="hidden" name="Provider" value="LOCAL" />
|
||||
<input type="hidden" name="Provider" value="LOCAL" />
|
||||
<input type="hidden" name="ReturnUrl" value="@Model.ReturnUrl" />
|
||||
|
||||
@Html.AntiForgeryToken()
|
||||
@ -67,10 +67,10 @@
|
||||
else
|
||||
{
|
||||
@foreach (var description in Model.ExternalProviders) {
|
||||
<form action="@Constants.LoginPath" method="post">
|
||||
<form action="@Constants.ExternalLoginPath" method="post">
|
||||
<input type="hidden" name="Provider" value="@description.AuthenticationScheme" />
|
||||
<input type="hidden" name="ReturnUrl" value="@Model.ReturnUrl" />
|
||||
<button class="btn btn-lg btn-success" type="submit">@SR["Connect using"] @description.DisplayName</button>
|
||||
<button class="btn btn-lg btn-success" type="submit" name="Submit.Login">@SR["Connect using"] @description.DisplayName</button>
|
||||
@Html.AntiForgeryToken()
|
||||
</form>
|
||||
}
|
||||
|
@ -2,6 +2,7 @@
|
||||
@{
|
||||
ViewBag.Title = "Oops!";
|
||||
}
|
||||
<h1>@ViewBag.Title</h1>
|
||||
<h2 class="text-danger">Your request cannot be served</h2>
|
||||
|
||||
<code>
|
||||
|
@ -19,7 +19,7 @@ else
|
||||
<ul class="nav navbar-nav navbar-right">
|
||||
<li><a class="navbar-link" asp-controller="Account" asp-action="Register" asp-route-returnurl="@Url.Action()" >@SR["Register"]</a></li>
|
||||
|
||||
<li><a class="navbar-link" asp-controller="Account" asp-action="Login" asp-route-returnurl="@Url.Action()" >@SR["Login"]</a></li>
|
||||
<li><a class="navbar-link" asp-controller="Account" asp-action="SignIn" asp-route-returnurl="@Url.Action()" >@SR["Login"]</a></li>
|
||||
</ul>
|
||||
}
|
||||
|
@ -67,9 +67,7 @@
|
||||
"Microsoft.AspNet.Localization": "1.0.0-rc1-final",
|
||||
"Microsoft.AspNet.Mvc": "6.0.0-rc1-*",
|
||||
"Microsoft.AspNet.Mvc.TagHelpers": "6.0.0-rc1-*",
|
||||
"Microsoft.AspNet.Owin": "1.0.0-rc1-final",
|
||||
"Microsoft.AspNet.Server.Kestrel": "1.0.0-rc1-final",
|
||||
"Microsoft.AspNet.SignalR.Owin": "1.2.2",
|
||||
"Microsoft.AspNet.SignalR.Core": "2.2.0",
|
||||
"Microsoft.AspNet.Server.WebListener": "1.0.0-rc1-final",
|
||||
"Microsoft.AspNet.StaticFiles": "1.0.0-rc1-*",
|
||||
|
File diff suppressed because it is too large
Load Diff
Reference in New Issue
Block a user