如何在Visual Studio单页应用程序模板中获取持有者令牌

时间:2015-02-11 18:17:53

标签: asp.net-mvc authentication

我使用Visual Studio 2013和单页应用程序模板创建了一个Web应用程序。按照:

visual studio screen shot

我已经创建了自己的Controller并将[Authorize]属性添加到了该类中。控制器现在变为401 - 这是预期的,因为我在客户端没有做任何事情来传递授权承载令牌。

我的问题是 - 如何获得此令牌? / Token URL似乎需要用户名和密码 - 我在索引页面上没有。我在sessionStorage等中看不到它。我认为我必须交换我的一个AspNet cookie作为代币 - 但似乎无法找到任何如何做的例子。

如果有人能用线索棒打我,我将非常感激。

2 个答案:

答案 0 :(得分:1)

在SPA模板中,如果查看Scripts / app / home.viewmodel.js,您可以看到如何获取持票人令牌。

具体来说,它是从app.dataModel.getAccessToken()

获取令牌
   $.ajax({
            method: 'get',
            url: app.dataModel.userInfoUrl,
            contentType: "application/json; charset=utf-8",
            headers: {
                'Authorization': 'Bearer ' + app.dataModel.getAccessToken()
            },
            success: function (data) {
                self.myHometown('Your Hometown is : ' + data.hometown);
            }
        });

当用户登录时设置访问令牌。正如您猜测的那样,令牌存储在sessionStorage中:

function AppDataModel() {
var self = this;
// Routes
self.userInfoUrl = "/api/Me";
self.siteUrl = "/";

// Route operations

// Other private operations

// Operations

// Data
self.returnUrl = self.siteUrl;

// Data access operations
self.setAccessToken = function (accessToken) {
    sessionStorage.setItem("accessToken", accessToken);
};

self.getAccessToken = function () {
    return sessionStorage.getItem("accessToken");
};
}

如果您想了解更多有关其工作原理的信息,请查看本教程:

http://www.asp.net/web-api/overview/security/individual-accounts-in-web-api

答案 1 :(得分:0)

@using System.Web.Mvc
@model EmployeePortal.Web.Models.LoginModel
@{
    ViewBag.Title = "Login";
    Layout = "~/Views/Shared/_Layout.cshtml";
}

<h2>Login</h2>

@using (Html.BeginForm("Login", "Account", FormMethod.Post, new { @Id = "loginForm" }))
{
    @Html.Hidden("grant_type", "password")
    @Html.Label("Username")
    @Html.EditorFor(model => model.Username, new { @Name = "username", @Id = "username" })
    @Html.Label("Password")
    @Html.EditorFor(model => model.Password, new { @Name = "username", @Id = "password" })

    <input type="submit" value="Submit" id="submitForm"/>
}

<script type="text/javascript">
    $(document).ready(function ($) {

     function loginUser(token, expiresInSeconds) {
            var expireyDateTime = new Date();
            expireyDateTime.setSeconds(expiresInSeconds);
            $.cookie('bearerToken', token, { expires: expireyDateTime, path: '/' });
        alert('logged in');
     }

        $("#submitForm").click(function (e) {
            e.preventDefault();

            var loginForm = $('#loginForm').serialize();

            $.ajax({
                type: 'POST',
                cache: false,
                contentType: 'application/x-www-form-urlencoded',
                url: 'http://localhost:54435/token',
                data: loginForm
            }).success(function (data) {
                loginUser(data.access_token, data.expires_in);
            }).error(function (data) {
                alert('login failed');
            });
        });
    });

</script>

通过上面的示例,我刚刚调用了令牌终点,然后一旦验证并且调用的ajax成功将其添加到指定超时的cookie中。

此示例使用https://github.com/carhartl/jquery-cookie存储Cookie。

我推荐的工具名为PostMan,它是Chrome的插件,可让您为API构建Post / Get / Put请求。