栏目分类:
子分类:
返回
名师互学网用户登录
快速导航关闭
当前搜索
当前分类
子分类
实用工具
热门搜索
名师互学网 > IT > 面试经验 > 面试问答

使用webapi的AngularJS客户端路由和令牌认证

面试问答 更新时间: 发布时间: IT归档 最新发布 模块sitemap 名妆网 法律咨询 聚返吧 英语巴士网 伯小乐 网商动力

使用webapi的AngularJS客户端路由和令牌认证

是否使用cookie身份验证或(承载)令牌仍然取决于您拥有的应用程序类型。据我所知,还没有任何最佳实践。但是由于您正在使用SPA,并且已经在使用JWT库,所以我倾向于基于令牌的方法。

不幸的是,我无法用ASP.NET帮助您,但是通常JWT库会为您生成并验证令牌。您所要做的就是在每个请求中随调用

generate
enpre
在凭据(和机密)上
verify
depre
在令牌上。而且,您不需要在服务器上存储任何状态,也不需要发送cookie(可能就是这样做的)
FormsAuthentication.SetAuthcookie(user.UserName,false)

我确定您的图书馆提供了有关如何使用生成/编码和验证/解码令牌的示例。

因此,生成和验证不是您在客户端执行的操作。

流程如下所示:

  1. 客户端将用户提供的登录凭据发送到服务器。
  2. 服务器对凭据进行身份验证,并使用生成的令牌进行响应。
  3. 客户端将令牌存储在某处(本地存储,cookie或仅在内存中)。
  4. 客户端将令牌作为每个请求的授权标头发送到服务器。
  5. 服务器验证令牌,并通过发送请求的资源或401(或类似方式)进行相应的操作。

步骤1和3:

    app.controller('UserController', function ($http, $window, $location) {        $scope.signin = function(user) {        $http.post(uri + 'account/signin', user) .success(function (data) {     // Stores the token until the user closes the browser window.     $window.sessionStorage.setItem('token', data.token);     $location.path('/'); }) .error(function () {     $window.sessionStorage.removeItem('token');     // TODO: Show something like "Username or password invalid." });        };    });

sessionStorage
只要用户打开页面就保留数据。如果您想自己处理到期时间,可以
localStorage
改用。接口是一样的。

第4步:

要将每个请求上的令牌发送到服务器,您可以使用Angular所谓的Interceptor。您要做的就是获取先前存储的令牌(如果有)并将其作为标头附加到所有传出请求中:

    app.factory('AuthInterceptor', function ($window, $q) {        return { request: function(config) {     config.headers = config.headers || {};     if ($window.sessionStorage.getItem('token')) {         config.headers.Authorization = 'Bearer ' + $window.sessionStorage.getItem('token');     }     return config || $q.when(config); }, response: function(response) {     if (response.status === 401) {         // TODO: Redirect user to login page.     }     return response || $q.when(response); }        };    });    // Register the previously created AuthInterceptor.    app.config(function ($httpProvider) {        $httpProvider.interceptors.push('AuthInterceptor');    });

并确保始终使用SSL!



转载请注明:文章转载自 www.mshxw.com
本文地址:https://www.mshxw.com/it/633189.html
我们一直用心在做
关于我们 文章归档 网站地图 联系我们

版权所有 (c)2021-2022 MSHXW.COM

ICP备案号:晋ICP备2021003244-6号