Question When Success Valid Access Token Not Return Result And Return Invalid ?

ahmedsalah

Active member
Joined
Sep 26, 2018
Messages
32
Programming Experience
3-5
I validate token using middle ware in asp.net core 2.2 in case of access token not valid return message not valid and this case work perfect

problem come when valid token success the problem is next request no give me result of action executed so that what i do for that working

problem is when success valid token is OK it reach until next but not display after that action that have result

in both cases if valid token or not valid return invalid token message

what i have tried

C#:
public async Task InvokeAsync(HttpContext context, DataContext dataContext)
        {
            var validKey = false;
            // than you logic to validate token          
            var CheckExistAccessToken = context.Request.Headers.ContainsKey("Authorization");
            var AccessTokenValue = context.Request.Headers["Authorization"].SingleOrDefault();
            //var token = AccessTokenValue.Substring(AccessTokenValue.IndexOf(' ') + 1);
            if (CheckExistAccessToken)
            {
                bool isvalid = _tockenvalidator.ValidateToken(AccessTokenValue);
                if (isvalid)
                {
                    validKey = true;
                }
                else
                {
                    validKey = false;
                }
                }
            if (!validKey)
            {
                context.Response.StatusCode = (int)HttpStatusCode.Forbidden;
                await context.Response.WriteAsync("Invalid Token");
            }
            //if valid than next middleware Invoke
            else
            {
                await _next.Invoke(context);
// not return to me action i write on postman and return also message not valid token
            }
        }
    }
public static class TokenExtensions
    {
        public static IApplicationBuilder UseTokenAuth(this IApplicationBuilder builder)
        {
              return builder.UseMiddleware<TokenValidateMiddleware>();
        }
    }
on configure of startup.cs

C#:
if (env.IsDevelopment())
            {
                app.UseDeveloperExceptionPage();
            }
            else
            {
                // The default HSTS value is 30 days. You may want to change this for production scenarios, see Enforce HTTPS in ASP.NET Core.
                app.UseHsts();
            }
            app.UseTokenAuth();
            app.UseHttpsRedirection();
            app.UseStatusCodePagesWithReExecute("/error/{0}");
            app.UseMvc();
            app.UseCors("CorsData");
            app.UseStaticFiles();
            app.UseDefaultFiles();
 
Last edited by a moderator:
No related to your problem, but will help make the code more legible: Change:
C#:
bool isvalid = _tockenvalidator.ValidateToken(AccessTokenValue);
if (isvalid)
{
    validKey = true;
}
else
{
    validKey = false;
}
to
C#:
validKey = _tockenvalidator.ValidateToken(AccessTokenValue);

Now regarding your problem. What happens if you change line 28 from:
C#:
await _next.Invoke(context);
to
C#:
await _next.Invoke(context).ConfigureAwait(false);
Beware that this is just a hack on the same scale as the VB6 of just throwing in a DoEvents(). You really should understand what is causing the deadlock and work to prevent the deadlock from happening in the first place.
(A good reference to read: Don't Block on Async Code )
 
I've not read that newer response. I've read his older responses for classic WebAPI and MVC where using the not being tied to a synchronization context would potentially impact the available thread pools being used by ASP.NET. Seeing that newer response, it looks like the newer .NET Core doesn't even have a synchronization context anymore. So yes, in ASP.NET Core, that would be redundant (or more of a no-op).

Anyway, since you the OP is using. NET Core, and there is not readily available way to break what looks to be a deadlock, then the OP has no recourse than break into the debugger when he gets the hanging behavior and try to see examine each thread's callstack to see if he has some kind of circular dependency that is inducing the deadlock.
 
Yes, I've seen that one too. However, just because ConfigureAwait(false) has had the plug pulled by the ASP Core dev team, it is still recommended to use ConfigureAwait(false) in library projects fully supported by DotNet 4.6 independently etc but not in MVC/ASP since Microsoft have ditched context.
 
Last edited:
Looks like Ahmed has gotten desperate and spammed multiple sites with the same question:
StackOverflow
ASP.NET
CSharp Corner
CodeProject
DreamInCode

@ahmed: From what I can see, TokenValidateMiddleware is custom code you've written. Can you share the code with us? Perhaps the source of the deadlock is present there?
 

Latest posts

Back
Top Bottom