protected override void RequestStartup(TinyIoCContainer requestContainer, 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(nancyContext => { //for now, we will pull the apiKey from the querystring, //but you can pull it from any part of the NancyContext var apiKey = (string)nancyContext.Request.Query.ApiKey.Value; //get the user identity however you choose to (for now, using a static class/method) return(UserDatabase.GetUserFromApiKey(apiKey)); }); AllowAccessToConsumingSite(pipelines); StatelessAuthentication.Enable(pipelines, configuration); }
protected override void RequestStartup(TinyIoCContainer requestContainer, 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(nancyContext => { // For now, we will get the apiKey from a cookie. // If there's no cookie, check the query string. try { string apiKey = ""; if (!nancyContext.Request.Cookies.TryGetValue("BCR_apiKey", out apiKey)) { apiKey = (string)nancyContext.Request.Query.ApiKey.Value; } return(BCR.UserDatabase.GetUserFromApiKey(apiKey)); } catch (Exception e) { System.Windows.Forms.MessageBox.Show("Error while initializing the user data:\n" + e.ToString(), "BCR Error"); Console.WriteLine(e.ToString()); } return(null); }); AllowAccessToConsumingSite(pipelines); StatelessAuthentication.Enable(pipelines, configuration); }
/// <summary> /// 每一次Request将执行此函数,在此函数中校验用户的身份 /// </summary> /// <param name="container"></param> /// <param name="pipelines"></param> /// <param name="context"></param> protected override void RequestStartup(TinyIoCContainer container, IPipelines pipelines, NancyContext context) { pipelines.AfterRequest += AfterRequest; var configuration = new StatelessAuthenticationConfiguration(nancyContext => { var authorization = nancyContext.Request.Headers.Authorization; if (string.IsNullOrEmpty(authorization)) { return(null); } else { var result = CheckHeaders(context, authorization); if (result) { return(new UserIdentify { UserName = authorization.Split(':')[1], Claims = new[] { authorization.Split(':')[1] } }); } else { return(null); } } }); StatelessAuthentication.Enable(pipelines, configuration); }
protected override void RequestStartup(TinyIoCContainer container, IPipelines pipelines, NancyContext context) { // Identify request holder through API key var configuration = new StatelessAuthenticationConfiguration(ctx => { Guid apiKey; // If API key found, retrieve user information associated with the // API key. If user found, add user information to request if (Guid.TryParse(ctx.Request.Headers.Authorization, out apiKey)) { var query = container.Resolve <IUserHelper>(); ClaimsPrincipal user = query.GetBy(apiKey); if (user.Identity.Name == string.Empty) { return(null); } // Add user information ctx.Items.Add(new KeyValuePair <string, object>("user", user.Identity)); container.Resolve <IHttpContextAccessor>().HttpContext.User = user; return(user); } return(null); }); // Add a default error handler to pipeline ErrorPipeline er = new ErrorPipeline(); er.AddItemToEndOfPipeline((ctx, ex) => LogAndGetErrorResponse(ex, ctx)); pipelines.OnError = er; StatelessAuthentication.Enable(pipelines, configuration); }
protected override void ApplicationStartup(TinyIoCContainer container, IPipelines pipelines) { base.ApplicationStartup(container, pipelines); StaticConfiguration.EnableRequestTracing = true; var authConfig = new StatelessAuthenticationConfiguration(ctx => { if (!ctx.Request.Query.auth.HasValue) { return(null); } return(new User()); }); StatelessAuthentication.Enable(pipelines, authConfig); var connectionFactory = container.Resolve <IConnectionManager>(); using (var conn = connectionFactory.GetConnection()) { conn.Execute("CREATE TABLE IF NOT EXISTS HitLog (Id INTEGER PRIMARY KEY, IpAddress STRING)"); } }
/// <summary> /// For our use case this method exists for the purpose of enabling Nancy's Stateless authentication (http://goo.gl/Dtxhve) /// </summary> protected override void RequestStartup(TinyIoCContainer requestContainer, 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 authorization code to get // your user's identity from Azure Active Directory via ADAL. // // If the authorization code required to do this is missing, NancyModules // secured via RequiresAuthentication() cannot be invoked... var configuration = new StatelessAuthenticationConfiguration(nancyContext => { // the only way a user will be authenticated is if a request contains an authentication code // attached to it... if (!nancyContext.Request.Query.code.HasValue) { return(null); // by returning null we essentially do not authenticate the incoming request } try { //for now, we will pull the apiKey from the querystring, //but you can pull it from any part of the NancyContext var authorizationCode = (string)nancyContext.Request.Query.code; return(AADHelper.GetAuthenticatedUserIDentity(authorizationCode)); //inject a user's identity (retrieved from AAD) into Nancy via StatelessAuthenticationConfiguration } catch (Exception) { return(null); } }); StatelessAuthentication.Enable(pipelines, configuration); }
private static void ConfigStatelessAuthentication(IPipelines pipelines) { var config = new StatelessAuthenticationConfiguration(ctx => AuthenticateUser(ReadAuthToken(ctx))); StatelessAuthentication.Enable(pipelines, config); }
/// <inheritdoc /> /// <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 => { if (!(ServerState.Instance?.ServerOnline ?? false)) { return(null); } //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 try { apiKey = (string)nancyContext.Request.Query.apikey.Value; } catch { // ignore } } AuthTokens auth = RepoFactory.AuthTokens.GetByToken(apiKey); return(auth != null ? RepoFactory.JMMUser.GetByID(auth.UserID) : 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 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); } var mysqlException = ex.GetBaseException() as MySqlException; if (mysqlException != null && mysqlException.IsUniqueKeyException()) { var response = new JsonResponse( new ErrorResponse(HttpStatusCode.Conflict, mysqlException.Message, ""), new JsonNetSerializer()); response.StatusCode = HttpStatusCode.Conflict; return(response); } //generic handler var genericResponse = new JsonResponse( new ErrorResponse(HttpStatusCode.InternalServerError, ex.Message, ""), new JsonNetSerializer()); genericResponse.StatusCode = HttpStatusCode.InternalServerError; return(genericResponse); }); 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> /// Standard Constructor with injected parameters. /// </summary> public ComposedAPI(RouteManager routeManager, IIdentityProvider identityProvider) { // Setup the JWT authentication for routes that require it. var configuration = new StatelessAuthenticationConfiguration(ctx => { // Try..Catch as I am calling user code here try { string jwtToken = ctx.Request.Headers.Authorization; if (string.IsNullOrEmpty(jwtToken)) { return(null); } var loginResult = identityProvider.TokenLogin(jwtToken); if (loginResult.IsAuthenticated) { return(InternalUserIdentity.Wrap(loginResult.User)); } ctx.Response = new Response { StatusCode = HttpStatusCode.Unauthorized, ReasonPhrase = loginResult.ErrorResponse }; return(null); } catch (Exception) { return(null); } }); StatelessAuthentication.Enable(this, configuration); foreach (var route in routeManager.GetRoutes()) { switch (route.Method) { case HttpMethod.Get: Get[route.Path] = ComposeFunction(route); break; case HttpMethod.Post: Post[route.Path] = ComposeFunction(route); break; case HttpMethod.Put: Put[route.Path] = ComposeFunction(route); break; case HttpMethod.Delete: Delete[route.Path] = ComposeFunction(route); break; case HttpMethod.Head: Head[route.Path] = ComposeFunction(route); break; } Options[route.Path] = BuildRouteOptions(route); } /* * TODO: Testing routes for error pages * Get["/"] = _ => * { * return "Hello"; * }; * Get["/ex"] = _ => * { * throw new NullReferenceException("Error is null"); * };*/ /* * // TODO: This should be hooked in the analysis * this.Before += (NancyContext ctx) => * { * Nancy.Routing.Route r = (Nancy.Routing.Route)ctx.ResolvedRoute; * Console.WriteLine(r.Action); * Console.WriteLine("This is before API"); * return null; * }; * * this.Before += (NancyContext ctx) => * { * Console.WriteLine("This is after API"); * return null; * }; */ }
protected override void ApplicationStartup(Nancy.TinyIoc.TinyIoCContainer container, Nancy.Bootstrapper.IPipelines pipelines) { base.ApplicationStartup(container, pipelines); #if !DEBUG pipelines.BeforeRequest.AddItemToEndOfPipeline(SecurityHooks.RequiresHttps(true)); #endif var statelessAuthenticationConfiguration = new StatelessAuthenticationConfiguration(context => { string token = context.Request.Headers["X-AUTH-TOKEN"].FirstOrDefault(); if (token == null && context.Request.Query.token.HasValue) { token = context.Request.Query.token.Value; } if (token == null && context.Request.Cookies.ContainsKey("TOKEN")) { token = context.Request.Cookies["TOKEN"]; } #if DEBUG var ip = System.Net.IPAddress.Parse(context.Request.UserHostAddress); if (token == null && System.Net.IPAddress.IsLoopback(ip)) { return(new User { UserName = "******", Claims = new string[] { "Garage", "Tag", "HVAC", "GroupMe", "Torrent", "ChoreBotNag" } }); } #endif if (!String.IsNullOrWhiteSpace(token)) { using (var sql = new SqlConnection(CloudConfigurationManager.GetSetting("DatabaseConnection"))) { sql.Open(); var check = sql.CreateCommand(); check.CommandText = "SELECT [User].UserName, Claim.Name FROM Token JOIN [User] on [User].Id = Token.UserId LEFT JOIN Claim on Claim.UserId = [User].Id WHERE Token.Value = @token"; check.Parameters.AddWithValue("token", token); var user = new User(); using (var reader = check.ExecuteReader()) { while (reader.Read()) { user.UserName = reader.GetString(0); // Don't add a NULL claim if user doesn't have any claims if (!reader.IsDBNull(1)) { ((List <String>)user.Claims).Add(reader.GetString(1)); } } } if (user.UserName != null) { return(user); } } } return(null); }); StatelessAuthentication.Enable(pipelines, statelessAuthenticationConfiguration); }
public static void Config(IPipelines pipelines) { var configuration = new StatelessAuthenticationConfiguration(ValidarToken); StatelessAuthentication.Enable(pipelines, configuration); }