I have developed a custom middleware in ASP.NET Core but it gets triggered with every request. My intent is to use it only when a request is authorized.
Update:
I create more sample for you and edit my answer. as you see, before the Next()
method, I checked every token request. If didn't have Authorization
tag in header of context
request, be next()
, If did check the token.
Now, may you have a question that what is the await _next(context);
It is very complex and long, I want to suggest you that visit this link to know what is this issue.
For Create a Middlware
you have to control and develop
.
Middleware
that work General action like you action Authorization
.static Extension class
for relation between Middleware
and startup
.Register
in startup
configuration.Now this is good sample for you:
General Middlware:
public class RequestTokenMiddleware
{
private readonly RequestDelegate _next;
private readonly SignInManager<User> _signInManager;
public RequestTokenMiddleware(RequestDelegate next, SignInManager<User> signInManager)
{
_next = next;
_signInManager = signInManager;
}
public async Task Invoke(HttpContext context)
{
try
{
var hasAuthorization = context.Request.Headers.ContainsKey("Authorization");
if (!hasAuthorization)
{
await _next(context);
}
else
{
var shouldBeNext = false;
foreach (var item in context.Request.Headers)
{
if (item.Key == "Authorization")
{
using (var contextBudget = BudgetUnitOfWork.Get())
{
var tokenCode = item.Value.ToString().Remove(0, 7);
var token = await contextBudget.Db.Token.FirstOrDefaultAsync(x => x.TokenCode == tokenCode).ConfigureAwait(false);
if (token == null || !token.IsValid)
{
signOut(context);
}
else
{
shouldBeNext = true;
}
}
}
}
if (shouldBeNext)
{
await _next(context);
}
}
}
catch (Exception exc)
{
signOut(context);
}
}
private async void signOut(HttpContext context)
{
try
{
await context.Response.WriteAsync(JsonConvert.SerializeObject(ResultModel.Failure(null, ResultModel.StatusType.InvalidToken)));
}
catch (Exception)
{
throw new Exception();
}
}
}
This is Static Extension class for Relation:
public static class ReuqestTokenMiddlewareExctention
{
public static IApplicationBuilder UseTokenValidator(this IApplicationBuilder applicationBuilder)
{
return applicationBuilder.UseMiddleware<RequestTokenMiddleware>();
}
}
Now Register your Middleware
in startup:
public void Configure(IApplicationBuilder app, IHostingEnvironment env, ILoggerFactory loggerFactory, IOptions<SetiaSettings> options)
{
app.UseTokenValidator();
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With