I have an authorization handler in which I enter a custom personService. I hooked up both the handler and PersonService via DI by default. The IhttpContextAccessor personal service works fine elsewhere in my application, but when it is called from the authorization handler, httpcontext is always null.
Here is the AuthHandler:
public class NoChildrenRequirement : AuthorizationHandler<NoChildrenRequirement>, IAuthorizationRequirement
{
private readonly IPersonService _personService;
public NoChildrenRequirement(IPersonService personService)
{
_personService = personService;
}
protected override void Handle(AuthorizationContext context, NoChildrenRequirement requirement)
{
var user = context.User;
var identity = user.Identity;
var isAuthenticated = identity.IsAuthenticated;
var currentPerson = _personService.CurrentPerson();
if (isAuthenticated && currentPerson != null && !currentPerson.IsAChild)
{
context.Succeed(requirement);
return;
}
context.Fail();
}
}
This is where I plug it in at startup:
services.AddTransient<NoChildrenRequirement>();
services.Configure<AuthorizationOptions>(options =>
{
options.AddPolicy("NoChildren", policy => policy.Requirements.Add(
services.BuildServiceProvider().GetRequiredService<NoChildrenRequirement>()));
});
Here is the start of face service:
public class PersonService : IPersonService
{
private readonly IPersonRepository _repository;
private readonly IMemoryCache _memoryCache;
private readonly IConfigService _configService;
private readonly IHttpContextAccessor _context;
private readonly IResourceService _resourceService;
private readonly string _cacheKey = "Person_";
public PersonService(IPersonRepository repository, IMemoryCache memoryCache,
IConfigService configService, IHttpContextAccessor context,
IResourceService resourceService)
{
_repository = repository;
_memoryCache = memoryCache;
_configService = configService;
_context = context;
_resourceService = resourceService;
}
This is where I connect the personal service to the launch:
services.AddTransient<IPersonService, PersonService>();
: IHttpContextAccessor _context; , , personalervice authhandler, , HttpContextAccessor null, HttpContext HttpContextAccessor null. ?