protected override void RequestStartup(global::Nancy.TinyIoc.TinyIoCContainer container, IPipelines pipelines, NancyContext context) { // At request startup we modify the request pipelines to // include stateless authentication // // Configuring stateless authentication is simple. Just use the // NancyContext to get the apiKey. Then, use the apiKey to get // your user's identity. var configuration = new StatelessAuthenticationConfiguration(c => { //for now, we will pull the apiKey from the querystring, //but you can pull it from any part of the NancyContext var apiKey = (string)c.Request.Query.ApiKey.Value ?? c.Request.Form.ApiKey.Value; if (apiKey == null && c.Request.Cookies.ContainsKey("ApiKey")) { apiKey = c.Request.Cookies["ApiKey"]; } context.Items.Add("ApiKey", apiKey); //get the user identity however you choose to (for now, using a static class/method) return(NSembleUserAuthentication.GetUserFromApiKey(container.Resolve <IDocumentSession>(), apiKey)); }); StatelessAuthentication.Enable(pipelines, configuration); }
protected override void ApplicationStartup(TinyIoCContainer container, IPipelines pipelines) { base.ApplicationStartup(container, pipelines); var cryptographyConfiguration = new CryptographyConfiguration( new RijndaelEncryptionProvider(new PassphraseKeyGenerator("SuperSecretPass", new byte[] { 1, 2, 3, 4, 5, 6, 7, 8 })), new DefaultHmacProvider(new PassphraseKeyGenerator("UberSuperSecure", new byte[] { 1, 2, 3, 4, 5, 6, 7, 8 }))); var formsAuthConfiguration = new FormsAuthenticationConfiguration() { RedirectUrl = "~/login", UserMapper = container.Resolve <IUserMapper>(), CryptographyConfiguration = cryptographyConfiguration }; FormsAuthentication.Enable(pipelines, formsAuthConfiguration); OAuth.Enable(); var configuration = new StatelessAuthenticationConfiguration(nancyContext => { var apiKey = (string)nancyContext.Request.Query["access_token"].Value; return(UserDatabase.GetUserFromToken(apiKey)); }); StatelessAuthentication.Enable(pipelines, configuration); InMemorySessions.Enable(pipelines); }
protected override void ApplicationStartup(TinyIoCContainer container, IPipelines pipelines) { //替换默认序列化方式 container.Register <ISerializer, CustomJsonNetSerializer>(); container.Register <IUserMapper, UserMapper>(); #region 业务注入 container.Register <IUserBaseService, UserBaseService>(); #endregion var configuration = new StatelessAuthenticationConfiguration( nancyContext => { //返回null代码token无效或用户未认证 var token = nancyContext.Request.Headers.Authorization; var userValidator = container.Resolve <IUserMapper>(); return(!string.IsNullOrEmpty(token) ? userValidator.GetUserFromAccessToken(token) : null); } ); StatelessAuthentication.Enable(pipelines, configuration); base.ApplicationStartup(container, pipelines); }
protected override void ApplicationStartup(TinyIoCContainer container, IPipelines pipelines) { base.ApplicationStartup(container, pipelines); StatelessAuthentication.Enable(pipelines, new StatelessAuthenticationConfiguration(ctx => { // Check for the API key string accessToken = null; if (ctx.Request.Query.apikey.HasValue) { accessToken = ctx.Request.Query.apikey; } else if (ctx.Request.Form["apikey"].HasValue) { accessToken = ctx.Request.Form["apikey"]; } else { var authHeader = ctx.Request.Headers.Authorization; if (!string.IsNullOrWhiteSpace(authHeader)) { accessToken = authHeader; } } // Authenticate the request var authService = new ApiClientAuthenticationService(ServerContext); return(accessToken == null ? null : authService.ResolveClientIdentity(accessToken)); })); }
/// <summary> /// This function override the RequestStartup which is used each time a request came to Nancy /// </summary> protected override void RequestStartup(TinyIoCContainer requestContainer, IPipelines pipelines, NancyContext context) { var configuration = new StatelessAuthenticationConfiguration(nancyContext => { //try to take "apikey" from header string apiKey = nancyContext.Request.Headers["apikey"].FirstOrDefault(); if (string.IsNullOrEmpty(apiKey)) { //take out value of "apikey" from query that was pass in request and check for User apiKey = (string)nancyContext.Request.Query.apikey.Value; } if (apiKey != null) { return(UserDatabase.GetUserFromApiKey(apiKey)); } else { return(null); } }); StaticConfiguration.DisableErrorTraces = false; StatelessAuthentication.Enable(pipelines, configuration); }
protected override void RequestStartup(TinyIoCContainer container, IPipelines pipelines, NancyContext context) { StatelessAuthentication.Enable(pipelines, new StatelessAuthenticationConfiguration(ctx => { string sessionKey; if (ctx.Request.Query.SessionKey.HasValue) { sessionKey = (string)ctx.Request.Query.sessionkey; } else if (!ctx.Request.Cookies.TryGetValue("Bastet_Session_Key", out sessionKey)) { return(null); } var connection = container.Resolve <IDbConnection>(); var session = connection.SingleWhere <Session>("SessionKey", sessionKey); if (session == null) { return(null); } var user = connection.SingleById <User>(session.UserId); if (user == null) { return(null); } return(new Identity(Identity.GetClaims(user, connection), user, session)); })); }
protected override void ApplicationStartup(TinyIoCContainer container, IPipelines pipelines) { OMServerContext.ConnectOsmiumMine(); // Enable authentication StatelessAuthentication.Enable(pipelines, new StatelessAuthenticationConfiguration(ctx => { // Take API from query string var apiKey = (string)ctx.Request.Query.apikey.Value; // get user identity var authenticator = new StatelessAuthenticationService <OMAccessKey, OMApiAccessScope>(OMServerContext); return(authenticator.ResolveClientIdentity(apiKey)); })); // Enable CORS pipelines.AfterRequest.AddItemToEndOfPipeline(ctx => { foreach (var origin in OMServerContext.Parameters.CorsOrigins) { ctx.Response.WithHeader("Access-Control-Allow-Origin", origin); } ctx.Response .WithHeader("Access-Control-Allow-Methods", "GET,POST,PUT,DELETE") .WithHeader("Access-Control-Allow-Headers", "Accept, Origin, Content-type"); }); base.ApplicationStartup(container, pipelines); }
protected override void ApplicationStartup(IContainer container, IPipelines pipelines) { base.ApplicationStartup(container, pipelines); var jwtService = container.GetInstance <IJWTService>(); // TODO: Move out to extension method var configuration = new StatelessAuthenticationConfiguration(ctx => { try { var bearerDeclaration = "Bearer "; var authHeader = ctx.Request.Headers.Authorization; var jwt = authHeader.Substring(bearerDeclaration.Length); var token = jwtService.DecodeToken(jwt); if (token != null) { return(new DailyTrackerPrincipal(token.UserId, token.Username)); } } catch (Exception) { return(null); } return(null); }); StatelessAuthentication.Enable(pipelines, configuration); }
protected override void ApplicationStartup(TinyIoCContainer container, IPipelines pipelines) { base.ApplicationStartup(container, pipelines); StatelessAuthentication.Enable(pipelines, new StatelessAuthenticationConfiguration(AuthenticateUser)); Metric.Config .WithReporting(r => r.WithConsoleReport(TimeSpan.FromSeconds(30)) //.WithReporter("Resetting Reporter", () => new SampleResettingReporter(), TimeSpan.FromSeconds(5)) ) .WithNancy(pipelines, config => config.WithMetricsModule(conf => conf .WithEndpointReport("test", (d, h, r) => new MetricsEndpointResponse("test", "text/plain")))); // read remote metrics from NancySample //Metric.Advanced.AttachContext("Remote", // new RemoteMetricsContext( // new Uri("http://localhost:1234/v2/json"), // TimeSpan.FromSeconds(5), // s => JsonConvert.DeserializeObject<JsonMetricsContext>(s))); pipelines.AfterRequest += ctx => { if (ctx.Response != null) { ctx.Response .WithHeader("Access-Control-Allow-Origin", "*") .WithHeader("Access-Control-Allow-Headers", "Origin, X-Requested-With, Content-Type, Accept"); } }; }
protected override void RequestStartup(TinyIoCContainer container, IPipelines pipelines, NancyContext context) { base.RequestStartup(container, pipelines, context); pipelines.BeforeRequest += nancyContext => { var acceptHeaders = new List <Tuple <string, decimal> >(nancyContext.Request.Headers.Accept); acceptHeaders.Insert(0, new Tuple <string, decimal>("application/vnd.siren+json", 1m)); nancyContext.Request.Headers.Accept = acceptHeaders; return(null); }; pipelines.AfterRequest.AddItemToEndOfPipeline(x => { x.Response.Headers.Add("Access-Control-Allow-Headers", "AUTHORIZATION"); x.Response.Headers.Add("Access-Control-Allow-Origin", "*"); x.Response.Headers.Add("Access-Control-Allow-Methods", "POST,GET,DELETE,PUT,OPTIONS"); }); StatelessAuthentication.Enable(pipelines, new StatelessAuthenticationConfiguration(ctx => { var statelessAuthenticator = container.Resolve <IStatelessAuthenticator>(); var accessToken = string.IsNullOrWhiteSpace(ctx.Request.Headers.Authorization) ? ctx.Request.Cookies["accessToken"] : ctx.Request.Headers.Authorization; return(statelessAuthenticator.GetUserIdentityBy(new Guid(accessToken))); })); }
protected override void ApplicationStartup(TinyIoCContainer container, IPipelines pipelines) { base.ApplicationStartup(container, pipelines); // We will send big JSON payloads JsonSettings.MaxJsonLength = int.MaxValue; // Authentication var authconf = new StatelessAuthenticationConfiguration(ctx => { var principal = ctx.GetFromOwinContext <ApplicationSignInManager>().AuthenticationManager.User; return(principal.Identity.IsAuthenticated ? new AuthenticatedUser(principal) : null); }); StatelessAuthentication.Enable(pipelines, authconf); #if !DEBUG // disable diagnostics in release version DiagnosticsHook.Disable(pipelines); container.Register <IDiagnostics, DisabledDiagnostics>(); StaticConfiguration.DisableErrorTraces = true; #endif pipelines.OnError += (ctx, err) => { logger.TraceEvent(TraceEventType.Error, 0, "Global application error occurred when serving request: {0}, ex: {1}", ctx.Request.Url, err); return(null); }; // make sure that we have partitions to store the coming logs var logmaintain = container.Resolve <ILogMaintenance>(); logmaintain.PerformMaintenanceIfNecessaryAsync().Wait(); }
protected override void RequestStartup(TinyIoCContainer container, IPipelines pipelines, NancyContext context) { var securityService = container.Resolve <ISecurityService>(); // TODO: remove this to own class var configuration = new StatelessAuthenticationConfiguration(ctx => { var jwt = ctx.Request.Headers.Authorization; try { var loginToken = securityService.DecodeToken(jwt); if (loginToken != null) { return(new UserIdentity { UserName = loginToken.LoginName, UserId = loginToken.UserId, Claims = loginToken.Claims, Name = loginToken.UserName }); } } catch (Exception) { return(null); } return(null); }); StatelessAuthentication.Enable(pipelines, configuration); pipelines.EnableCORS(); }
protected override void RequestStartup(IWindsorContainer container, IPipelines pipelines, NancyContext context) { SSLProxy.RewriteSchemeUsingForwardedHeaders(pipelines); #if SKIPAUTH var statelessAuthenticationConfiguration = new StatelessAuthenticationConfiguration(ctx => { var userMapper = container.Resolve <IUserMapper>(); return(userMapper.GetUserFromIdentifier(Guid.Empty, null)); }); StatelessAuthentication.Enable(pipelines, statelessAuthenticationConfiguration); #else FormsAuthenticationConfiguration formsAuthConfiguration; try { var userMapper = container.Resolve <IUserMapper>(); formsAuthConfiguration = new FormsAuthenticationConfiguration { UserMapper = userMapper, RedirectUrl = "~/login" }; } catch (Exception e) { this.logger.Error("Error getting user mapper", e); throw; } FormsAuthentication.Enable(pipelines, formsAuthConfiguration); #endif }
protected override void ApplicationStartup(TinyIoCContainer container, IPipelines pipelines) { pipelines.BeforeRequest += ctx => { if (!ctx.Request.Headers.Accept.Any()) { ctx.Request.Headers.Accept = new[] { Tuple.Create("application/json", 1m) } } ; if (string.IsNullOrEmpty(ctx.Request.Headers.ContentType)) { ctx.Request.Headers.ContentType = "application/json"; } return(null); }; var configuration = new StatelessAuthenticationConfiguration(ctx => { var jwtToken = ctx.Request.Headers.Authorization; return(AuthenticationHelper.GetUserFromApiKey(jwtToken)); }); AllowAccessToConsumingSite(pipelines); StatelessAuthentication.Enable(pipelines, configuration); }
protected override void RequestStartup(ILifetimeScope requestContainer, IPipelines pipelines, NancyContext context) { base.RequestStartup(requestContainer, pipelines, context); NancyExceptionHandling.Enable( requestContainer, pipelines, context); var requestThrottleManager = requestContainer.Resolve <IRequestThrottleManager>(); requestThrottleManager.RequiresThrottlingByPathAndIpOnlyUnauthorized( pipelines, ThrottlingPeriod.Minute, requestCountLimit: thresholdSettings.MinuteRequestsLimitByActionByIP); requestThrottleManager.RequiresThrottlingByPathAndIpOnlyUnauthorized( pipelines, ThrottlingPeriod.Hour, requestCountLimit: thresholdSettings.HourlyRequestsLimitByActionByIP); StatelessAuthentication.Enable( pipelines, requestContainer .Resolve <IAuthenticationConfigurationBuilder>() .Build()); NancySecurityCriticalActionsHandling.Enable( requestContainer, pipelines); }
protected override void RequestStartup(IUnityContainer container, IPipelines pipelines, NancyContext context) { var configuration = new StatelessAuthenticationConfiguration(ctx => { var apikey = ctx.Request.Headers.Authorization; if (apikey != null) { var claimPrincipal = _authService.GetUserFromApiKey(apikey); if (claimPrincipal != null) { return(new UserIdentity() { Claims = new List <string>() { claimPrincipal.Identity.Name }, UserName = claimPrincipal.Identity.Name }); } } return(null); }); AllowAccessToConsumingSite(pipelines); StatelessAuthentication.Enable(pipelines, configuration); }
private static void ConfigureStatelessAuth(TinyIoCContainer container, IPipelines pipelines) { var statelessAuthConfigurationFactory = container.Resolve <IStatelessAuthConfigurationFactory>(); var configuration = statelessAuthConfigurationFactory.Create(); StatelessAuthentication.Enable(pipelines, configuration); }
protected override void RequestStartup(TinyIoCContainer requestContainer, IPipelines pipelines, NancyContext context) { var configuration = new StatelessAuthenticationConfiguration(nancyContext => { var c = TinyIoCContainer.Current; var conn = c.Resolve <SqlServerConnection>("sqlConn"); var token = nancyContext.Request.Headers.Authorization; var usuario = conn.GetObject <Usuario>("sp_usuarios_valid", new List <SqlParameter> { new SqlParameter { ParameterName = "@token", Value = token } }); if (usuario.id > 0 || token == "MARTIN") { return(new ClaimsPrincipal(new UserIdentity { IsAuthenticated = true, Name = usuario.email, AuthenticationType = "stateless", Usuario = usuario })); } return(null); }); AllowAccessToConsumingSite(pipelines); StatelessAuthentication.Enable(pipelines, configuration); }
public AuthModule() : base("/auth") { StatelessAuthentication.Enable(this, KaiseiCore.StatelessConfig); //App Post("/sso", _ => { if (Context.CurrentUser == null) { return new Response { StatusCode = HttpStatusCode.Unauthorized } } ; var sso = this.Bind <SSOData>(); var userId = ((UserModel)Context.CurrentUser).Id; return(KaiseiCore.AuthorizeApp(sso.AppId, userId)); }); Post(@"/", _ => { var post = this.Bind <SSOData>(); if (Context.CurrentUser != null) { post.Verified = true; } return(View["Index", post]); }); Post("/verifyPassword", _ => { if (!(Context.CurrentUser is UserModel user)) { return new Response { StatusCode = HttpStatusCode.Unauthorized } } ; var credentials = this.Bind <UserCredentials>(); user = KaiseiCore.VerifyUser(credentials); if (user == null) { return new Response { StatusCode = HttpStatusCode.Unauthorized } } ; else { return new Response { StatusCode = HttpStatusCode.OK } }; });
protected override void ApplicationStartup(TinyIoCContainer container, IPipelines pipelines) { base.ApplicationStartup(container, pipelines); var identityProvider = container.Resolve <IIdentityProvider>(); var statelessAuthConfig = new StatelessAuthenticationConfiguration(identityProvider.GetUserIdentity); StatelessAuthentication.Enable(pipelines, statelessAuthConfig); }
protected override void ApplicationStartup(TinyIoCContainer container, IPipelines pipelines) { base.ApplicationStartup(container, pipelines); var StatelessAuthConfigurationFactory = container.Resolve <IStatelessAuthConfigurationFactory>(); var configuration = StatelessAuthConfigurationFactory.Create(); StatelessAuthentication.Enable(pipelines, configuration); }
protected override void ApplicationStartup(ILifetimeScope container, IPipelines pipelines) { var identityProvider = BootstraperLifetimeScope.Resolve <IIdentityProvider>(); var statelessAuthConfig = new StatelessAuthenticationConfiguration(identityProvider.GetUserIdentity); StatelessAuthentication.Enable(pipelines, statelessAuthConfig); base.ApplicationStartup(container, pipelines); }
public IndexModule() { StatelessAuthentication.Enable(this, ProcrastinatorCore.StatelessConfig); this.RequiresAuthentication(); Get["/"] = _ => { Console.WriteLine(Context?.CurrentUser?.UserName); return(View["index", new { user = Context.CurrentUser, bgid = Rand.Next(7) }]); }; }
protected override void ApplicationStartup(TinyIoCContainer container, IPipelines pipelines) { //log requests pipelines.BeforeRequest += ctx => { _logger.Info($"http server request {ctx.Request.Method} {ctx.Request.Url}"); return(null); }; pipelines.OnError.AddItemToEndOfPipeline((ctx, ex) => { //log errors _logger.Error(ex, "Unhandled exception in http server: " + ex.Message); //special response for model binding exceptions if (ex is ModelBindingException) { var response = new JsonResponse(new ValidationErrorResponse(ex.Message), new JsonNetSerializer()); response.StatusCode = HttpStatusCode.BadRequest; return(response); } //handle situations where an operation would violate a unique constraint in the db - return 409 Conflict var sqlException = ex.GetBaseException() as SqlException; if (sqlException != null && sqlException.IsUniqueKeyException()) { var response = new JsonResponse( new ErrorResponse(HttpStatusCode.Conflict, sqlException.Message, ""), new JsonNetSerializer()); response.StatusCode = HttpStatusCode.Conflict; return(response); } return(ctx.Response); }); var statelessAuthConfiguration = new StatelessAuthenticationConfiguration(ctx => { var authHeader = ctx.Request.Headers["Authorization"]; if (authHeader == null || !authHeader.Any()) { return(null); } if (authHeader.First() == _apiKey) { return(new ApiUser("admin")); } return(null); }); //Enables authentication for all modules StatelessAuthentication.Enable(pipelines, statelessAuthConfiguration); }
/// <summary> /// This function override the RequestStartup which is used each time a request came to Nancy /// </summary> protected override void RequestStartup(TinyIoCContainer requestContainer, IPipelines pipelines, NancyContext context) { StaticConfiguration.EnableRequestTracing = true; var configuration = new StatelessAuthenticationConfiguration(nancyContext => { //try to take "apikey" from header string apiKey = nancyContext.Request.Headers["apikey"].FirstOrDefault(); if (string.IsNullOrEmpty(apiKey)) { //take out value of "apikey" from query that was pass in request and check for User apiKey = (string)nancyContext.Request.Query.apikey.Value; } if (apiKey != null) { return(UserDatabase.GetUserFromApiKey(apiKey)); } else { return(null); } }); StaticConfiguration.DisableErrorTraces = false; StatelessAuthentication.Enable(pipelines, configuration); pipelines.OnError += (ctx, ex) => onError(ctx, ex); pipelines.BeforeRequest += BeforeProcessing; pipelines.AfterRequest += AfterProcessing; #region CORS Enable pipelines.AfterRequest.AddItemToEndOfPipeline((ctx) => { ctx.Response.WithHeader("Access-Control-Allow-Origin", "*") .WithHeader("Access-Control-Allow-Methods", "POST,GET,OPTIONS") .WithHeader("Access-Control-Allow-Headers", "Accept, Origin, Content-type, apikey"); }); #endregion #region Gzip compression GzipCompressionSettings gzipsettings = new GzipCompressionSettings { MinimumBytes = 16384 //16k }; gzipsettings.MimeTypes.Add("application/xml"); gzipsettings.MimeTypes.Add("application/json"); pipelines.EnableGzipCompression(gzipsettings); #endregion }
protected override void RequestStartup(TinyIoCContainer container, IPipelines pipelines, NancyContext context) { var configuration = new StatelessAuthenticationConfiguration(ctx => { var jwtToken = ctx.Request.Headers.Authorization; if (string.IsNullOrEmpty(jwtToken)) { jwtToken = ctx.Request.Query.Authorization; } if (string.IsNullOrEmpty(jwtToken)) { jwtToken = ctx.Request.Form.Authorization; } try { var ssa = container.Resolve <SuperSimpleAuth>(); var user = ssa.Validate(jwtToken); //claims if using later versions of nancy //var claims = new List<Claim>(); //foreach(var role in user.Roles) //{ // foreach(var permission in role.Permissions) // { // claims.Add(new Claim(role.Name, permission)); // } //} //var identity = new ClaimsIdentity( // new GenericIdentity(user.UserName), // claims, // "Jwt", // "SSA", // "SSA"); var identity = new NancyUserIdentity(user); //return new ClaimsPrincipal(identity); return(identity); } catch (Exception exc) { return(null); } }); StatelessAuthentication.Enable(pipelines, configuration); }
protected override void ApplicationStartup(TinyIoCContainer container, IPipelines pipelines) { base.ApplicationStartup(container, pipelines); //configure the NLog stuff LoggingConfiguration logConfig = new LoggingConfiguration(); FileTarget fileTarget = new FileTarget(); fileTarget.FileName = "${basedir}/logFile.txt"; logConfig.AddTarget("file", fileTarget); fileTarget.Layout = @"${date:format=MM-dd-yyyy_HH\:mm\:ss} | ${message}"; var rule1 = new LoggingRule("*", LogLevel.Info, fileTarget); logConfig.LoggingRules.Add(rule1); LogManager.Configuration = logConfig; //create configuration with validation for JWT tokens for federated authentication StatelessAuthenticationConfiguration configuration = new StatelessAuthenticationConfiguration(ctx => { if (string.IsNullOrEmpty(ctx.Request.Headers.Authorization)) { //Auth header doesn't exist or is null, so assume no user return(null); } try { //validate the token is legit var validator = new JwtValidator(_config); bool result = validator.Validate(ctx.Request.Headers.Authorization); //if token was validated successfully, return User object if (result) { //return new User, passing the token in to populate the various claims return(new User(validator.DecodeToken(ctx.Request.Headers.Authorization))); } //if we somehow get here, return null return(null); } catch (Exception ex) { //something happened during the validation, so return null //return null; throw ex; } }); StatelessAuthentication.Enable(pipelines, configuration); }
/// <remarks> /// Offloading ssl onto nginx and forwarding. The below modification to the behavior of the /// application bootstrapper enables Nancy to listen for the XForwardedProto header. See /// http://stackoverflow.com/questions/29634033/nancyfx-ssl-how-to-make-this-requirehttps-work-on-linux /// </reamarks> protected override void RequestStartup(TinyIoCContainer requestContainer, IPipelines pipelines, NancyContext context) { var authConfiguration = new StatelessAuthenticationConfiguration(nancyContext => { var sessionToken = (string)nancyContext.Request.Query.session_token?.Value; return(SessionTokenManager.GetUserClaimsFromSessionToken(sessionToken).Result); }); AllowAccessToConsumingSite(pipelines); SSLProxy.RewriteSchemeUsingForwardedHeaders(pipelines); StatelessAuthentication.Enable(pipelines, authConfiguration); }
/// <summary> /// Constructs secure module that allows users of type userType to access /// </summary> /// <param name="uri">Base path</param> /// <param name="userType">Type of user to allow access</param> protected SecureModule(string uri, Type userType) : base(uri) { StatelessAuthentication.Enable(this, new StatelessAuthenticationConfiguration(GetUserIdentity)); this.userType = userType; Before += ctx => { var user = ctx.CurrentUser; return(user != null ? null : Response.AsText("Unauthorized").WithStatusCode(HttpStatusCode.Unauthorized)); }; }
public static void SetupTokenAuthentication(this IPipelines pipelines, ILifetimeScope container) { var jwtTokenHandler = container.Resolve <IJwtTokenHandler>(); var statelessAuthConfiguration = new StatelessAuthenticationConfiguration(ctx => { var token = jwtTokenHandler.GetFromAuthorizationHeader(ctx.Request.Headers.Authorization); var isValid = jwtTokenHandler.IsValid(token); return(isValid ? new WardenIdentity(token.Sub) : null); }); StatelessAuthentication.Enable(pipelines, statelessAuthConfiguration); }