简体   繁体   中英

MVC4 Razor. How to pass a javascript variable to server?

I have a javascript variable that I want to pass back to the server side, which I thereafter intend to use it as an access token to grant user access to other pages which requires this token.

I wonder how do I pass this javascript variable back to server, so I can set it to a session variable? Do I need to send it back using ajax?

this is the part of jQuery I use to retrieve the token from server

$(document).ready(function () {
        $('#loginForm').submit(function(e) {
            var blargh = $(this).find('input').serialize();

            $.ajax({
                type: 'post',
                url: '/WebAPI/api/authenticate/login',
               data: blargh,
                success: function (data) {
                    $.each(data, function(index, token) {
                        $('#container').prepend('<input type="hidden" name="MY_HIDDEN_FIELD_NAME" id="MY_HIDDEN_FIELD_NAME" value="'+token+'">');
                    });
                },
                error: function(jqXHR, status, errorThrown) {
                    alert("Error " + status + "\nError Thrown" + errorThrown )
                },
            });
            e.preventDefault();

        });

    });

Couldn't you pass it back as either a hidden form element or pass it back in the query string of a ajax postback?

Example of a hook to get the post back value in global.asmx

protected void Session_Start(object src, EventArgs e)
    {
        if(!string.IsNullOrEmpty(Request.Form["MY_HIDDEN_FIELD_NAME"]))
        {
            Session["MY_SESSION_NAME"] = Request.Form["MY_HIDDEN_FIELD_NAME"]
        }
    }

I would recommend sending you the acess token in request headers when u are sending a ajax request

xhr.setRequestHeader('custom-header', 'value');

and on the server side you can fetch the request header

First - why is your client generating the token (I hope I've understood you correctly there)? The server should generate the token and the client must then be responsible for maintaining it.

If it's an API token that'll only ever be used in the browser from javascript, then I recommend using an authentication cookie - all browsers know how to handle them and you can also easily expire them server-side if you no longer want to allow a particular token to have access (that's quite an important point). Also I strongly recommend against relying on server-side session to maintain the authentication session.

Authentication tokens should ideally be stateless (just like in Forms Authentication's cookie) - the burden of proof is on the client to send you a correct token, with that token containing the information you need to re-initialise the current requests state with the correct user.

If, however, it's a general purpose API for any type of client then you should allow the client to send the token to you in the query string of all requests at a very minimum. You should also support taking it in the request header as well - clients that can easily support setting request headers often prefer to because it then hides the auth token from the URL and makes formatting requests easier (there's also the potential to max out a web server's query string limit if the token is big enough).

I then recommend you look, at a minimum, at overriding MVCs AuthorizeAttribute (there are 2 - one for the 'standard' MVC 4 pipeline and one for the new Web API pipeline, & they would both need to be done if you are using both technologies. The link is for the MVC 4 one) to crack out your cookie/header/query string value. In there you can get the value, decrypt the token, identify the user and set the roles. The core code of that attribute then contains the logic for denying a request based on whether the user is authenticated/has a certain role/is a certain user.

To pass back an additional item in the AJAX POST, you could add it like this...

var blargh = $(this).find('input').serialize();
blargh.someItem = "value";

Bear in mind that this only works when the form is submitted using AJAX, so not where JavaScript isn't available or is disabled.

All the normal security disclaimers apply!

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM