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

前端之家收集整理的这篇文章主要介绍了使用webapi的AngularJS客户端路由和令牌认证前端之家小编觉得挺不错的,现在分享给大家,也给大家做个参考。
我想在SPA angularjs应用程序中使用asp.net mvc webapi作为后端和客户端路由(无cshtml)创建身份验证和授权的示例。下面是可用于设置完整示例的函数的示例。但我不能把它全部。任何帮助赞赏。

问题:

>什么是最佳实践:Cookie或令牌?
>如何在角度创建承载令牌以授权每个请求?
> API函数验证?
>如何保留在客户端上签名的用户中的自动签名?

示例代码

>登录表单

  1. <form name="form" novalidate>
  2. <input type="text" ng-model="user.userName" />
  3. <input type="password" ng-model="user.password" />
  4. <input type="submit" value="Sign In" data-ng-click="signin(user)">
  5. </form>

>认证角控制器

  1. $scope.signin = function (user) {
  2. $http.post(uri + 'account/signin',user)
  3. .success(function (data,status,headers,config) {
  4. user.authenticated = true;
  5. $rootScope.user = user;
  6. $location.path('/');
  7. })
  8. .error(function (data,config) {
  9.  
  10. alert(JSON.stringify(data));
  11. user.authenticated = false;
  12. $rootScope.user = {};
  13. });
  14. };

>我的API后端API代码

  1. [HttpPost]
  2. public HttpResponseMessage SignIn(UserDataModel user)
  3. {
  4. //FormsAuthetication is just an example. Can I use OWIN Context to create a session and cookies or should I just use tokens for authentication on each request? How do I preserve the autentication signed in user on the client?
  5. if (this.ModelState.IsValid)
  6. {
  7. if (true) //perform authentication against db etc.
  8. {
  9. var response = this.Request.CreateResponse(HttpStatusCode.Created,true);
  10. FormsAuthentication.SetAuthCookie(user.UserName,false);
  11.  
  12. return response;
  13. }
  14.  
  15. return this.Request.CreateErrorResponse(HttpStatusCode.Forbidden,"Invalid username or password");
  16. }
  17. return this.Request.CreateErrorResponse(HttpStatusCode.BadRequest,this.ModelState);
  18. }

>授权
使用JWT库来限制内容

  1. config.MessageHandlers.Add(new JsonWebTokenValidationHandler
  2. {
  3. Audience = "123",SymmetricKey = "456"
  4. });

>我的API方法

  1. [Authorize]
  2. public IEnumerable<string> Get()
  3. {
  4. return new string[] { "value1","value2" };
  5. }
是否使用cookie身份验证或(承载)令牌仍取决于您具有的应用程序类型。据我所知,还没有任何最佳做法。但是,由于你正在使用SPA,并且已经使用JWT库,我赞成基于令牌的方法

不幸的是,我不能帮助你的ASP.NET,但通常JWT库生成和验证的令牌为你。所有你需要做的是对证书(和秘密)调用generate或encode,并对每个请求发送的令牌进行验证或解码。并且你不需要在服务器上存储任何状态,并且不需要发送cookie,你可能使用FormsAuthentication.SetAuthCookie(user.UserName,false)。

我相信你的库提供了一个例子,如何使用generate / encode和验证/解码令牌。

所以生成和验证不是你在客户端做的。

流程如下:

>客户端将用户提供的登录凭据发送到服务器。
>服务器验证凭据并使用生成的令牌进行响应。
>客户端将令牌存储在某个地方(本地存储,cookie,或只是在内存中)。
>客户端将令牌作为每个请求的授权头发送到服务器。
>服务器验证令牌并相应地发送请求的资源或401(或类似的东西)。

步骤1和3:

  1. app.controller('UserController',function ($http,$window,$location) {
  2. $scope.signin = function(user) {
  3. $http.post(uri + 'account/signin',user)
  4. .success(function (data) {
  5. // Stores the token until the user closes the browser window.
  6. $window.sessionStorage.setItem('token',data.token);
  7. $location.path('/');
  8. })
  9. .error(function () {
  10. $window.sessionStorage.removeItem('token');
  11. // TODO: Show something like "Username or password invalid."
  12. });
  13. };
  14. });

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

步骤4:

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

  1. app.factory('AuthInterceptor',function ($window,$q) {
  2. return {
  3. request: function(config) {
  4. config.headers = config.headers || {};
  5. if ($window.sessionStorage.getItem('token')) {
  6. config.headers.Authorization = 'Bearer ' + $window.sessionStorage.getItem('token');
  7. }
  8. return config || $q.when(config);
  9. },response: function(response) {
  10. if (response.status === 401) {
  11. // TODO: Redirect user to login page.
  12. }
  13. return response || $q.when(response);
  14. }
  15. };
  16. });
  17.  
  18. // Register the prevIoUsly created AuthInterceptor.
  19. app.config(function ($httpProvider) {
  20. $httpProvider.interceptors.push('AuthInterceptor');
  21. });

并确保始终使用SSL!

猜你在找的Angularjs相关文章