So I have a Base controller that all controllers inherit from, and it implements ApiController, in override initialize I have something like this:
protected override void Initialize(HttpControllerContext controllerContext)
{
var tenantId= requestUtils.GetFromHeader(controllerContext.Request);
if (tenantId!= null)
log4net.ThreadContext.Properties["tenantId"] = tenantId;
else
log4net.ThreadContext.Properties["tenantId"] = "default";
await unitOfWork.SetTenantIdentifier(tenantIdentifier);
base.Initialize(controllerContext);
}
I need to set the tenantId for the unitofwork (since I have multitenant solution) and it needs an await before it (since I need to fetch something from the db)but I can't make Initialize an async Task so I'm trying to find a workaround or so.
//await unitOfWork.SetTenantIdentifier(tenantIdentifier);
unitOfWork.SetTenantIdentifier(tenantIdentifier).Wait();
You should verify that there is no risk of deadlock on the Wait().
Related
I am trying to roll out authorization in an entire environment and would like to feature flag this for quick rollback if it goes south. Once we know all services are aligned with OAuth this feature will be removed and become permanent. I have chosen the IAutofacAuthorizationFilter to inject an object to determine the feature flag state which a typical attribute doesn't offer.
I'd like to enable the default behavior as if I had decorated the controller with [Authorize] if the feature is true otherwise let the methods execute without it, but I'm having trouble enabling the default behavior from inside a IAutofacAuthorizationFilter where there is no base class to override like await base.OnAuthorizationAsync(actionContext, cancellationToken); inside a AuthorizeAttribute.
What I have working so far:
public class FeatureBasedAuthorizeAttribute : IAutofacAuthorizationFilter
{
private readonly IFeatureManager _featureManager;
public FeatureBasedAuthorizeAttribute(IFeatureManager featureManager)
{
_featureManager = featureManager;
}
public async Task OnAuthorizationAsync(HttpActionContext actionContext, CancellationToken cancellationToken)
{
if (_featureManager.IsEnabled<EnableAppAuthorization>())
{
// Return result of default ASP.Net authorization here... How?
}
// Return without Authorization (current state)
await Task.FromResult(0);
}
}
// Wire up in startup.cs
builder.Register(c => new FeatureBasedAuthorizeAttribute(c.Resolve<IFeatureManager>()))
.AsWebApiAuthorizationFilterForAllControllers()
.InstancePerRequest();
Ultimately time away from the screen solved it for me. My solution was this:
public async Task OnAuthorizationAsync(HttpActionContext actionContext, CancellationToken cancellationToken)
{
if (_featureManager.IsEnabled<EnableAppAuthorization>())
{
// Return result of default ASP.Net authorization
var authorizeAttribute = new AuthorizeAttribute();
await authorizeAttribute.OnAuthorizationAsync(actionContext, cancellationToken);
}
// Return without Authorization (current state)
await Task.FromResult(0);
}
I'd like to be able to pass cancellation tokens via dependency injection instead of as parameters every time. Is this a thing?
We have an asp.net-core 2.1 app, where we pass calls from controllers into a maze of async libraries, handlers and other services to fulfil the byzantine needs of the fintech regulatory domain we service.
At the top of the request, I can declare that I want a cancellation token, and I'll get one:
[HttpPost]
public async Task<IActionResult> DoSomeComplexThingAsync(object thing, CancellationToken cancellationToken) {
await _someComplexLibrary.DoThisComplexThingAsync(thing, cancellationToken);
return Ok();
}
Now, I want to be a good async programmer and make sure my cancellationToken gets passed to every async method down through the call chain. I want to make sure it gets passed to EF, System.IO streams, etc. We have all the usual repository patterns and message passing practices you'd expect. We try to keep our methods concise and have a single responsibility. My tech lead gets visibly aroused by the word 'Fowler'. So our class sizes and function bodies are small, but our call chains are very, very deep.
What this comes to mean is that every layer, every function, has to hand off the damn token:
private readonly ISomething _something;
private readonly IRepository<WeirdType> _repository;
public SomeMessageHandler(ISomething<SomethingElse> something, IRepository<WeirdType> repository) {
_something = something;
_repository = repository;
}
public async Task<SomethingResult> Handle(ComplexThing request, CancellationToken cancellationToken) {
var result = await DoMyPart(cancellationToken);
cancellationToken.ThrowIfCancellationRequested();
result.SomethingResult = await _something.DoSomethingElse(result, cancellationToken);
return result;
}
public async Task<SomethingResult> DoMyPart(ComplexSubThing request, CancellationToken cancellationToken) {
return await _repository.SomeEntityFrameworkThingEventually(request, cancellationToken);
}
This goes on ad infinitum, as per the needs of our domain complexity. It seems like CancellationToken appears more times in our codebase than any other term. Our arg lists are often already too long (i.e. more than one) as it is, even though we declare a million object types. And now we have this extra little cancellation token buddy hanging around in every arg list, every method decl.
My question is, since Kestrel and/or the pipeline gave me the token in the first place, it'd be great if I could just have something like this:
private readonly ISomething _something;
private readonly IRepository<WeirdType> _repository;
private readonly ICancellationToken _cancellationToken;
public SomeMessageHandler(ISomething<SomethingElse> something, ICancellationToken cancellationToken) {
_something = something;
_repository = repository;
_cancellationToken = cancellationToken;
}
public async Task<SomethingResult> Handle(ComplexThing request) {
var result = await DoMyPart(request);
_cancellationToken.ThrowIfCancellationRequested();
result.SomethingResult = await _something.DoSomethingElse(result);
return result;
}
public async Task<SomethingResult> DoMyPart(ComplexSubThing request) {
return await _repository.SomeEntityFrameworkThingEventually(request);
}
This would then get passed around via DI composition, and when I had something that needs the token explicitly I could do this:
private readonly IDatabaseContext _context;
private readonly ICancellationToken _cancellationToken;
public IDatabaseRepository(IDatabaseContext context, ICancellationToken cancellationToken) {
_context = context;
_cancellationToken = cancellationToken;
}
public async Task<SomethingResult> DoDatabaseThing() {
return await _context.EntityFrameworkThing(_cancellationToken);
}
Am I nuts? Do I just pass the damn token, every damn time, and praise the async gods for the bounty that has been given? Should I just retrain as a llama farmer? They seem nice. Is even asking this some kind of heresy? Should I be repenting now? I think for async/await to work properly, the token has to be in the func decl. So, maybe llamas it is
First of all, there are 3 injection scopes: Singleton, Scoped and Transient. Two of those rule out using a shared token.
DI services added with AddSingleton exist across all requests, so any cancellation token must be passed to the specific method (or across your entire application).
DI services added with AddTransient may be instantiated on demand and you may get issues where a new instance is created for a token that is already cancelled. They'd probably need some way for the current token to be passed to [FromServices] or some other library change.
However, for AddScoped I think there is a way, and I was helped by this answer to my similar question - you can't pass the token itself to DI, but you can pass IHttpContextAccessor.
So, in Startup.ConfigureServices or the extension method you use to register whatever IRepository use:
// For imaginary repository that looks something like
class RepositoryImplementation : IRepository {
public RepositoryImplementation(string connection, CancellationToken cancellationToken) { }
}
// Add a scoped service that references IHttpContextAccessor on create
services.AddScoped<IRepository>(provider =>
new RepositoryImplementation(
"Repository connection string/options",
provider.GetService<IHttpContextAccessor>()?.HttpContext?.RequestAborted ?? default))
That IHttpContextAccessor service will be retrieved once per HTTP request, and that ?.HttpContext?.RequestAborted will return the same CancellationToken as if you had called this.HttpContext.RequestAborted from inside a controller action or added it to the parameters on the action.
I think you are thinking in a great way, I do not think you need to regret or repent.
This is a great idea, I also thought about it, and I implement my own solution
public abstract class RequestCancellationBase
{
public abstract CancellationToken Token { get; }
public static implicit operator CancellationToken(RequestCancellationBase requestCancellation) =>
requestCancellation.Token;
}
public class RequestCancellation : RequestCancellationBase
{
private readonly IHttpContextAccessor _context;
public RequestCancellation(IHttpContextAccessor context)
{
_context = context;
}
public override CancellationToken Token => _context.HttpContext.RequestAborted;
}
and the registration should be like this
services.AddHttpContextAccessor();
services.AddScoped<RequestCancellationBase, RequestCancellation>();
now you can inject RequestCancellationBase wherever you want, and the better thing is that you can directly pass it to every method that expects CancellationToken this is because of public static implicit operator CancellationToken(RequestCancellationBase requestCancellation)
this solution helped me, hope it is helpful for you also
I'm trying to write a custom policy for an ASP.NET Core 3.1 web application, using a custom Identity storage provider.
I've tried to wrap my head around the fact that policies in ASP.NET Core are designed to take user informations from an HttpContext object, when I read this in a MSDN Article:
once you hold a reference to the user, you can always find the username from the claims and run a query against any database or external service
I started writing my own policy (as of now a simple role requirement) injecting the UserManager into the constructor:
public class RoleHandler : AuthorizationHandler<RoleRequirement>
{
private UserManager<AppUser> UserManager;
public RoleHandler(UserManager<AppUser> usermanager)
{
UserManager = usermanager;
}
}
Now I have a couple problems:
INJECTING A SCOPED SERVICE IN A SINGLETON
Policies are supposed to be lasting for the entire application life, so that would be a Singleton:
services.AddSingleton<IAuthorizationHandler, RoleHandler>();
but the UserManager injected in the policy server is a scoped service and that is not allowed. Solution was very easy, changing the configuration of the policy service from a singleton to a scoped service
services.AddScoped<IAuthorizationHandler, RoleHandler>();
but I don't know whether that cause any issue or not.
WRITING AN ASYNCHRONOUS POLICY HANDLER
This is my implementation of the HandleRequirementAsync method:
protected override Task HandleRequirementAsync(AuthorizationHandlerContext context, RoleRequirement requirement)
{
AppUser user = UserManager.FindByIdAsync(context.User.Identity.Name).Result;
if (user != null)
{
bool result = UserManager.IsInRoleAsync(user, requirement.Role.ToString()).Result;
if (result) context.Succeed(requirement);
}
return Task.CompletedTask;
}
I used Task.Result but it blocks the thread. I can't use await because that would make the method returning a Task<Task> instead of a Task and I can't change it. How can I solve this?
Don't return Task.CompletedTask.
When you declare a method as async, it implicitly returns a Task when the first await is hit:
protected override async Task HandleRequirementAsync(AuthorizationHandlerContext context, RoleRequirement requirement)
{
AppUser user = await UserManager.FindByIdAsync(context.User.Identity.Name);
if (user != null)
{
bool result = await UserManager.IsInRoleAsync(user, requirement.Role.ToString());
if (result) context.Succeed(requirement);
}
}
Task.CompletedTask is generally used when you need to implement a Task returning method synchronously, which you are not.
My HandleRequirementAsync also calls httpClient.GetAsync (Blazor server, .NET 5), adding async to the HandleRequirementAsync and execute the await hpptClient.GetAsync() breaks the authorization. With async method with delays, Try typing the route address in the browser and it will redirect to not authorized page, even though the context.Succeed(requirement) is executed.
The working solution for me is to keep the HandleRequirementAsync as it is, returning Task.CompletedTask. For the async method we need to call, just use pattern for calling async method from non async method.
The one I use is from https://stackoverflow.com/a/43148321/423356
my sample async method:
public async Task<IList<Permission>> GetGroupPermissions(int userId)
{
HttpResponseMessage response = await _httpClient.GetAsync(string.Format("Auth/GroupPermissions/{0}", userId));
try
{
var payload = await response.Content.ReadFromJsonAsync<List<Permission>>();
response.EnsureSuccessStatusCode();
return payload;
}
catch
{
return new List<Permission>();
}
}
HandleRequirementAsync:
protected override Task HandleRequirementAsync(AuthorizationHandlerContext context, PermissionRequirement requirement)
{
var t2 = (Task.Run(() => GetGroupPermissions(userId)));
t2.Wait();
var userGroupPermissions = t2.Result;
if (!userGroupPermissions.Contains(requirement.Permission))
{
//context.Fail(); //no need to fail, other requirement might success
return Task.CompletedTask;
}
context.Succeed(requirement);
return Task.CompletedTask;
}
I've got an expensive "current user" obejct that I want to cache for the duration of the request. To do this I'm using the built-in DI in asp.net core, to create a ICurrentUser object when requested. It looks like this:
public class CurrentUserCache : ICurrentUser
{
public CurrentUserCache(IHttpContextAccessor httpContextAccessor, UserManager userManager)
{
var httpContextAccessor1 = httpContextAccessor;
_user = new Lazy<User>(() => httpContextAccessor1.HttpContext.User != null ? userManager.GetUserAsync(httpContextAccessor1.HttpContext.User).Result : null);
}
private Lazy<User> _user;
public User User {
get => _user.Value;
set {}
}
}
It's using a Lazy object to defer the retrieval of the object, since some controller actions might not need to make use of it.
My problem is - the code inside the lazy to get the user, is blocking (.Result). I don't want to do that, since it's quite expensive.
I don't know how to make this code async. I could possibly create a Lazy<Task<user>> to get the user, but then I can't await that in my user property, because it's a property and properties can't be async.
So - how can I turn this code into something that works well for async?
Thanks!
Turn the property into an awaitable function
public class CurrentUserCache : ICurrentUser {
public CurrentUserCache(IHttpContextAccessor httpContextAccessor, UserManager userManager) {
_user = new Lazy<Task<User>>(() =>
userManager.GetUserAsync(httpContextAccessor.HttpContext.User)
);
}
private Lazy<Task<User>> _user;
public Task<User> GetUserAsync() {
return _user.Value;
}
}
I am working on some Restful APIs in .net web api . All the API controllers that I am working on inherit from a base API controller. It has some logic in the Initialize function.
protected override void Initialize(HttpControllerContext controllerContext)
{
// some logic
}
There is a new product requirement comes in and I want to return the response to the client in the Initialize function depending on some criteria.
e.g.
protected override void Initialize(HttpControllerContext controllerContext)
{
// some logic
controllerContext.Request.CreateErrorResponse(HttpStatusCode.Unauthorized, "error");
}
however it seems like that the .net pipeline still moves on even I return the response already.
Is there anyway to return the response inside that function and stop the execution? Or I have to refactor the existing code to do it in another way?
Here is a hacky way of accomplishing what you want. Throw an exception like so.
protected override void Initialize(HttpControllerContext controllerContext)
{
// some logic
if(youhavetosend401)
throw new HttpResponseException(HttpStatusCode.Unauthorized);
}
The cleaner way, assuming what you are trying to do is all about authorization is to create an authorization filter like so.
public class MyAuthorizeAttribute : AuthorizeAttribute
{
protected override bool IsAuthorized(HttpActionContext context)
{
// Do your stuff and determine if the request can proceed further or not
// If not, return false
return true;
}
}
Apply the filter on the action method or controller or even globally.
[MyAuthorize]
public HttpResponseMessage Get(int id)
{
return null;
}
Use HttpResponseException to send the HttpResponseMessage created for Error.
protected override void Initialize(System.Web.Http.Controllers.HttpControllerContext controllerContext)
{
//Your Logic
throw new HttpResponseException(controllerContext.Request.CreateErrorResponse(System.Net.HttpStatusCode.Unauthorized, "error"));
base.Initialize(controllerContext);
}
Use
Application.CompleteRequest()
it will fire the EndRequest event.