public async Task Invoke(IDictionary<string, object> environment) { context = new OwinContext(environment); try { if (context.IsLogoutRequest()) { await context.Singout(options); } else if (context.IsLoginRequest(options)) { await next.Invoke(environment); } else if (context.IsTokenRequest()) { var flow = await FlowFactory.GetTokenEndProint ( context, options, AuthCodeStorage, RefreshTokenStorage ); await flow.TokenRequest(); } else { var flow = await FlowFactory.Get ( context, options, AuthCodeStorage, RefreshTokenStorage ); await flow.AuthenticatesEndUser(); } } catch (AuthenticationRequestException ex) { context.BadRequest(ex); } catch (UnauthorizedException ex) { context.Unauthorized(options, ex); } catch (Exception ex) { var aex = new AuthenticationRequestException("internal_error", ex.Message); context.BadRequest(aex); } }