Reputation: 1255
I've implemented IdentityServer4. The application is running ASP.NET Core. The hosting environment is on IIS. I'm using Shibboleth to perform pre-authentication to the site. This populates a number of server variables in IIS. (We cannot use HTTP Headers in our environment, everything must be done using ServerVariables)
I want to retrieve either server variable 'AUTH_USER' or 'REMOTE_USER'.
In legacy ASP or ASP.NET this was as simple as calling Request.ServerVariable("AUTH_USER"). This has changed in ASP.NET Core.
I've tried ClaimsPricipal -> User.Identity.Name, (User name is empty, IsAuthenticated is false)
I've confirmed the server variables are in fact set.
This question is similar to this question but doesn't answer the question
Upvotes: 6
Views: 14762
Reputation: 1074
I am using .Net 7 and I had to use the request headers to get to the server variables.
HttpContext.Request?.Headers
Upvotes: 0
Reputation: 8588
The .NET (Core) team changed this quite a few times in the last releases. I couldn't neither get HttpContextServerVariableExtensions version nor the legacy variant to via context features to work.
But this gist helped me. Works with .NET 5 on AWS fargate likely with some kind of load balancer pass-through.
public static class HttpContextExtensions
{
//https://gist.github.com/jjxtra/3b240b31a1ed3ad783a7dcdb6df12c36
public static IPAddress GetRemoteIPAddress(this HttpContext context, bool allowForwarded = true)
{
if (allowForwarded)
{
string header = (context.Request.Headers["CF-Connecting-IP"].FirstOrDefault() ?? context.Request.Headers["X-Forwarded-For"].FirstOrDefault());
if (IPAddress.TryParse(header, out IPAddress ip))
{
return ip;
}
}
return context.Connection.RemoteIpAddress;
}
}
I assume you can get any values like this out of the header. HttpContext.Request.Headers["X-Forwarded-For"]
. Note that you cannot locally debug the headers. I didn't see those entries because of my local setup that differs. I saw what magic strings are available e.g. here.
Upvotes: 4
Reputation: 12711
In Asp.Net Core 3, there is an extension method GetServerVariable
on the HttpContext
.
To use it you need to install the Microsoft.AspNetCore.Http.Extensions
NuGet package, and the actual method is in the Microsoft.AspNetCore.Http.HttpContextServerVariableExtensions
class.
Note that the server has to support it, otherwise it will return null
.
For earlier versions of ASP.Net Core you might be able to use the features property of the context property, by calling context.Features.Get<IServerVariablesFeature>()
Upvotes: 9