public Task ChallengeAsync(ChallengeContext context) { if (PriorHandler != null) { return PriorHandler.ChallengeAsync(context); } return Task.FromResult(0); }
public Task ChallengeAsync(ChallengeContext context) { bool handled = false; if (ShouldHandleScheme(context.AuthenticationScheme)) { switch (context.Behavior) { case ChallengeBehavior.Automatic: // If there is a principal already, invoke the forbidden code path if (User == null) { goto case ChallengeBehavior.Unauthorized; } else { goto case ChallengeBehavior.Forbidden; } case ChallengeBehavior.Unauthorized: HttpContext.Response.StatusCode = 401; // We would normally set the www-authenticate header here, but IIS does that for us. break; case ChallengeBehavior.Forbidden: HttpContext.Response.StatusCode = 403; handled = true; // No other handlers need to consider this challenge. break; } context.Accept(); } if (!handled && PriorHandler != null) { return PriorHandler.ChallengeAsync(context); } return Task.FromResult(0); }
public Task ChallengeAsync(ChallengeContext context) { throw new NotImplementedException(); }
public GenericRepository(ChallengeContext ctx) { _dbContext = ctx; }
public UnitOfWork(ChallengeContext context) { _context = context; Users = new UserRepository(_context); }
/// <inheritdoc /> protected override Task <bool> HandleForbiddenAsync(ChallengeContext context) { Response.Headers[WWWAuthenticateHeader] = $"{Options.AuthenticationScheme} realm=\"{Options.Realm}\""; return(base.HandleForbiddenAsync(context)); }
protected override async Task <bool> HandleUnauthorizedAsync(ChallengeContext context) { Response.StatusCode = 401; Response.Headers["WWW-Authenticate"] = "Bearer"; return(false); }
protected override Task <bool> HandleUnauthorizedAsync(ChallengeContext context) { return(base.HandleUnauthorizedAsync(context)); }
protected override Task <bool> HandleUnauthorizedAsync(ChallengeContext context) { Response.StatusCode = 401; Response.Headers[ChallengeHeader] = "Basic realm=\"" + Options.Realm + "\""; return(Task.FromResult(false)); }
public Task ChallengeAsync(ChallengeContext context) { context.Accept(); return TaskCache.CompletedTask; }
/// <summary> /// Responds to a 401 Challenge. Sends an OpenIdConnect message to the 'identity authority' to obtain an identity. /// </summary> /// <returns></returns> /// <remarks>Uses log id's OIDCH-0026 - OIDCH-0050, next num: 37</remarks> protected override async Task <bool> HandleUnauthorizedAsync([NotNull] ChallengeContext context) { Logger.LogDebug(Resources.OIDCH_0026_ApplyResponseChallengeAsync, this.GetType()); // order for local RedirectUri // 1. challenge.Properties.RedirectUri // 2. CurrentUri if Options.DefaultToCurrentUriOnRedirect is true) AuthenticationProperties properties = new AuthenticationProperties(context.Properties); if (!string.IsNullOrEmpty(properties.RedirectUri)) { Logger.LogDebug(Resources.OIDCH_0030_Using_Properties_RedirectUri, properties.RedirectUri); } else if (Options.DefaultToCurrentUriOnRedirect) { Logger.LogDebug(Resources.OIDCH_0032_UsingCurrentUriRedirectUri, CurrentUri); properties.RedirectUri = CurrentUri; } if (_configuration == null && Options.ConfigurationManager != null) { _configuration = await Options.ConfigurationManager.GetConfigurationAsync(Context.RequestAborted); } var message = new OpenIdConnectMessage { ClientId = Options.ClientId, IssuerAddress = _configuration?.AuthorizationEndpoint ?? string.Empty, RedirectUri = Options.RedirectUri, // [brentschmaltz] - #215 this should be a property on RedirectToIdentityProviderNotification not on the OIDCMessage. RequestType = OpenIdConnectRequestType.AuthenticationRequest, Resource = Options.Resource, ResponseType = Options.ResponseType, Scope = Options.Scope }; // Omitting the response_mode parameter when it already corresponds to the default // response_mode used for the specified response_type is recommended by the specifications. // See http://openid.net/specs/oauth-v2-multiple-response-types-1_0.html#ResponseModes if (!string.Equals(Options.ResponseType, OpenIdConnectResponseTypes.Code, StringComparison.Ordinal) || !string.Equals(Options.ResponseMode, OpenIdConnectResponseModes.Query, StringComparison.Ordinal)) { message.ResponseMode = Options.ResponseMode; } if (Options.ProtocolValidator.RequireNonce) { message.Nonce = Options.ProtocolValidator.GenerateNonce(); if (Options.CacheNonces) { if (await Options.NonceCache.GetAsync(message.Nonce) != null) { Logger.LogError(Resources.OIDCH_0033_NonceAlreadyExists, message.Nonce); throw new OpenIdConnectProtocolException(string.Format(CultureInfo.InvariantCulture, Resources.OIDCH_0033_NonceAlreadyExists, message.Nonce)); } await Options.NonceCache.SetAsync(message.Nonce, new byte[0], new DistributedCacheEntryOptions { AbsoluteExpirationRelativeToNow = Options.ProtocolValidator.NonceLifetime }); } else { WriteNonceCookie(message.Nonce); } } if (Options.Notifications.RedirectToIdentityProvider != null) { var redirectToIdentityProviderNotification = new RedirectToIdentityProviderNotification <OpenIdConnectMessage, OpenIdConnectAuthenticationOptions>(Context, Options) { ProtocolMessage = message }; await Options.Notifications.RedirectToIdentityProvider(redirectToIdentityProviderNotification); if (redirectToIdentityProviderNotification.HandledResponse) { Logger.LogVerbose(Resources.OIDCH_0034_RedirectToIdentityProviderNotificationHandledResponse); return(true); } else if (redirectToIdentityProviderNotification.Skipped) { Logger.LogVerbose(Resources.OIDCH_0035_RedirectToIdentityProviderNotificationSkipped); return(false); } if (!string.IsNullOrEmpty(redirectToIdentityProviderNotification.ProtocolMessage.State)) { properties.Items[OpenIdConnectAuthenticationDefaults.UserstatePropertiesKey] = redirectToIdentityProviderNotification.ProtocolMessage.State; } message = redirectToIdentityProviderNotification.ProtocolMessage; } var redirectUriForCode = message.RedirectUri; if (string.IsNullOrEmpty(redirectUriForCode)) { Logger.LogDebug(Resources.OIDCH_0031_Using_Options_RedirectUri, Options.RedirectUri); redirectUriForCode = Options.RedirectUri; } if (!string.IsNullOrEmpty(redirectUriForCode)) { // When redeeming a 'code' for an AccessToken, this value is needed properties.Items.Add(OpenIdConnectAuthenticationDefaults.RedirectUriForCodePropertiesKey, redirectUriForCode); } message.State = Options.StateDataFormat.Protect(properties); var redirectUri = message.CreateAuthenticationRequestUrl(); if (!Uri.IsWellFormedUriString(redirectUri, UriKind.Absolute)) { Logger.LogWarning(Resources.OIDCH_0036_UriIsNotWellFormed, redirectUri); } Response.Redirect(redirectUri); return(true); }
public UsersController(ChallengeContext context) { _unitOfWork = new UnitOfWork(context); }
protected override async Task <bool> HandleUnauthorizedAsync(ChallengeContext context) { var properties = new AuthenticationProperties(context.Properties); var configuration = await Options.ConfigurationManager.GetConfigurationAsync(Context.RequestAborted); if (configuration == null) { throw new InvalidOperationException("The OpenID 2.0 authentication middleware was unable to retrieve " + "the provider configuration from the OpenID 2.0 authentication server."); } if (string.IsNullOrEmpty(configuration.AuthenticationEndpoint)) { throw new InvalidOperationException("The OpenID 2.0 authentication middleware was unable to retrieve " + "the authentication endpoint address from the discovery document."); } // Determine the realm using the current address // if one has not been explicitly provided; var realm = Options.Realm; if (string.IsNullOrEmpty(realm)) { realm = Request.Scheme + "://" + Request.Host + OriginalPathBase; } // Use the current address as the final location where the user agent // will be redirected to if one has not been explicitly provided. if (string.IsNullOrEmpty(properties.RedirectUri)) { properties.RedirectUri = Request.Scheme + "://" + Request.Host + OriginalPathBase + Request.Path + Request.QueryString; } // Store the return_to parameter for later comparison. properties.Items[OpenIdAuthenticationConstants.Properties.ReturnTo] = Request.Scheme + "://" + Request.Host + OriginalPathBase + Options.CallbackPath; // Generate a new anti-forgery token. GenerateCorrelationId(properties); // Create a new message containing the OpenID 2.0 request parameters. // See http://openid.net/specs/openid-authentication-2_0.html#requesting_authentication var message = new OpenIdAuthenticationMessage { ClaimedIdentifier = "http://specs.openid.net/auth/2.0/identifier_select", Identity = "http://specs.openid.net/auth/2.0/identifier_select", Mode = OpenIdAuthenticationConstants.Modes.CheckIdSetup, Namespace = OpenIdAuthenticationConstants.Namespaces.OpenId, Realm = realm, ReturnTo = QueryHelpers.AddQueryString( uri: properties.Items[OpenIdAuthenticationConstants.Properties.ReturnTo], name: OpenIdAuthenticationConstants.Parameters.State, value: Options.StateDataFormat.Protect(properties)) }; if (Options.Attributes.Count != 0) { // openid.ns.ax (http://openid.net/srv/ax/1.0) message.SetParameter( prefix: OpenIdAuthenticationConstants.Prefixes.Namespace, name: OpenIdAuthenticationConstants.Aliases.Ax, value: OpenIdAuthenticationConstants.Namespaces.Ax); // openid.ax.mode (fetch_request) message.SetParameter( prefix: OpenIdAuthenticationConstants.Prefixes.Ax, name: OpenIdAuthenticationConstants.Parameters.Mode, value: OpenIdAuthenticationConstants.Modes.FetchRequest); foreach (var attribute in Options.Attributes) { message.SetParameter( prefix: OpenIdAuthenticationConstants.Prefixes.Ax, name: $"{OpenIdAuthenticationConstants.Prefixes.Type}.{attribute.Key}", value: attribute.Value); } // openid.ax.required message.SetParameter( prefix: OpenIdAuthenticationConstants.Prefixes.Ax, name: OpenIdAuthenticationConstants.Parameters.Required, value: string.Join(",", Options.Attributes.Select(attribute => attribute.Key))); } var address = QueryHelpers.AddQueryString(configuration.AuthenticationEndpoint, message.Parameters); Response.Redirect(address); return(true); }
/// <summary> /// Responds to a 401 Challenge. Sends an OpenIdConnect message to the 'identity authority' to obtain an identity. /// </summary> /// <returns></returns> protected override async Task <bool> HandleUnauthorizedAsync(ChallengeContext context) { if (context == null) { throw new ArgumentNullException(nameof(context)); } Logger.EnteringOpenIdAuthenticationHandlerHandleUnauthorizedAsync(GetType().FullName); // order for local RedirectUri // 1. challenge.Properties.RedirectUri // 2. CurrentUri if RedirectUri is not set) var properties = new AuthenticationProperties(context.Properties) { ExpiresUtc = Options.SystemClock.UtcNow.Add(Options.RemoteAuthenticationTimeout) }; if (string.IsNullOrEmpty(properties.RedirectUri)) { properties.RedirectUri = CurrentUri; } Logger.PostAuthenticationLocalRedirect(properties.RedirectUri); if (_configuration == null && Options.ConfigurationManager != null) { _configuration = await Options.ConfigurationManager.GetConfigurationAsync(Context.RequestAborted); } var message = new OpenIdConnectMessage { ClientId = Options.ClientId, IssuerAddress = _configuration?.AuthorizationEndpoint ?? string.Empty, RedirectUri = BuildRedirectUri(Options.CallbackPath), Resource = Options.Resource, ResponseType = Options.ResponseType, Scope = string.Join(" ", Options.Scope) }; // Omitting the response_mode parameter when it already corresponds to the default // response_mode used for the specified response_type is recommended by the specifications. // See http://openid.net/specs/oauth-v2-multiple-response-types-1_0.html#ResponseModes if (!string.Equals(Options.ResponseType, OpenIdConnectResponseTypes.Code, StringComparison.Ordinal) || !string.Equals(Options.ResponseMode, OpenIdConnectResponseModes.Query, StringComparison.Ordinal)) { message.ResponseMode = Options.ResponseMode; } if (Options.ProtocolValidator.RequireNonce) { message.Nonce = Options.ProtocolValidator.GenerateNonce(); WriteNonceCookie(message.Nonce); } GenerateCorrelationId(properties); var redirectContext = new RedirectContext(Context, Options, properties) { ProtocolMessage = message }; await Options.Events.RedirectToIdentityProvider(redirectContext); if (redirectContext.HandledResponse) { Logger.RedirectToIdentityProviderHandledResponse(); return(true); } else if (redirectContext.Skipped) { Logger.RedirectToIdentityProviderSkipped(); return(false); } message = redirectContext.ProtocolMessage; if (!string.IsNullOrEmpty(message.State)) { properties.Items[OpenIdConnectDefaults.UserstatePropertiesKey] = message.State; } // When redeeming a 'code' for an AccessToken, this value is needed properties.Items.Add(OpenIdConnectDefaults.RedirectUriForCodePropertiesKey, message.RedirectUri); message.State = Options.StateDataFormat.Protect(properties); if (Options.AuthenticationMethod == OpenIdConnectRedirectBehavior.RedirectGet) { var redirectUri = message.CreateAuthenticationRequestUrl(); if (!Uri.IsWellFormedUriString(redirectUri, UriKind.Absolute)) { Logger.InvalidAuthenticationRequestUrl(redirectUri); } Response.Redirect(redirectUri); return(true); } else if (Options.AuthenticationMethod == OpenIdConnectRedirectBehavior.FormPost) { var inputs = new StringBuilder(); foreach (var parameter in message.Parameters) { var name = HtmlEncoder.Encode(parameter.Key); var value = HtmlEncoder.Encode(parameter.Value); var input = string.Format(CultureInfo.InvariantCulture, InputTagFormat, name, value); inputs.AppendLine(input); } var issuer = HtmlEncoder.Encode(message.IssuerAddress); var content = string.Format(CultureInfo.InvariantCulture, HtmlFormFormat, issuer, inputs); var buffer = Encoding.UTF8.GetBytes(content); Response.ContentLength = buffer.Length; Response.ContentType = "text/html;charset=UTF-8"; // Emit Cache-Control=no-cache to prevent client caching. Response.Headers[HeaderNames.CacheControl] = "no-cache"; Response.Headers[HeaderNames.Pragma] = "no-cache"; Response.Headers[HeaderNames.Expires] = "-1"; await Response.Body.WriteAsync(buffer, 0, buffer.Length); return(true); } throw new NotImplementedException($"An unsupported authentication method has been configured: {Options.AuthenticationMethod}"); }
protected override Task <bool> HandleForbiddenAsync(ChallengeContext context) => HandleUnauthorizedAsync(context);
protected override Task <bool> HandleForbiddenAsync(ChallengeContext context) { return(base.HandleForbiddenAsync(context)); }
public async Task <List <Product> > GetAllWithCategories() { using var context = new ChallengeContext(); return(await context.Products.Include(p => p.Category).ToListAsync()); }
public Task ChallengeAsync(ChallengeContext context) { return(_handler.ChallengeAsync(context)); }
public CommentRepository(ChallengeContext context) : base(context) { }
public OperationController(ChallengeContext context) { _context = context; }
protected override async Task <bool> HandleUnauthorizedAsync(ChallengeContext context) { var properties = new AuthenticationProperties(context.Properties); if (Options.Endpoint == null) { // Note: altering options during a request is not thread safe but // would only result in multiple discovery requests in the worst case. Options.Endpoint = await DiscoverEndpointAsync(Options.Authority); } if (Options.Endpoint == null) { Logger.LogError("The user agent cannot be redirected to the identity provider because no " + "endpoint was registered in the options or discovered through Yadis."); return(true); } // Determine the realm using the current address // if one has not been explicitly provided; var realm = Options.Realm; if (string.IsNullOrEmpty(realm)) { realm = Request.Scheme + "://" + Request.Host + OriginalPathBase; } // Use the current address as the final location where the user agent // will be redirected to if one has not been explicitly provided. if (string.IsNullOrEmpty(properties.RedirectUri)) { properties.RedirectUri = Request.Scheme + "://" + Request.Host + OriginalPathBase + Request.Path + Request.QueryString; } // Store the return_to parameter for later comparison. properties.Items[OpenIdAuthenticationConstants.Properties.ReturnTo] = Request.Scheme + "://" + Request.Host + OriginalPathBase + Options.CallbackPath; // Generate a new anti-forgery token. GenerateCorrelationId(properties); var state = UrlEncoder.Encode(Options.StateDataFormat.Protect(properties)); // Create a new message containing the OpenID 2.0 request parameters. // See http://openid.net/specs/openid-authentication-2_0.html#requesting_authentication var message = new OpenIdAuthenticationMessage { ClaimedIdentifier = "http://specs.openid.net/auth/2.0/identifier_select", Identity = "http://specs.openid.net/auth/2.0/identifier_select", Mode = OpenIdAuthenticationConstants.Modes.CheckIdSetup, Namespace = OpenIdAuthenticationConstants.Namespaces.OpenId, Realm = realm, ReturnTo = QueryHelpers.AddQueryString( uri: properties.Items[OpenIdAuthenticationConstants.Properties.ReturnTo], name: OpenIdAuthenticationConstants.Parameters.State, value: state) }; if (Options.Attributes.Count != 0) { // openid.ns.ax (http://openid.net/srv/ax/1.0) message.SetParameter( prefix: OpenIdAuthenticationConstants.Prefixes.Namespace, name: OpenIdAuthenticationConstants.Aliases.Ax, value: OpenIdAuthenticationConstants.Namespaces.Ax); // openid.ax.mode (fetch_request) message.SetParameter( prefix: OpenIdAuthenticationConstants.Prefixes.Ax, name: OpenIdAuthenticationConstants.Parameters.Mode, value: OpenIdAuthenticationConstants.Modes.FetchRequest); foreach (var attribute in Options.Attributes) { message.SetParameter( prefix: OpenIdAuthenticationConstants.Prefixes.Ax, name: $"{OpenIdAuthenticationConstants.Prefixes.Type}.{attribute.Key}", value: attribute.Value); } // openid.ax.required message.SetParameter( prefix: OpenIdAuthenticationConstants.Prefixes.Ax, name: OpenIdAuthenticationConstants.Parameters.Required, value: string.Join(",", Options.Attributes.Select(attribute => attribute.Key))); } Response.Redirect(await GenerateChallengeUrlAsync(message)); return(true); }
protected override Task <bool> HandleForbiddenAsync(ChallengeContext context) { throw new NotSupportedException(); }
/// <summary> /// Override this method to deal with 401 challenge concerns, if an authentication scheme in question /// deals an authentication interaction as part of it's request flow. (like adding a response header, or /// changing the 401 result to 302 of a login page or external sign-in location.) /// </summary> /// <param name="context"></param> /// <returns>True if no other handlers should be called</returns> protected override async Task <bool> HandleUnauthorizedAsync(ChallengeContext context) { if (context == null) { throw new ArgumentNullException(nameof(context)); } Logger.LogTrace($"Entering {nameof(WsFederationAuthenticationHandler)}'s HandleUnauthorizedAsync"); if (_configuration == null) { _configuration = await Options.ConfigurationManager.GetConfigurationAsync(Context.RequestAborted); } var baseUri = Request.Scheme + Uri.SchemeDelimiter + Request.Host + Request.PathBase; var currentUri = baseUri + Request.Path + Request.QueryString; var properties = new AuthenticationProperties(context.Properties); if (string.IsNullOrEmpty(properties.RedirectUri)) { properties.RedirectUri = currentUri; } var wsFederationMessage = new WsFederationMessage { IssuerAddress = _configuration.TokenEndpoint ?? string.Empty, Wtrealm = Options.Wtrealm, Wctx = $"{WsFederationAuthenticationDefaults.WctxKey}={Uri.EscapeDataString(Options.StateDataFormat.Protect(properties))}", Wa = WsFederationActions.SignIn, Wreply = BuildWreply(Options.CallbackPath) }; if (!string.IsNullOrWhiteSpace(Options.Wreply)) { wsFederationMessage.Wreply = Options.Wreply; } var redirectContext = new RedirectContext(Context, Options) { ProtocolMessage = wsFederationMessage, Properties = properties }; await Options.Events.RedirectToIdentityProvider(redirectContext); if (redirectContext.HandledResponse) { Logger.LogDebug("RedirectContext.HandledResponse"); return(true); } if (redirectContext.Skipped) { Logger.LogDebug("RedirectContext.Skipped"); return(false); } var redirectUri = redirectContext.ProtocolMessage.CreateSignInUrl(); if (!Uri.IsWellFormedUriString(redirectUri, UriKind.Absolute)) { Logger.LogWarning($"The sign-in redirect URI is malformed: {redirectUri}"); } Response.Redirect(redirectUri); return(true); }
public ChallengeDbFunction(ChallengeContext context) { this.context = context; }
// private System.Data.Entity.DbContextTransaction dbTran; //http://www.entityframeworktutorial.net/entityframework6/transaction-in-entity-framework.aspx public BaseRepository(ChallengeContext _context) { Context = _context; }
public Task ChallengeAsync(ChallengeContext context) { context.Accept(); return(Task.CompletedTask); }
/// <summary> /// </summary> /// <param name="context"></param> /// <returns>True if no other handlers should be called</returns> protected virtual Task <bool> HandleForbiddenAsync(ChallengeContext context) { Response.StatusCode = 403; return(Task.FromResult(true)); }
public override async Task ChallengeAsync(string authenticationScheme, AuthenticationProperties properties, ChallengeBehavior behavior) { if (string.IsNullOrEmpty(authenticationScheme)) { throw new ArgumentException(nameof(authenticationScheme)); } var handler = HttpAuthenticationFeature.Handler; var challengeContext = new ChallengeContext(authenticationScheme, properties?.Items, behavior); if (handler != null) { await handler.ChallengeAsync(challengeContext); } if (!challengeContext.Accepted) { throw new InvalidOperationException($"No authentication handler is configured to handle the scheme: {authenticationScheme}"); } }
/// <summary> /// Override this method to deal with 401 challenge concerns, if an authentication scheme in question /// deals an authentication interaction as part of it's request flow. (like adding a response header, or /// changing the 401 result to 302 of a login page or external sign-in location.) /// </summary> /// <param name="context"></param> /// <returns>True if no other handlers should be called</returns> protected virtual Task <bool> HandleUnauthorizedAsync(ChallengeContext context) { Response.StatusCode = 401; return(Task.FromResult(false)); }
/// <summary> /// Invoked before a challenge is sent back to the caller. /// </summary> public virtual Task Challenge(ChallengeContext context) => OnChallenge(context);
public OrderRepository(ChallengeContext _context) : base(_context) { }