locked
when implement middle ware validate token is valid OK but next request not handle and not give me result succeed ? RRS feed

  • Question

  • User696604810 posted

    I validate token using middle ware 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

    and only return invalid token message i write on middle ware in both cases of valid or not valid access token

    when i test it by post man it working good 

    if token is not valid

    return invalid token

    else

    return user menu data in case of make request to get data for menu as example 

    my code as below :

    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);
                   
                }
            }
        }
     public static class TokenExtensions
        {
            public static IApplicationBuilder UseTokenAuth(this IApplicationBuilder builder)
            {
                  return builder.UseMiddleware<TokenValidateMiddleware>();
                
            }
        }
    on configure of startup.cs
    
     if (env.IsDevelopment())
                {
                    app.UseDeveloperExceptionPage();
                }
                else
                {
                    // The default HSTS value is 30 days. You may want to change this for production scenarios, see https://aka.ms/aspnetcore-hsts.
                    app.UseHsts();
                }
               
               
                app.UseTokenAuth(); 
    
                app.UseHttpsRedirection();
               
                app.UseStatusCodePagesWithReExecute("/error/{0}");
            
                app.UseMvc();
                app.UseCors("CorsData");
                app.UseStaticFiles();
                app.UseDefaultFiles();

    when success token by debug

    i reach to this line await _next.Invoke(context);

    but not give me result as action i write on post man

    suppose when access token valid return data for user menu 

    this working on post man but on my app return invalid token why 

    this is my question

    Saturday, September 14, 2019 1:07 AM

Answers

  • User696604810 posted

    can any one help me on that

    • Marked as answer by Anonymous Thursday, October 7, 2021 12:00 AM
    Saturday, September 14, 2019 6:24 PM

All replies

  • User475983607 posted

    If I understand correctly, the custom middleware functions as expected when submitting a bearer token using PostMan as the client.  The custom middleware does not function as expected when testing using another client.  

    Can you explain or share the client code?  Specifically, how does the client pass the bearer token?

    Saturday, September 14, 2019 12:07 PM
  • User696604810 posted

    when make post man in case of valid access token

    this image show 

    http://www.mediafire.com/view/h5am34ceqa4bvsh/validaccesstoken.png/file

    eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJzdWIiOiJBZG1pbiIsInVzZXIiOnsiaWQiOiJBZG1pbiJ9fQ.-sfTpg64pHfsXPDvS_vFQHn0LqogPXRDIYg0zzaZHik

    and when change it and add some more characters it is not valid and return invalid

    mmmmmmmmmInR5cCI6IkpXVCJ9.eyJzdWIiOiJBZG1pbiIsInVzZXIiOnsiaWQiOiJBZG1pbiJ9fQ.-sfTpg64pHfsXPDvS_vFQHn0LqogPXRDIYg0zzaZHik

    https://www.mediafire.com/view/vbb0gc627t70k9e/invalidaccesstoken.png/file

    under configure service on startup.cs file i have configure service as following :

     public void ConfigureServices(IServiceCollection services)
            {
          
                services.AddCors(options => options.AddPolicy("CorsData", builder =>
                {
    
                    builder.AllowAnyOrigin().AllowAnyMethod().AllowAnyHeader();
    
                }));
                //=================This Setting Related To generate Access Token Data===============
                var signingkey = new SymmetricSecurityKey(Encoding.UTF8.GetBytes("this is secret phrase"));
    
                services.AddAuthentication(options =>
                {
                    options.DefaultAuthenticateScheme = JwtBearerDefaults.AuthenticationScheme;
                    options.DefaultChallengeScheme = JwtBearerDefaults.AuthenticationScheme;
    
                }).AddJwtBearer(cfg =>
                {
                    cfg.RequireHttpsMetadata = false;
                    cfg.SaveToken = false;
                    cfg.TokenValidationParameters = new Microsoft.IdentityModel.Tokens.TokenValidationParameters()
                    {
                        IssuerSigningKey = signingkey,
                        ValidateAudience = false,
                        ValidateIssuer = false,
                        ValidateLifetime = false,
                        ValidateIssuerSigningKey = true
                    };
                });
                //=================
                services.AddMvc().SetCompatibilityVersion(CompatibilityVersion.Version_2_2);
    
          
    
            }

    can you help me in that

    Saturday, September 14, 2019 3:56 PM
  • User475983607 posted

    can you help me in that

    I'm not sure what help you are looking for...

    As I understand, testing with PostMan works but your client application does not.  Your follow up post confirms PostMan functions as expected? 

    Can you explain how your custom token validation code is intended to function?  Keep in mind, you approach is non standard and not recommended.  As I recommended in your similar post, you should use the standard API library that comes with the framework.  The API along with [Authorize] will return a standard 401 (Unauthorized) HTTP response.

    Saturday, September 14, 2019 5:27 PM
  • User696604810 posted
     public  interface ItockenValidate
        {
           bool ValidateToken(string AccessTokenValue);
        }
    
    public class tockenValidate : ItockenValidate
    {
    public bool ValidateToken(string AccessTokenValue)
    {
    
    try
    {
    var tokenHandler = new JwtSecurityTokenHandler();
    var validationParameters = GetValidationParameters();
    
    SecurityToken validatedToken;
    
    IPrincipal principal = tokenHandler.ValidateToken(AccessTokenValue, validationParameters, out validatedToken);
    return true;
    }
    catch (Exception)
    {
    return false;
    }
    
    }
    TokenValidationParameters GetValidationParameters()
    {
    return new TokenValidationParameters()
    {
    ValidateLifetime = false, // Because there is no expiration in the generated token
    ValidateAudience = false, // Because there is no audiance in the generated token
    ValidateIssuer = false, // Because there is no issuer in the generated token
    IssuerSigningKey = new SymmetricSecurityKey(Encoding.UTF8.GetBytes("401b09eab3c013d4ca54922bb802bec8fd5318192b0a75f201d8b3727429090fb337591abd3e44453b954555b7a0812e1081c39b740293f765eae731f5a65ed1")) // The same key as the one that generate the token
    //pay = ((JwtSecurityToken)access_token).Payload["userId"].ToString()
    };
    }
    }
    }

    Saturday, September 14, 2019 5:33 PM
  • User696604810 posted

    can any one help me on that

    • Marked as answer by Anonymous Thursday, October 7, 2021 12:00 AM
    Saturday, September 14, 2019 6:24 PM