ASP.NET Controller User property not working correctly - asp.net-core

I am trying to do something seemingly very simple. All I want to do is get the current Identity User's email address for my Blazor view. I have a UserEmailController in my Server project, with a GetCurrent() method that returns a Task<string>.
public class UserEmailsController : Controller
{
private readonly UserManager<ApplicationUser> _userManager;
public UserEmailsController(UserManager<ApplicationUser> userManager)
{
_userManager = userManager;
}
[HttpGet]
[Route("api/currentUser")]
public async Task<string> GetCurrent()
{
var user = await _userManager.GetUserAsync(User);
return await _userManager.GetEmailAsync(user);
}
}
From the spelunking I've done, it seems that the User property on the Controller base class should have the information loaded into it when a user is logged in, and I should be able to do something like await _userManager.GetUserAsync(User). However, when I break on this line, the Name property of User is null, along with many of the other values. But IsAuthenticated is true. Huh?
So, the result of the _userManager.GetUserAsync(User) call is null.
I've seen a few posts about this, and there are two common themes.
#1 - people try to use the User property in the constructor of a controller and it doesn't work. The suggested solution is to use it in an Action instead, which is of course what I'm doing.
#2 - another common suggestion is to use HttpContext.User, or to inject an IHttpContextAccessor (added via services.AddSingleton... or services.AddHttpContextAccessor()). I've tried all of these approaches and I get the same result.

I found a solution here. Specifically using HttpContext.User.FindFirst(ClaimTypes.NameIdentifier) and then passing that into _userManager.FindByIdAsync(nameId). Hell of a roundabout way of doing it, but it works.

Related

IHttpContextAccessor scope

I have IHttpContextAccessor injected in a controller. I am reading user name from IHttpContextAccessor and returning it back to the UI.
My question is is very basic. I need to understand how this will work when multiple users will connect and request User Name.
I just want to make sure that the user names will be returned only for the corresponding user.
I don't want to save the user name in session variable after returned to the client. Whenever is needed, I will request a call and get it from the context.
Is this approach valid?
private IHttpContextAccessor ctx
public EmployeeController(IHttpContextAccessor context)
{
ctx=context;
}
public string GetEmployeeName()
{
return ctx.HttpContext.User.UserName;
}
The HttpContextAccessor will be registered as the Singleton service when you
called AddHttpContextAccessor.
According to the source codes, you could find the HttpContextAccessor will check the _httpContextCurrent value when it call get and set method. It will auto set the _httpContextCurrent.Value when the new request come to the application.

AsyncLocal<T> doesn't reach controllers

I don't quite fully understand this situation, where AsyncLocal instance is set at a certain point in the AuthenticationHandler, but does not reach the controller, when it is injected into the constructor.
I've made it similar to how IHttpContextAccessor works, but still nowhere near. However, if I set the AsyncLocal from a Middleware, it reaches the controller. Also, setting the HttpContext.Items property from AuthenticationHandler works just fine.
Question: How is HttpContext able to retain Items property contents all the way, and is ASP.NET runtime disposing the captured ExecutionContext of my DomainContextAccessor for some security reason because of where it is being set at?
I've made a sample app to demo this use case. I'd really appreciate someone shedding the light on this problem.
You already have a good answer on "how should I fix this?" Here's more of a description of why it's behaving this way.
AsyncLocal<T> has the same semantics as logging scopes. Because it has those same semantics, I always prefer to use it with an IDisposable, so that the scope is clear and explicit, and there's no weird rules around whether a method is marked async or not.
For specifics on the weird rules, see this. In summary:
Writing a new value to an AsyncLocal<T> sets that value in the current scope.
Methods marked async will copy their scope to a new scope the first time it's written to (and it's the new scope that is modified).
I've made it similar to how IHttpContextAccessor works, but still nowhere near.
I don't recommend copying the design of IHttpContextAccessor. It works... for that very specific use case. If you want to use AsyncLocal<T>, then use a design like this:
static class MyImplicitValue
{
private static readonly AsyncLocal<T> Value = new();
public static T Get() => Value.Value;
public static IDisposable Set(T newValue)
{
var oldValue = Value.Value;
Value.Value = newValue;
return new Disposable(() => Value.Value = oldValue);
}
}
usage:
using (MyImplicitValue.Set(myValue))
{
// Code in here can get myValue from MyImplicitValue.Get().
}
You can wrap that into an IMyImplicitValueAccessor if desired, but note that any "setter" logic should be using the IDisposable pattern as shown.
AsyncLocal instance is set at a certain point in the AuthenticationHandler, but does not reach the controller
That's because your AuthenticationHandler sets the value but doesn't call the controller after setting that value (and it shouldn't).
However, if I set the AsyncLocal from a Middleware, it reaches the controller.
That's because middleware is calls the next middleware (eventually getting to the controller). I.e., middleware is structured like this:
public async Task InvokeAsync(HttpContext context)
{
using (implicitValue.Set(myValue))
{
await _next(context);
}
}
So the controllers are in the scope of when that AsyncLocal<T> value was set.
How is HttpContext able to retain Items property contents all the way
Items is just a property bag. It doesn't have anything to do with AsyncLocal<T>. It exists because it's a property on HttpContext, and it persists because the same HttpContext instance is used throughout the request.
is ASP.NET runtime disposing the captured ExecutionContext of my DomainContextAccessor for some security reason because of where it is being set at?
Not exactly. The AsyncLocal<T> is being set just fine; it's just that the controllers are not called within the scope of that AsyncLocal<T> being set.
So what must be happening is there is a execution context change which wipes that value out. It works with in the middleware because your controller is in the same execution context as your middleware.
Change your code to this:
private static void DomainContextChangeHandler(AsyncLocalValueChangedArgs<DomainContextHolder> args)
{
Trace.WriteLine($"ThreadContextChanged: {args.ThreadContextChanged}");
Trace.WriteLine($"Current: {args.CurrentValue?.GetHashCode()}");
Trace.WriteLine($"Previous: {args.PreviousValue?.GetHashCode()}");
Trace.WriteLine($"Thread Id: {Thread.CurrentThread.ManagedThreadId}");
}
Now you can see when the context changes.
Here is something you could do:
private static void DomainContextChangeHandler(AsyncLocalValueChangedArgs<DomainContextHolder> args)
{
if (args.ThreadContextChanged && (args.PreviousValue != null) && (args.CurrentValue == null))
{
Trace.WriteLine(
"***** Detected context change with a previous value but setting current " +
"value to null. Resetting value to previous.");
_domainContextCurrent.Value = args.PreviousValue;
return;
}
Trace.WriteLine($"ThreadContextChanged: {args.ThreadContextChanged}");
Trace.WriteLine($"Current: {args.CurrentValue?.GetHashCode()}");
Trace.WriteLine($"Previous: {args.PreviousValue?.GetHashCode()}");
Trace.WriteLine($"Thread Id: {Thread.CurrentThread.ManagedThreadId}");
}
But, that kinda defeats the purpose of using AsyncLocal as your backing store.
My suggestion is you drop the AsyncLocal and use normal class-scoped storage:
namespace WebApp.Models
{
public interface IDomainContextAccessor
{
DomainContext DomainContext { get; set; }
}
public sealed class DomainContextAccessor : IDomainContextAccessor
{
public DomainContext DomainContext { get; set; }
}
}
And inject it as scoped instead of singleton:
services.AddScoped<IDomainContextAccessor, DomainContextAccessor>();
It will do exactly what you want without any kludges -- AND, the future you (or devs) will absolutely understand what's going on and why it is the way it is.
No middleware, no AsyncLocal funny-business. It just works.
Your answer is here:
.net core AsyncLocal loses its value
In your DomainContextAccessor class when you set new value in this line: _domainContextCurrent.Value = new DomainContextHolder { Context = value };
you create NEW ExecutionContext in current thread and child threads.
So I suppose that mvc runs like this:
Middleware thread => you set value => some child thread with Controller execution which sees parent changes
But for UserAuthenticationHandler it feels it works like this:
Some controller factory creates controller with injected IDomainContextAccessor (1 context) => mvc executes auth handler in child task where you set value and create 2 context. But it's value does not go UP to parent (where controller 1 context exists) because you create new context when you set value. Even more your code gets parents context, gets reference to its value and makes property Context = null, so you will get null in Controller.
So to fix this you need to change your code:
public class DomainContext
{
private static AsyncLocal<DomainContext> _contextHolder = new AsyncLocal<DomainContext>();
public static DomainContext Current
{
get
{
return _contextHolder.Value;
}
}
public Job JobInfo { get; set; }
public static void InitContext()
{
_contextHolder.Value = new DomainContext();
}
}
//using in middleware:
DomainContext.InitContext();
//using in auth handler:
DomainContext.Current.JobInfo = ...
In example above you don't change DomainContext reference in _contextHolder.Value;
It remains the same but you only change value of JobInfo in it later in auth handler

How to access Request.Properties outside of Web API Controller

I'm setting a Property on Request.Properties inside a DelegatingHandler after I pluck some data out of a header on an incoming request to a Web API.
This all works fine. I can also access Request.Properties from within the controller as well as in my Action and Exception filters. However, I also need to access this data from outside of the controller (I call a business layer class from the controller). It is data I want to include in some logs in other places,
I can see HttpContext.Current from this class, and I can see the original header from here, so I guess I could pluck it out again, but since I have already done this and put it in the Properties it seems to make more sense to get it from there. However, I don't seem to have access to the Request.Properties from anywhere else.
If this isn't the right way to do this, how else would I pass around this per-request data so that it was accessible from anywhere on the stack in Web API?
I also need to access [Request.Properties] data from outside of the controller (I call a business layer class from the controller). It is data I want to include in some logs in other places... However, I don't seem to have access to the Request.Properties from anywhere else. If this isn't the right way to do this, how else would I pass around this per-request data so that it was accessible from anywhere on the stack in Web API?
You can get it from HttpContext.Current, though it is less than ideal. Keep in mind that if any other non-web applications consume the same business layer, then HttpContext.Current would be null. HttpContext.Current is only non-null when you are running in IIS, and an IIS thread is handling the execution of the request stack. If you ever plan to self-host the web api using OWIN without IIS, there will be no HttpContext.Current.
Personally, if the data really is important enough to be passed into the business layer to be logged, then I would just pass it to the business layer method:
public Task<HttpResponseMessage> SomeAction(SomeModel model) {
... other code
someBusinessLayerObject.SomeMethod(arg1, arg2, Request.Properties["myHeaderKey"]);
}
...If you need other values from Request.Properties, then you can just pass the whole dictionary to the methods that will end up using its values.
A third option if you are using an inversion of control container would be to add some kind of scoped object dependency class and put the data in there. Then constructor inject it into your business layer class:
public interface IHaveRequestData {
IDictionary<string, object> Properties { get; set; }
}
public class RequestData : IHaveRequestData {
public IDictionary<string, object> Properties { get; set; }
}
// ioc registration pseudocode
iocContainer.Register<IHaveRequestData, RequestData>(Lifetime
.WhateverYouNeedSoThatOneOfTheseGetsCreatedForEachWebRequest);
public class SomeController : ApiController {
private readonly IHaveRequestData RequestData;
public SomeController(IHaveRequestData requestData) {
RequestData = requestData;
}
public Task<HttpResponseMessage> SomeAction() {
// you may even be able to do this part in an action filter
RequestData.Properties = Request.Properties;
}
}
public class SomeBusinessLayerComponent {
private readonly IHaveRequestData RequestData;
private readonly ILog Log;
public SomeBusinessLayerComponent(IHaveRequestData requestData, ILog log) {
RequestData = requestData;
Log = log;
}
public Task SomeMethod() {
Log.Info(RequestData["myHeader"]);
}
}

How can I kick the user if I change IsConfirmed column?

I use ASP.NET SimpleMembership..
My scenario;
The user login and then I change IsConfirmed column to false on webpages_Membership table..
And the user try to change page, the login page seems to the user..
Your most sensible options are to use any of the authentication related steps in Global.asax.cs, or to derive from AuthorizeAttribute. Given that non-confirmed users are going to have to get to somewhere (for example in order to confirm their account) then you probably don't want the former. With either approach their next request will get denied.
Therefore, I would just extend your [Authorize] attribute to do something like the following, and just use that in the appropriate Controllers and Actions instead of [Authorize] (I'm assuming C# as you didn't specify language in your tags):
public class AuthorizeIfConfirmedAttribute : AuthorizeAttribute {
protected override bool AuthorizeCore(HttpContextBase httpContext) {
if (!base.AuthorizeCore(httpContext)) return false;
System.Security.Principal.IIdentity user = httpContext.User.Identity;
return WebMatrix.WebData.WebSecurity.IsConfirmed(user.Name);
}
}
[AuthorizeIfConfirmed]
public class MyController { ... }
(If you want to use a custom property on your UserProfile class instead of IsConfirmed then you can simply adjust this code accordingly).
The advantage of this approach is that it keeps all your authorization logic in the usual place, and you can also combine it with role enforcement, e.g.:
[AuthorizeIfConfirmed(Roles = "admin")]
public class MyController { ... }
Note that if you use WebApi or SignalR you may have to include these checks in however you are performing request authorization for the apis as well.
I user Application_AuthenticateRequest in Global.asax.. Because my application needs authenticate on all pages..
protected void Application_AuthenticateRequest()
{
if (WebSecurity.IsAuthenticated)
{
bool isConfirmed = (..your codes here..)
if (isConfirmed == false)
{
WebSecurity.Logout();
}
}
}

Passing parameter through all MVC4 pages

In my application there's the need of passing out a specific parameter, when it exists, through all pages.
What is the best way of I can do this?
There's some function that is called whenever I do an GET or POST requisition, in which I can verify if the parameter exist and persist it?
Create an action filter like the one below.
public sealed class ScaffoldActionFilter : ActionFilterAttribute
{
public override void OnActionExecuted(ActionExecutedContext filterContext)
{
var model = filterContext.Controller.ViewData.Model as PageModelBase;
// Whatever you want to do.
model.myParam = "Im available in all views";
}
}
Next register it to run on every request. Look in app_start/filterconfig.cs
and and it like this.
filters.Add(new ScaffoldActionFilter());
Now just return the standard pagebasemodel or a derived type from every view and you have what you want.