Пример #1
0
        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();
        }
Пример #2
0
        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();
        }
Пример #3
0
        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);
        }
Пример #4
0
        private static void ConfigureStatelessAuth(TinyIoCContainer container, IPipelines pipelines)
        {
            var statelessAuthConfigurationFactory = container.Resolve <IStatelessAuthConfigurationFactory>();
            var configuration = statelessAuthConfigurationFactory.Create();

            StatelessAuthentication.Enable(pipelines, configuration);
        }
Пример #5
0
        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);
        }
Пример #6
0
        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);
        }
Пример #7
0
        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);
        }
Пример #8
0
        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 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));
            }));
        }
Пример #10
0
        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
        }
Пример #11
0
        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);
        }
Пример #12
0
        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
                    }
                };
            });
Пример #13
0
        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);
        }
Пример #14
0
        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);
        }
Пример #15
0
        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);
        }
Пример #16
0
 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) }]);
     };
 }
Пример #17
0
        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);
        }
Пример #18
0
        /// <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
        }
Пример #19
0
        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);
        }
Пример #20
0
        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);
        }
Пример #21
0
 /// <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));
     };
 }
Пример #22
0
        /// <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);
        }
Пример #23
0
        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);
        }
Пример #24
0
 public IndexModule() : base("/")
 {
     StatelessAuthentication.Enable(this, AobaCore.StatelessConfig);
     //this.RequiresAuthentication();
     Get("/", p =>
     {
         var curUser = ((UserModel)Context.CurrentUser)?.Username;
         if (curUser == null)
         {
             return(View["login.html"]);
         }
         Console.WriteLine($"User: {curUser}");
         return(View["index"]);
     });
 }
Пример #25
0
        protected override void RequestStartup(TinyIoCContainer requestContainer, IPipelines pipelines, NancyContext context)
        {
            var configuration =
                new StatelessAuthenticationConfiguration(nancyContext =>
            {
                var apiKey = (string)nancyContext.Request.Headers.Authorization;


                return(UserDatabase.ValidateToken(apiKey));
            });

            AllowAccessToConsumingSite(pipelines);

            StatelessAuthentication.Enable(pipelines, configuration);
        }
Пример #26
0
 public UserModule() : base("/user")
 {
     StatelessAuthentication.Enable(this, KaiseiCore.StatelessConfig);
     Get("/", _ =>
     {
         if (!(Context.CurrentUser is UserModel user))
         {
             return new Response
             {
                 StatusCode = HttpStatusCode.Unauthorized
             }
         }
         ;
         return(Response.AsJson(user));
     });
Пример #27
0
 public IndexModule()
 {
     StatelessAuthentication.Enable(this, KaiseiCore.StatelessConfig);
     Get("/", _ =>
     {
         if (Context.CurrentUser != null)
         {
             return(Response.AsRedirect("/account"));
         }
         else
         {
             return(View["index", new { Callback = "/account", AppId = (string)null }]);
         }
     });
 }
Пример #28
0
        protected override void RequestStartup(TinyIoCContainer container, IPipelines pipelines, NancyContext context)
        {
            var configuration =
                new StatelessAuthenticationConfiguration(
                    ctx =>
            {
                var apiKey = ctx.Request.Headers.Authorization;

                return(KeyDatabase.GetClaimFromApiKey(apiKey));
            });

            AllowAccessToConsumingSite(pipelines);

            StatelessAuthentication.Enable(pipelines, configuration);
        }
Пример #29
0
        public PetStoreModule(IPetStoreService petStoreService) : base(petStoreService)
        {
            var configuration =
                new StatelessAuthenticationConfiguration(context =>
            {
                var token = context.Request.Headers.Authorization;

                if (string.IsNullOrEmpty(token))
                {
                    return(null);
                }
                return(new ClaimsPrincipal(new ClaimsIdentity(new Claim[] { new Claim("user", "admin") }, "token")));
            });

            StatelessAuthentication.Enable(this, configuration);
        }
Пример #30
0
        protected override void ApplicationStartup(TinyIoCContainer container, IPipelines pipelines)
        {
            var configuration =
                new StatelessAuthenticationConfiguration(nancyContext =>
            {
                var jwtToken = nancyContext.Request.Headers.Authorization;


                try
                {
                    var requestToken = jwtToken.Substring("Bearer: ".Length).Trim();
                    var payload      = JWT.Payload <JwtToken>(requestToken);
                    var epoch        = new DateTime(1970, 1, 1, 0, 0, 0, DateTimeKind.Utc);
                    var tokenExpires = epoch.AddSeconds(payload.exp);


                    if (tokenExpires < DateTime.Now)
                    {
                        return(null);
                    }

                    var principal = new ClaimsPrincipal(new HttpListenerBasicIdentity(payload.sub, null));
                    IEnumerable <Claim> identityClaims = new List <Claim>();
                    if (payload.permissions != null)
                    {
                        identityClaims = payload.permissions.Select(claim => new Claim("permissions", claim));
                    }
                    var identities = new ClaimsIdentity(identityClaims);
                    principal.AddIdentity(identities);

                    return(principal);
                }
                catch (Exception)
                {
                    return(null);
                }
            });

            StatelessAuthentication.Enable(pipelines, configuration);
            base.ApplicationStartup(container, pipelines);
            pipelines.AfterRequest += ctx =>
            {
                ctx.Response.Headers.Add("Access-Control-Allow-Origin", "*");
                ctx.Response.Headers.Add("Access-Control-Allow-Headers", "Origin, X-Requested-With, Content-Type, Accept, Authorization");
                ctx.Response.Headers.Add("Access-Control-Allow-Methods", "DELETE, POST");
            };
        }