locked
How to implement middle ware to valid access token function using asp.net core 2.2 ? RRS feed

  • Question

  • User696604810 posted

    I have function do validate access token and it work successfully i tested 

    i need to implement middle ware on it .

    How to do that please ?

    i need when valid access token then show result of action i request 

    and if not valid access token then show not valid message 

     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()
    };
    }
    }
    }

    my key is Authorization :JWT eyj0efdggfgfdfdddddds

    Sunday, September 15, 2019 2:58 AM

All replies

  • User-2054057000 posted

    You can use Response-Editing Middleware to return valid or invalid responses based on your token.

    public class ResponseEditingMiddleware
    {
        private RequestDelegate nextDelegate;
        public ResponseEditingMiddleware(RequestDelegate next)
        {
            nextDelegate = next;
        }
     
        public async Task Invoke(HttpContext httpContext)
        {
            await nextDelegate.Invoke(httpContext);
            
            // check token and provide response like await httpContext.Response.WriteAsync("Bad token");
            
        }
    }

    Sunday, September 15, 2019 5:25 AM
  • User696604810 posted

    I have problem here after I do 

    await nextDelegate.Invoke(httpContext);
    not get response body
    i see response body on postman
    but not see on my app why
    http://www.mediafire.com/view/h5am34ceqa4bvsh/validaccesstoken.png/file
    Sunday, September 15, 2019 9:17 AM
  • User696604810 posted

    How to read response body returned because after next 

    Sunday, September 15, 2019 9:31 AM
  • User696604810 posted

    1- i opened postman and i write https://localhost:44363/Security/UserPrograms/Admin as get request

    2-when make send it implement action below :

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

    3- on header key authorization : ejhdddddddfggttt

    4- if is not valid token it must give invalid token

    5-in case of valid it must return result below 

    6- post man return result below when valid access token 

    7- my browser return invalid why i need result as postman

    8- from debug when valid token it reach to next but not show result below 

    [
      {
        "form_name": "FrmAddPrograms",
        "title": "Adding Screens",
        "url": "",
        "permissions": {
          "Insert": "True",
          "Edit": "True",
          "Read": "True",
          "Delete": "True",
          "Print": "True",
          "Excel": "False",
          "RecordList": "False"
        }
      },
      {
        "form_name": "FrmFollowingOrders",
        "title": "Following Orders",
        "url": "",
        "permissions": {
          "Insert": "True",
          "Edit": "True",
          "Read": "True",
          "Delete": "True",
          "Print": "True",
          "Excel": "False",
          "RecordList": "False"
        }
      },
      {
        "form_name": "frmItemsSerialNumbers",
        "title": "Items Serial Numbers",
        "url": "",
        "permissions": {
          "Insert": "True",
          "Edit": "True",
          "Read": "True",
          "Delete": "True",
          "Print": "True",
          "Excel": "False",
          "RecordList": "False"
        }
      },

    Sunday, September 15, 2019 10:22 AM
  • User475983607 posted

    PostMan works as expected but you application does not?  Is this a correct statement?

    The design will not work if you've built a browser based application.  Your design requires a code based solution.  Either server side using C# or within the browser using JavaScript. 

    Keep in mind the standard JWT token API handles this use case rather well.  It's not clear why you've build a custom solution which is limiting your options. 

    Sunday, September 15, 2019 12:11 PM
  • User696604810 posted

    i dont understand that can you clear please 

    if i test my app with postman and give me result are this OK or not ?

    Sunday, September 15, 2019 3:31 PM
  • User475983607 posted

    if i test my app with postman and give me result are this OK or not ?

    I'm not sure what you are asking. 

    If PostMan works as expected and your application does not work as expected then logically your application probably has issues.  I've asked repeatedly to share your client application but you have not.  

    In a previous thread I provided a working JWT application.  I'm not sure what else I can do to help you.

    Sunday, September 15, 2019 4:21 PM
  • User696604810 posted

    this is my client connection 

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

    Sunday, September 15, 2019 6:47 PM
  • User696604810 posted

    I share connection can any one help me

    Monday, September 16, 2019 1:17 AM
  • User711641945 posted

    Hi ahmedbarbary,

    Could you share a simple demo which could reproduce your issue?

    And I suggest you could follow the tutorial to learn JWT,because JWT itself will authenticate the token.

    Reference:https://www.c-sharpcorner.com/article/jwt-json-web-token-authentication-in-asp-net-core/

    Best Regards,

    Rena

    Monday, September 16, 2019 9:13 AM