/// <summary> /// Initializes a new instance of the <see cref="BaseBasicContext" /> class. /// </summary> /// <param name="context">The HTTP request context.</param> /// <param name="options">The middleware options.</param> public BaseBasicContext(HttpContext context, BasicAuthenticationOptions options) : base(context) { //Requires.NotNull(options, nameof(options)); Options = options; }
private static TestServer CreateServer( BasicAuthenticationOptions configureOptions, Func <HttpContext, bool> handler = null, Uri baseAddress = null) { var builder = new WebHostBuilder() .Configure(app => { app.UseAuthentication(); app.Use(async(context, next) => { var request = context.Request; var response = context.Response; if (request.Path == new PathString("/")) { response.StatusCode = (int)HttpStatusCode.OK; } else if (request.Path == new PathString("/unauthorized")) { response.StatusCode = (int)HttpStatusCode.Unauthorized; } else if (request.Path == new PathString("/forbidden")) { await context.ForbidAsync(BasicAuthenticationDefaults.AuthenticationScheme); } else if (request.Path == new PathString("/challenge")) { await context.ChallengeAsync(BasicAuthenticationDefaults.AuthenticationScheme); } else { await next(); } }); }) .ConfigureServices(services => { if (configureOptions != null) { services.AddAuthentication(BasicAuthenticationDefaults.AuthenticationScheme).AddBasic(options => { options.Realm = configureOptions.Realm; options.Events = configureOptions.Events; }); } else { services.AddAuthentication(BasicAuthenticationDefaults.AuthenticationScheme).AddBasic(); } }); var server = new TestServer(builder) { BaseAddress = baseAddress }; return(server); }
public void SettingANonAsciiRealmThrows() { var options = new BasicAuthenticationOptions(); Exception ex = Assert.Throws <ArgumentOutOfRangeException>(() => options.Realm = "💩"); Assert.Equal("Realm must be US ASCII\r\nParameter name: Realm", ex.Message); }
void ConfigureBasicAuth(BasicAuthenticationOptions options) { options.Realm = "shawnl.ink"; options.AllowInsecureProtocol = true; options.Events = new BasicAuthenticationEvents { OnValidateCredentials = context => { if (context.Username == _config.Security.Username && context.Password == _config.Security.Password) { var claims = new[] { new Claim( ClaimTypes.NameIdentifier, context.Username, ClaimValueTypes.String, context.Options.ClaimsIssuer), new Claim( ClaimTypes.Name, context.Username, ClaimValueTypes.String, context.Options.ClaimsIssuer) }; context.Principal = new ClaimsPrincipal( new ClaimsIdentity(claims, context.Scheme.Name)); context.Success(); } return(Task.CompletedTask); } }; options.Validate(); }
public void SettingAnAsciiRealWorks() { const string realm = "Realm"; var options = new BasicAuthenticationOptions { Realm = realm }; Assert.Equal(realm, options.Realm); }
/// <summary> /// Adds a Basic authentication middleware to your web application pipeline. /// </summary> /// <param name="app">The application builder.</param> /// <param name="configureOptions">The middleware options configuration.</param> public static IApplicationBuilder UseBasicAuthentication(this IApplicationBuilder app, Action<BasicAuthenticationOptions> configureOptions) { var options = new BasicAuthenticationOptions(); if (configureOptions != null) { configureOptions(options); } return app.UseBasicAuthentication(options); }
/// <summary> /// Adds a Basic authentication middleware to your web application pipeline. /// </summary> /// <param name="app">The application builder.</param> /// <param name="configureOptions">The middleware options configuration.</param> public static IApplicationBuilder UseBasicAuthentication(this IApplicationBuilder app, Action <BasicAuthenticationOptions> configureOptions) { var options = new BasicAuthenticationOptions(); if (configureOptions != null) { configureOptions(options); } return(app.UseBasicAuthentication(options)); }
/// <summary></summary> /// <param name="appBuilder"></param> /// <param name="provider"></param> public static void UseBasicAuthentication(this IAppBuilder appBuilder, IBasicAuthenticationProvider provider) { if (provider == null) { throw new ArgumentNullException("provider"); } BasicAuthenticationOptions options = new BasicAuthenticationOptions { Provider = provider }; UseBasicAuthentication(appBuilder, options); }
public DependencyModule( ILogger <DependencyModule> logger, SharedOptions sharedOptions, CompaniesHouseOptions coHoOptions, ResponseCachingOptions responseCachingOptions, DistributedCacheOptions distributedCacheOptions, DataProtectionOptions dataProtectionOptions, BasicAuthenticationOptions basicAuthenticationOptions) { _logger = logger; _sharedOptions = sharedOptions; _coHoOptions = coHoOptions; _responseCachingOptions = responseCachingOptions; _distributedCacheOptions = distributedCacheOptions; _dataProtectionOptions = dataProtectionOptions; _basicAuthenticationOptions = basicAuthenticationOptions; }
/// <summary></summary> /// <param name="appBuilder"></param> /// <param name="options"></param> public static void UseBasicAuthentication(this IAppBuilder appBuilder, BasicAuthenticationOptions options) { if (appBuilder == null) { throw new ArgumentNullException("appBuilder"); } if (options == null) { throw new ArgumentNullException("options"); } appBuilder.Use(typeof(BasicAuthenticationMiddleware), options); appBuilder.MarkStage("Authenticate"); }
public static void Configure(BasicAuthenticationOptions options) { options.Realm = "idunno"; options.AllowInsecureProtocol = true; options.Events = new BasicAuthenticationEvents { OnValidateCredentials = context => { var identity = UserIdentities.GetIdentity(context.Username, context.Password); if (identity != null) { context.Principal = new ClaimsPrincipal(identity); context.Success(); } return(Task.CompletedTask); } }; }
private void ConfigureBasicAuthOptions(BasicAuthenticationOptions options) { options.Realm = "Radario"; options.Events = new BasicAuthenticationEvents { OnValidatePrincipal = context => { if ((context.UserName == "radario") && (context.Password == "qwertyp0p")) { var claims = new List <Claim> { new Claim(ClaimTypes.Name, context.UserName, context.Options.ClaimsIssuer) }; var principal = new ClaimsPrincipal(new ClaimsIdentity(claims, BasicAuthenticationDefaults.AuthenticationScheme)); context.Principal = principal; } else { context.AuthenticationFailMessage = "Authentication failed."; } return(Task.CompletedTask); } }; }
public static IAppBuilder UseBasicAuthentication(this IAppBuilder app, string realm, BasicAuthenticationMiddleware.CredentialValidationFunction validationFunction) { var options = new BasicAuthenticationOptions(realm, validationFunction); return(app.UseBasicAuthentication(options)); }
public Task <bool> IsValidUserAsync(BasicAuthenticationOptions options, string username, string password) { return(Task.FromResult(true)); }
/// <summary> /// Creates a new instance of the context object. /// </summary> /// <param name="context">The HTTP request context.</param> /// <param name="options">The middleware options.</param> /// <param name="userName">The user name (login, e-mail, etc.) used.</param> /// <param name="password">The password (secret).</param> public BasicSignInContext(HttpContext context, BasicAuthenticationOptions options, string userName, string password) : base(context, options) { UserName = userName; Password = password; }
public static IAppBuilder UseBasicAuthentication(this IAppBuilder app, BasicAuthenticationOptions options) { return(app.Use <BasicAuthenticationMiddleware>(options)); }
public void ConfigureAuth(IAppBuilder app) { var basicAuthOptions = new BasicAuthenticationOptions("contosoodata", async(username, password) => await Authenticate(username, password)); app.UseBasicAuthentication(basicAuthOptions); }
/// <summary> /// Adds a cookie-based authentication middleware to your web application pipeline. /// </summary> /// <param name="app">The application builder.</param> /// <param name="options">The middleware options configuration.</param> public static IApplicationBuilder UseBasicAuthentication(this IApplicationBuilder app, BasicAuthenticationOptions options) { //Requires.NotNull(options, nameof(options)); return app.UseMiddleware<BasicAuthenticationMiddleware>(options); }
/// <summary> /// Adds OAuth2 Authorization Server capabilities to an OWIN web application. This middleware /// performs the request processing for the Authorize and Token endpoints defined by the OAuth2 specification. /// See also http://tools.ietf.org/html/rfc6749 /// </summary> /// <param name="app">The web application builder</param> /// <param name="options">Options which control the behavior of the Authorization Server.</param> /// <returns>The application builder</returns> public static IAppBuilder UseSentinelAuthorizationServer(this IAppBuilder app, SentinelAuthorizationServerOptions options) { if (app == null) { throw new ArgumentNullException(nameof(app)); } // Last minute default configurations if (options.Logger == null) { options.Logger = LogManager.GetLogger("Sentinel.OAuth"); } if (options.IssuerUri == null) { throw new InvalidOperationException("IssuerUri must be set"); } if (options.TokenCryptoProvider == null) { options.TokenCryptoProvider = new SHA2CryptoProvider(HashAlgorithm.SHA256); } if (options.PasswordCryptoProvider == null) { options.PasswordCryptoProvider = new PBKDF2CryptoProvider(); } if (options.SignatureCryptoProvider == null) { options.SignatureCryptoProvider = new AsymmetricCryptoProvider(); } if (options.PrincipalProvider == null) { options.PrincipalProvider = new PrincipalProvider(options.TokenCryptoProvider); } if (options.UserRepository == null && options.UserManager == null) { throw new InvalidOperationException("UserRepository must be set if not using a specific UserManager"); } if (options.ClientRepository == null && options.ClientManager == null) { throw new InvalidOperationException("ClientRepository must be set if not using a specific ClientManager"); } if (options.TokenRepository == null) { options.TokenRepository = new MemoryTokenRepository(); } if (options.TokenProvider == null) { options.TokenProvider = new JwtTokenProvider(new JwtTokenProviderConfiguration(options.TokenCryptoProvider, options.IssuerUri, options.TokenCryptoProvider.CreateHash(256))); } if (options.TokenManager == null) { options.TokenManager = new TokenManager(options.Logger, options.PrincipalProvider, options.TokenProvider, options.TokenRepository); } if (options.UserManager == null && options.UserRepository != null) { options.UserManager = new UserManager(options.Logger, options.PasswordCryptoProvider, options.SignatureCryptoProvider, options.UserRepository, options.UserApiKeyRepository, options.ClientRepository); } if (options.ClientManager == null && options.ClientRepository != null) { options.ClientManager = new ClientManager(options.Logger, options.PasswordCryptoProvider, options.SignatureCryptoProvider, options.ClientRepository); } var oauthOptions = new OAuthAuthorizationServerOptions { AllowInsecureHttp = true, AccessTokenExpireTimeSpan = options.AccessTokenLifetime, AuthorizationCodeExpireTimeSpan = options.AuthorizationCodeLifetime, AuthorizeEndpointPath = new PathString(options.AuthorizationCodeEndpointUrl), TokenEndpointPath = new PathString(options.TokenEndpointUrl), Provider = new SentinelAuthorizationServerProvider(options), AccessTokenProvider = new SentinelAccessTokenProvider(options), AuthorizationCodeProvider = new SentinelAuthorizationCodeProvider(options), RefreshTokenProvider = new SentinelRefreshTokenProvider(options) }; // Initialize underlying OWIN OAuth system app.UseOAuthAuthorizationServer(oauthOptions); app.UseOAuthBearerAuthentication(new OAuthBearerAuthenticationOptions() { AccessTokenProvider = oauthOptions.AccessTokenProvider }); // Initialize basic auth if specified if (options.EnableBasicAuthentication) { var basicAuthenticationOptions = new BasicAuthenticationOptions() { ClientManager = options.ClientManager, UserManager = options.UserManager, Logger = options.Logger, RequireSecureConnection = options.RequireSecureConnection, Realm = options.Realm }; app.Use <BasicAuthenticationMiddleware>(basicAuthenticationOptions, oauthOptions); } if (options.EnableSignatureAuthentication) { var apiKeyAuthenticationOptions = new SignatureAuthenticationOptions() { ClientManager = options.ClientManager, UserManager = options.UserManager, Logger = options.Logger, Realm = options.Realm, RequireSecureConnection = options.RequireSecureConnection, MaximumClockSkew = options.MaximumClockSkew }; app.Use <SignatureAuthenticationMiddleware>(apiKeyAuthenticationOptions, oauthOptions); } app.UseStageMarker(PipelineStage.Authenticate); // Set up identity endpoint app.Map(options.IdentityEndpointUrl, config => config.Use <UserInfoMiddleware>()); return(app); }
// Strongly typed middleware usage public static IAppBuilder UseBasicAuthentication(this IAppBuilder app, string realm, Func<string, string, Task<bool>> validator) { var options = new BasicAuthenticationOptions(realm, validator); return app.Use<BasicAuthenticationMiddleware>(options); }
/// <summary> /// Adds a cookie-based authentication middleware to your web application pipeline. /// </summary> /// <param name="app">The application builder.</param> /// <param name="options">The middleware options configuration.</param> public static IApplicationBuilder UseBasicAuthentication(this IApplicationBuilder app, BasicAuthenticationOptions options) { //Requires.NotNull(options, nameof(options)); return(app.UseMiddleware <BasicAuthenticationMiddleware>(options)); }