How to pass bearer token into request header

Viewed 350

It's my first time building a web api. I've successfully set up the model view controller and enabled token generation. However, I am stuck on how to pass the access token through the request header. After I have logged in and attempt to view another page, there is nothing in the header in regards to the authorization therefore I receive a 401 error. I've looked at several blogs, forums and articles over the past couple days and cannot come to a conclusion on how this is done. I have my jquery storing the header in a variable, but I am unsure on where that is stored and how to reference it or where to put the reference. I've messed around with setting it in global.asax and some of the config files, also at the top of the controller class. My next thought is to create a web page for each controller and storing the authorization there, even still I don't know how to dynamically place a token that would vary for other users. I feel like there is something very simple that I'm missing. I suppose my question is how do I store my javascript variable in each request header? Here is my javascript for reference:

$("#btnLogin").on('click', function () {
        //var data = { Email: $("#loginEmail").val().trim(), Password: $("#textPwd").val().trim(), ConfirmPassword: $("#loginPwd").val().trim() };
        $.ajax(
            {
                url: "/TOKEN",
                type: "POST",
                data: $.param({ grant_type: 'password', username: $("#loginEmail").val(), password: $("#loginPwd").val() }),
                headers: { 'Content-Type': 'application/x-www-form-urlencoded' },
                success: function (resp) {
                    sessionStorage.setItem('userName', resp.userName);
                    sessionStorage.setItem('accessToken', resp.access_token);
                    var authHeaders = {};
                    authHeaders.Authorization = 'Bearer ' + resp.access_token;
                    $.ajax({
                        url: "https://localhost:44327/api/values",
                        type: "GET",
                        headers: authHeaders,
                        success: function (response) {
                            $("#loginEmail").val(),
                            $("#loginPwd").val(),
                            $("#msg").text(response)
                        }
                    });

                },
                error: function () {
                    $("#msg").text("Authentication failed");
                }
            })

    });
0 Answers
Related