public Task <bool> InvokeAsync(IDictionary <string, object> environment) { IOwinEnvironment context = new DefaultOwinEnvironment(environment); var client = environment.Get <IClient>(OwinKeys.StormpathClient); var configuration = environment.Get <StormpathConfiguration>(OwinKeys.StormpathConfiguration); var authenticatedUser = environment.Get <IAccount>(OwinKeys.StormpathUser); var authenticationScheme = environment.Get <string>(OwinKeys.StormpathUserScheme); var deleteCookieAction = new Action <WebCookieConfiguration>(cookie => Cookies.DeleteTokenCookie(context, cookie, logger)); var setStatusCodeAction = new Action <int>(code => context.Response.StatusCode = code); var setHeaderAction = new Action <string, string>((name, value) => context.Response.Headers.SetString(name, value)); var redirectAction = new Action <string>(location => context.Response.Headers.SetString("Location", location)); var handler = new RouteProtector( client, configuration, deleteCookieAction, setStatusCodeAction, setHeaderAction, redirectAction, logger); if (handler.IsAuthenticated(authenticationScheme, RouteProtector.AnyScheme, authenticatedUser)) { return(TaskConstants.CompletedTask); // Authentication check succeeded } logger.Info("User attempted to access a protected endpoint with invalid credentials."); handler.OnUnauthorized(context.Request.Headers.GetString("Accept"), context.Request.Path); return(Task.FromResult(false)); // Authentication check failed }
public async Task Invoke(IDictionary <string, object> environment) { if (this._next == null) { throw new ArgumentNullException(nameof(_next)); } IOwinEnvironment context = new DefaultOwinEnvironment(environment); logger.Trace($"Incoming request {context.Request.Path}", "StormpathMiddleware.Invoke"); using (var scopedClient = CreateScopedClient(context)) { var currentUser = await GetUserAsync(context, scopedClient, context.CancellationToken).ConfigureAwait(false); if (currentUser == null) { logger.Trace("Request is anonymous", "StormpathMiddleware.Invoke"); } else { logger.Trace($"Request for Account '{currentUser.Href}' via scheme {environment[OwinKeys.StormpathUserScheme]}", "StormpathMiddleware.Invoke"); } AddStormpathVariablesToEnvironment( environment, Configuration, scopedClient, currentUser); var requestPath = GetRequestPathOrThrow(context); var routeHandler = GetRouteHandler(requestPath); if (routeHandler == null) { await this._next.Invoke(environment); return; } logger.Trace($"Handling request '{requestPath}'", "StormpathMiddleware.Invoke"); if (routeHandler.AuthenticationRequired) { var filter = new AuthenticationRequiredFilter(this.logger); var isAuthenticated = await filter.InvokeAsync(environment); if (!isAuthenticated) { return; } } var handled = await routeHandler.Handler(scopedClient)(context); if (!handled) { logger.Trace("Handler skipped request.", "StormpathMiddleware.Invoke"); await this._next.Invoke(environment); } } }