如何在 Visual Studio 单页应用程序模板中获取不记名令牌

How to get the bearer token in the Visual Studio Single Page Application template

我使用 Visual Studio 2013 和单页应用程序模板创建了一个网络应用程序。根据:

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

我的问题是 - 如何获得此令牌? /Token URL 似乎需要用户名和密码 - 我在索引页面上没有。我没有在 sessionStorage 之类的地方看到它。我假设我必须用我的一个 AspNet cookie 换取一个令牌 - 但似乎找不到任何如何这样做的例子。

如果有人能用线索棒打我,我将不胜感激

在 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

@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 请求