What is the process for verifying and authenticating a token's header?

Trying to incorporate token in the search functionality. The token is used to check the header for identification, ensuring that the request passes through all steps. If incorrect, the request is cancelled and returned.

Requested JSON

{ 
"header": { 
"Token": "558fedce-a84e-4a9a-8698-5cd27d5af3ed"
},
"body": { 
"WarehouseCode": "W001", 
"CompanyCode": "C001"
}
}

Index.cshtml

<div class="row">
    <div class="col-md-4">
        @using (Html.BeginForm("Index", "Home", FormMethod.Post))
        {
        @Html.TextArea("track") <input type="submit" value="Track"/>
        }
    </div>
</div>

Model.cs

   public class GetInvBalReq
    {
        public class GetData
        {
            public Header header { get; set; }
            public Body body { get; set; }
        }

        public class Header
        {
            public string Token { get; set; }
        }

        public class Body
        {
            public string WarehouseCode { get; set; }
            public string CompanyCode { get; set; }
        }
    }

HomeController.cs

This controller manages the search feature

   [System.Web.Mvc.HttpPost]
        public ActionResult Index(string track)
        {

            UploadToBCSSoftSCM b = new UploadToBCSSoftSCM();
                string response = b.GetInvBal(track);
                var data = JsonConvert.DeserializeObject<Rootobject>(response);

            return View(data);
        }

Answer №1

public class TokenValidationFilter: ActionFilterAttribute
{
    public override void OnActionExecuting(HttpActionContext actionContext)
    {
        //Retrieve token from request headers
        IEnumerable<string> tokens;
        if (!actionContext.Request.Headers.TryGetValues("Token", out tokens) || tokens.Count() > 1)
        {
         //If no token header is found in the request
        actionContext.Response = new HttpResponseMessage(HttpStatusCode.Unauthorized);
        }
        else
        {
        //Logic to validate the token goes here
        //Set response as unauthorized if token is invalid
        }
    }
}

Then apply the attribute on the method as follows:

[TokenValidationFilter]
public ActionResult Index(string track)
{

    UploadToBCSSoftSCM uploader = new UploadToBCSSoftSCM();
    string result = uploader.GetInvBal(track);
    var deserializedData = JsonConvert.DeserializeObject<Rootobject>(result);

    return View(deserializedData);
}

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

Guide on building a FastAPI endpoint that can handle both Form and JSON body in one request

Is it possible to design an endpoint in FastAPI that can handle both (multipart) Form data and JSON body? How can I make the endpoint recognize the type of data it is receiving? ...

Exploring data in C# using HtmlAgilityPack to extract information from a table

I've been working on a project for some time now, and here's the situation: A friend of mine has a web application that generates data for charts using HTML. I need to extract specific values from a table on his website so that we can store this ...

Changing an Array into JSON format using AngularJS

I am attempting to switch from a dropdown to a multiselect dropdown. <select name="molecularMethod" class="form-control" ng-model="request.molecularMethod" multiple> It is functioning properly. However, when items are selected, it generates an arra ...

The Vite manifest file could not be located in the designated path: C:xampphtdocslolaboutpublicuild/manifest.json

"Error: Vite manifest not found at: C:\xampp\htdocs\vrsweb\public\build/manifest.json" Please start the development server by running npm run dev in your terminal and refreshing the page." Whenever I attempt to acce ...

The .map() function seems to be missing some data when fetching from the database in a Node.js

I am currently tackling an exercise for a Bootcamp, and the function I am using is not yielding the desired outcome. The objective is to query the database with a first name or a part of a first name. While I can successfully execute the DB query and retri ...

Unexpected behavior observed with Gridview paging within ModalPopupExtender

Having an issue with my modal pop-up extender that displays a grid view. When I click a button, the grid is supposed to populate following this code: protected void btnViewRecipients_Click(object sender, EventArgs e) { ModalPopupExtender1.Show(); ...

GridPanel Store Failing to Load

Having trouble loading a simple GridPanel with a Store created in the code behind. I've double-checked everything, but when I add the Store to the GridPanel, it just displays "Loading..." indefinitely without actually loading anything. This is how th ...

Is there a recursive method to verify the folder name for each aggregate?

Consider the scenario with these sample documents: (parent_id: null denotes items located at root directory) {"_id":"a", "name":"Pictures", "parent_id": null, "type": "folder"} {"_ ...

pytrends_json.decoder.JSONDecodeError: Anticipating a value at line 1, column 1 (character 0)

When I execute this code, I encounter an error: from pytrends.request import TrendReq google_username = '' google_password = '' pytrend = TrendReq(google_username, google_password, custom_useragent='My Pytrends Script') pytre ...

A guide to updating a particular row and sending parameters with jQuery and AJAX

I am utilizing a JSON response to dynamically display table content. Here is the code I am using to display row values: var rows = ''; for(var i=0; i<response.response.length; i++) { rows += '<tr><td class="country">&ap ...

What are some strategies for managing two APIs in a single UIViewController?

I have a single ViewController containing an UIImage and two UITextFields, along with one UITableView. The data to populate these UI elements is fetched from an API. The first API provides the data for the UIImage and UITextFields, while the second API fe ...

Tips for accessing and modifying values within an array with the edit-json-file npm package

Looking to make changes to the user's name and value in JSON format: { "User": [ { "name": "John", "value": 1000000 } ] } ...

Error encountered when attempting to retrieve JSON data in JavaScript due to being undefined

A snippet of code that reads and writes JSON data is presented below: var info; $(function () { $.getJSON("data.json", function (d) { info = d; }); $('.btn').click(function () { info['c-type'] = $('#c- ...

Failed to retrieve the requested item using fetch, encountering a NetworkError

My API is being accessed to retrieve data using this code snippet. It sends the email and password to the API: onSubmitSignIn = () => { fetch('http://localhost:3001/signin', { method: 'post', headers: {'Content-Type&ap ...

App Engine serves up JSON data using JsonProperty

I appreciate how the JsonProperty in Python seamlessly encodes data into JSON when saving to the database and decodes it upon retrieval. However, I am seeking a solution to directly send raw JSON data to a web browser without the need for further encodin ...

Displaying data from a JSON file in a table view in Swift can be challenging, especially if the type `ANY` is used and does

I've noticed that there have been multiple inquiries similar to mine, but none of them seem to address my specific goal. In my local directory, I have a JSON file structured like an array as follows: "["countrycode1", "country1", "countrycode2", "cou ...

Utilizing jq for finding a parent element based on a specific child key/value pair

How can I use jq to select a parent object that contains a child object meeting two filter requirements? For instance, I want to choose all Subnets elements with a child tag having key "Name" and value "TheName". There are two subnets in my example - one ...

exit the application immediately

Whenever I attempt to log in by clicking the login button on my application, it unexpectedly crashes. Can anyone help me understand why this is happening and provide a solution? Below is the code for my Login_Menu activity: package com.campuspro.start; ...

Converting JSON information into a structured database table

Seeking assistance with preprocessing a JSON file generated by YouTube's iframe API. The goal is to transform this JSON data into a pandas dataframe format, where each key from the JSON becomes a separate column and every recorded "event" translates t ...

Issues with login validation in HTML when utilizing JSON and PHP

While creating a login form in HTML using JSON and PHP, I encountered an issue where the if statements in the success function were not working properly. However, the beforeSend and error functions are functioning as expected. Can someone assist me in iden ...