Skip to content

Repository files navigation

Soenneker.Extensions.HttpContext

Small ASP.NET Core helpers for local-request checks, Basic authentication challenges, and proxy-aware client IP lookup.

Installation

dotnet add package Soenneker.Extensions.HttpContext

Identify local requests

using Soenneker.Extensions.HttpContext;

if (httpContext.IsLocalRequest())
{
    // Apply behavior intended only for requests from this host.
}

IsLocalRequest() returns true when the remote address is loopback, matches the local connection address, or both addresses are absent. It returns false when only the remote address is absent. It examines the connection addresses after any middleware that may have rewritten them.

Return a Basic authentication challenge

httpContext.SetUnauthorized();
return;

SetUnauthorized() sets status code 401 and adds WWW-Authenticate: Basic unless a challenge header already exists. It does not write a response body or end request processing, so return from the endpoint or middleware after calling it.

Read the client IP

string? clientIp = httpContext.GetRequestIp();

The lookup order is:

  1. A valid IP address in CF-Connecting-IP.
  2. The first address in X-Forwarded-For, when it is a valid IP address.
  3. HttpContext.Connection.RemoteIpAddress.

Forwarding headers are supplied by the caller and can be spoofed unless your edge proxy removes incoming copies and writes trusted values. Only use the returned forwarded address for authorization, rate limiting, or auditing when that trust boundary is enforced. In standard ASP.NET Core deployments, prefer configuring Forwarded Headers Middleware and then reading RemoteIpAddress directly when possible.

Malformed or blank forwarding values are ignored. If no usable address is available, GetRequestIp() returns null.

About

A collection of helpful HttpContext extension methods

Topics

Resources

Code of conduct

Contributing

Security policy

Stars

0 stars

Watchers

1 watching

Forks

Releases

Sponsor this project

Packages

Used by

Contributors

Languages