How to pass headers with @Url.Action() for jwt authorization

289 views Asked by At

I have a login page and on typing correct credentials ,user must be redirected to next page after login page(LandingPage).On clicking Submit button,user is not getting redirected to next page and showing 401 unauthorized error.Jwt token is successfully generated and saved but I am unable to redirect to next page as @url.Action("Land","LandingPage") does not pass header which is needed for authorization. (Technology:Dot net mvc,web api,Ajax)

Code for ajax call to redirect:-

$.ajax({
        url: "https://localhost:44374/api/Login",

                type: 'POST',
                data: JSON.stringify(data),
                dataType: "json",
                contentType: "application/json",
                //headers: { Authorization: $`Bearer ${localStorage.getItem("Bearer")}` },
                success: function (data) {
                    alert("Successfully Logged in");
                    console.log(data);
                    window.localStorage.setItem("Bearer", data.token);
                    window.location.href = "@Url.Action("Land", "LandingPage")"; //PROBLEM HERE
                },
                error: function (e) {
                    alert("Failed to authenticate !");
                }
            });
1

There are 1 answers

0
Michal Trojanowski On

You are using window.location.href in order to send the user to the landing page. This makes a browser redirect to that page, right? A browser sends cookies to your server, it will not send the Authorization header. If you're not using AJAX to get data from some APIs, in my opinion, it's better to use sessions and cookies to log in users. Use the JWT token only when you need to make an AJAX call to an API.