Custom Authorization attribute with Dependency resolved using HttpContext.
FOR SYNCHRONOUS
public class CustomAuthFilter : AuthorizeAttribute, IAuthorizationFilter
{
public CustomAuthFilter(params string[] args)
{
Args = args;
}
public string[] Args { get; }
public void OnAuthorization(AuthorizationFilterContext context)
{
int x = this.Args.Length;
var service = context.HttpContext.RequestServices.GetRequiredService<ISample>();
string name = service.GetName();
context.Result = new UnauthorizedResult();
}
}
Controller
[CustomAuthFilter("Anish","jiya","sample")]public async Task<IActionResult> Index()
{
ViewBag.Title = "Organizer - Conference Overview";
return View(await repo.GetAll());
}
FOR ASYNC
public class CustomAuthFilter : AuthorizeAttribute, IAsyncAuthorizationFilter
{
public CustomAuthFilter(params string[] args)
{
Args = args;
}
public string[] Args { get; }
public async Task OnAuthorizationAsync(AuthorizationFilterContext context)
{
//DO Whatever...
//Resolve Services from the container
var service = context.HttpContext.RequestServices.GetRequiredService<ISample>();
var httpClientFactory = context.HttpContext.RequestServices.GetRequiredService<IHttpClientFactory>();
string name = service.GetName();
using var httpClient = httpClientFactory.CreateClient();
var resp = await httpClient.GetAsync("https://jsonplaceholder.typicode.com/todos/1");
var data = await resp.Content.ReadAsStringAsync();
//Return based on logic
context.Result = new UnauthorizedResult();
}
}
Comments
Post a Comment