Combine the use of authentication both for MVC pages and for Web API pages?

后端 未结 5 1505
面向向阳花
面向向阳花 2020-12-12 21:52

I have an MVC 5 web application and can login with a Login.cshtml page and get a cookie and the login works fine. But, I would like to do a login with the Web API and then (

5条回答
  •  旧时难觅i
    2020-12-12 22:18

    Ugg... what I had to do was use the Login.cshtml form and override the submit... make an Ajax call to get the WebApi bearer token... and then do the form submit to get the actual MVC cookie. So, I'm actually making two login requests... one for the WebApi token and the other for the MVC cookie.

    Seem pretty hacky to me... it would be nice if there was some way to sign in to MVC using the bearer token... or a call to the WebApi that would return me a cookie that I can use for normal MVC page requests.

    If anyone has a better way I would love to hear it.

    This is script code that I added to Login.cshtml:

        $(document).ready(function () {
            $('form:first').submit(function (e) {
                e.preventDefault();
                var $form = $(this);
                var formData = $form.serializeObject(); // https://github.com/macek/jquery-serialize-object
                formData.grant_type = "password";
                $.ajax({
                    type: "POST",
                    url: '@Url.Content("~/Token")',
                    dataType: "json",
                    data: formData, // seems like the data must be in json format
                    success: function (data) {
                        sessionStorage.setItem('token', data.access_token);
                        $form.get(0).submit(); // do the actual page post now
                    },
                    error: function (textStatus, errorThrown) {
                    }
                });
            });
        });
    

提交回复
热议问题