13 Replies - 468 Views - Last Post: 16 September 2019 - 10:08 PM Rate Topic: -----

#1 ahmedba   User is offline

  • D.I.C Head

Reputation: -1
  • View blog
  • Posts: 220
  • Joined: 24-January 14

when success valid access token not return result and return invalid ?

Posted 13 September 2019 - 06:38 PM

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

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

 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");


Is This A Good Question/Topic? 0
  • +

Replies To: when success valid access token not return result and return invalid ?

#2 Skydiver   User is offline

  • Code herder
  • member icon

Reputation: 7192
  • View blog
  • Posts: 24,376
  • Joined: 05-May 12

Re: when success valid access token not return result and return invalid ?

Posted 14 September 2019 - 06:29 PM

Also posted here.
Was This Post Helpful? 0
  • +
  • -

#3 andrewsw   User is offline

  • never lube your breaks
  • member icon

Reputation: 6829
  • View blog
  • Posts: 28,319
  • Joined: 12-December 12

Re: when success valid access token not return result and return invalid ?

Posted 15 September 2019 - 03:51 AM

What debugging steps have you taken?
Was This Post Helpful? 0
  • +
  • -

#4 Skydiver   User is offline

  • Code herder
  • member icon

Reputation: 7192
  • View blog
  • Posts: 24,376
  • Joined: 05-May 12

Re: when success valid access token not return result and return invalid ?

Posted 15 September 2019 - 08:06 AM

Looks like Ahmed has gotten desperate and spammed multiple sites with the same question:
StackOverflow
ASP.NET
CSharp Corner
CodeProject

ahmedba: 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?
Was This Post Helpful? 0
  • +
  • -

#5 ahmedba   User is offline

  • D.I.C Head

Reputation: -1
  • View blog
  • Posts: 220
  • Joined: 24-January 14

Re: when success valid access token not return result and return invalid ?

Posted 15 September 2019 - 08:41 AM

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

};
}
}
}


This post has been edited by Skydiver: 15 September 2019 - 10:59 AM
Reason for edit:: Put code in code tags. Learn to do this yourself.

Was This Post Helpful? 0
  • +
  • -

#6 Skydiver   User is offline

  • Code herder
  • member icon

Reputation: 7192
  • View blog
  • Posts: 24,376
  • Joined: 05-May 12

Re: when success valid access token not return result and return invalid ?

Posted 15 September 2019 - 11:03 AM

So that class there is called tockenValidate, but somehow you are using a different class named TokenValidateMiddleware in this code:
builder.UseMiddleware<TokenValidateMiddleware>();



Where is the code for TokenValidateMiddleware?
Was This Post Helpful? 0
  • +
  • -

#7 ahmedba   User is offline

  • D.I.C Head

Reputation: -1
  • View blog
  • Posts: 220
  • Joined: 24-January 14

Re: when success valid access token not return result and return invalid ?

Posted 15 September 2019 - 12:27 PM

using Microsoft.AspNetCore.Builder;
using Microsoft.AspNetCore.Hosting;
using Microsoft.AspNetCore.Http;
using Microsoft.AspNetCore.Http.Extensions;
using Microsoft.AspNetCore.Http.Internal;
using Microsoft.AspNetCore.Mvc;
using Microsoft.AspNetCore.Mvc.Abstractions;
using Microsoft.AspNetCore.Mvc.Infrastructure;
using Microsoft.AspNetCore.Routing;
using Microsoft.Extensions.Logging;
using Microsoft.Extensions.Options;
using Microsoft.IdentityModel.Tokens;
using Microsoft.Net.Http.Headers;
using Security.Data;
using Security.Services;
using System;
using System.Collections.Generic;
using System.IdentityModel.Tokens.Jwt;
using System.Linq;
using System.Net;
using System.Net.Http;
using System.Security.Claims;
using System.Security.Principal;
using System.Text;
using System.Threading.Tasks;

namespace Security.MiddleWare
{
    
    public class TokenValidateMiddleware 
    {
        // private const string AccessTokenValue = "3443444476655"; 

        private readonly RequestDelegate _next;
        private ItockenValidate _tockenvalidator { get; set; }
        public TokenValidateMiddleware(RequestDelegate next, ItockenValidate tockenvalidator)
        {
            _next = next;
            _tockenvalidator = tockenvalidator;
          
        }
       
      

       
        public string GenerateTokens(string userId)
        {

            var Claims = new Claim[]
                     {
            new Claim(JwtRegisteredClaimNames.Sub,userId)
                     };
            var signingkey = new SymmetricSecurityKey(Encoding.UTF8.GetBytes("[email protected]"));
            var SigningCredntials = new SigningCredentials(signingkey, SecurityAlgorithms.HmacSha256);
            var Jwt = new JwtSecurityToken();
            var jsonu = new { id = userId };
            Jwt.Payload["user"] = jsonu;
          
            return new JwtSecurityTokenHandler().WriteToken(Jwt);
        }
        
       
        
        
        

        //==============
        private static 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
               
        };
        }
        // always should be defiened Invoke or InvokeAsync with HttpContext and returned Task (You can also inject you services here - for example DataContext)
        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)
                {
                    //string AccessTokenValue = ValidateToken(GetUserId.ToString());
                    //bool isvalid = ValidateToken(AccessTokenValue);
                    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 validm than next middleware Invoke
                else
            {
                
                context.Request.EnableRewind();
                await _next.Invoke(context);
              
                    
                   
                }
            
            
        }
    }
    
    
        public static IApplicationBuilder UseTokenAuth(this IApplicationBuilder builder, Func<HttpContext, Func<Task>, Task> middleware)
        {
            
            return builder.Use(next =>
            {
                return context =>
                {
                    Func<Task> simpleNext = () => next(context);
                    return middleware(context, simpleNext);
                };
            });

        }
    }
   

}


This post has been edited by Skydiver: 15 September 2019 - 12:47 PM
Reason for edit:: Put code in code tags. Learn how to do this yourself.

Was This Post Helpful? 0
  • +
  • -

#8 Skydiver   User is offline

  • Code herder
  • member icon

Reputation: 7192
  • View blog
  • Posts: 24,376
  • Joined: 05-May 12

Re: when success valid access token not return result and return invalid ?

Posted 15 September 2019 - 03:06 PM

I suggest trying out a dead simple middleware class first. Something like this:
using Microsoft.AspNetCore.Http;
using System.Threading.Tasks;

namespace TestCoreWeb
{
    public class TestMiddleware
    {
        private readonly RequestDelegate _next;

        public TestMiddleware(RequestDelegate next)
            => _next = next;

        public async Task InvokeAsync(HttpContext context)
            => await _next(context);
    }
}



See if you are getting the same kind of hang or deadlock. If there is no hang/deadlock, then progressively add just a little bit of code to the InvokeAsync() until it hangs.

If the system is hanging with that simplest version possible, then there is something else in your configuration that is causing the hang/deadlock.
Was This Post Helpful? 0
  • +
  • -

#9 ahmedba   User is offline

  • D.I.C Head

Reputation: -1
  • View blog
  • Posts: 220
  • Joined: 24-January 14

Re: when success valid access token not return result and return invalid ?

Posted 15 September 2019 - 06:49 PM

but remain main question How to get next request pipeline in case of token success .

suppose i need to get data from action result get request by post man


i write on postman link as then select get then write on header

key : authorization
value :eeerrttyyyyy


if valid access token it will continue execution and get result from action

this is actually i need on next but cannot do it .

[HttpGet(Contracts.ApiRoutes.Security.GetUserMenus)]
       public IActionResult GetUserMenu(string userId)
       {
           string strUserMenus = _SecurityService.GetUserMenus(userId);
           return Ok(strUserMenus);
       }



What I have tried:


public async Task InvokeAsync(HttpContext context, DataContext dataContext)  
        {  
              
                var validKey = false;  
  
               
                if (validKey)  
                {  
                  //success token
                context.Request.EnableRewind();  
                await _next.Invoke(context);  
// how to get next request meaning i need to get result of action getusermenu  
                }  
              
              
               
        }  
    }

Was This Post Helpful? 0
  • +
  • -

#10 Skydiver   User is offline

  • Code herder
  • member icon

Reputation: 7192
  • View blog
  • Posts: 24,376
  • Joined: 05-May 12

Re: when success valid access token not return result and return invalid ?

Posted 15 September 2019 - 07:12 PM

How did you insert that GetUserMenu() into the middleware pipeline? Right now, it looks like that is a controller method rather than a middleware pipeline method.

Also, your original question was regard to things hanging. Are you saying that you've resolved the original issue that you have and now you have a new problem?
Was This Post Helpful? 0
  • +
  • -

#11 Skydiver   User is offline

  • Code herder
  • member icon

Reputation: 7192
  • View blog
  • Posts: 24,376
  • Joined: 05-May 12

Re: when success valid access token not return result and return invalid ?

Posted 15 September 2019 - 07:25 PM

Personally, I think that this what you really need if you just need to setup authorization (rather than authentication) for that particular controller method: Writing your own custom ASP.Net MVC [Authorize] attributes. Yes, it's a bit dated, and I don't know if it'll still work with .NET Core.

Since it looks like you are using claims based JWT anyway, this maybe an alternative which is available out of the box in .NET Core: Claims-based authorization in ASP.NET Core
Was This Post Helpful? 0
  • +
  • -

#12 ahmedba   User is offline

  • D.I.C Head

Reputation: -1
  • View blog
  • Posts: 220
  • Joined: 24-January 14

Re: when success valid access token not return result and return invalid ?

Posted 16 September 2019 - 01:11 AM

see modified my code and get response on variable responseBody
and get result correctly
but on browser show invalid token
although isvalid =true

public async Task InvokeAsync(HttpContext context, DataContext dataContext)
        {
            
                

                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 validm than next middleware Invoke
                else
                {
                //===============
                Stream originalBody = context.Response.Body;

                try
                {
                    using (var memStream = new MemoryStream())
                    {
                        context.Response.Body = memStream;

                        await _next(context);

                        memStream.Position = 0;
                        string responseBody = new StreamReader(memStream).ReadToEnd();//get response body here after next.Invoke()

                        memStream.Position = 0;
                        await memStream.CopyToAsync(originalBody);
                    }

                }
                finally
                {
                    context.Response.Body = originalBody;
                }
}
}

remaining show response on browser
How to do that please
on code above data show but on browser show invalid token

This post has been edited by ahmedba: 16 September 2019 - 02:58 AM

Was This Post Helpful? 0
  • +
  • -

#13 Skydiver   User is offline

  • Code herder
  • member icon

Reputation: 7192
  • View blog
  • Posts: 24,376
  • Joined: 05-May 12

Re: when success valid access token not return result and return invalid ?

Posted 16 September 2019 - 02:30 PM

I don't know why. I recommend using Fiddler to see the full web traffic and not just relying on what the browser finally presents. That may give you a clue regarding what is happening.

Personally, I think that you are using the wrong tool for the job. You should be using the Authorize attribute to determine whether the page needs to be served or not.
Was This Post Helpful? 0
  • +
  • -

#14 ahmedba   User is offline

  • D.I.C Head

Reputation: -1
  • View blog
  • Posts: 220
  • Joined: 24-January 14

Re: when success valid access token not return result and return invalid ?

Posted 16 September 2019 - 10:08 PM

are function generate access token generate valid access token or not ?

I generate access token but i dont know are this valid or not
my access token generate accesss tokr : eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJzdWIiOiJBZG1pbiIsInVzZXIiOnsiaWQiOiJBZG1pbiJ9fQ.-sfTpg64pHfsXPDvS_vFQHn0LqogPXRDIYg0zzaZHik
public string GenerateTokens(string userId, out object jwtcontent)
        {
            
            jwtcontent = new object();
            var securityKey = new SymmetricSecurityKey(Encoding.UTF8.GetBytes("401b09eab3c013d4ca54922bb802bec8fd5318192b0a75f201d8b3727429090fb337591abd3e44453b954555b7a0812e1081c39b740293f765eae731f5a65ed1"));
            var credentials = new SigningCredentials(securityKey, SecurityAlgorithms.HmacSha256);

            var secToken = new JwtSecurityToken(
                signingCredentials: credentials,
               
                claims: new[]
                {
                    new Claim(JwtRegisteredClaimNames.Sub, userId)
                });
               

            var handler = new JwtSecurityTokenHandler();
            var jsonu = new { id = userId };
            secToken.Payload["user"] = jsonu;
            return handler.WriteToken(secToken);
         
        }

Was This Post Helpful? 0
  • +
  • -

Page 1 of 1