小编典典

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

angularjs

我想创建一个使用asp.net mvc webapi作为后端和客户端路由(没有cshtml)的SPA
angularjs应用程序中的身份验证和授权的示例。以下只是可用于设置完整示例的函数示例。但是我不能一概而论。任何帮助表示赞赏。

问题:

  1. 最佳实践是什么:基于Cookie或令牌?
  2. 如何创建有角度的承载令牌以对每个请求进行授权?
  3. 验证API函数?
  4. 如何在客户端上保留登录的登录用户?

示例代码:

  1. 登录表格
        <form name="form" novalidate>
     <input type="text" ng-model="user.userName" />
     <input type="password" ng-model="user.password" />
     <input type="submit" value="Sign In" data-ng-click="signin(user)">
    </form>
  1. 身份验证角度控制器
        $scope.signin = function (user) {
    $http.post(uri + 'account/signin', user)
        .success(function (data, status, headers, config) {
            user.authenticated = true;
            $rootScope.user = user;
            $location.path('/');
        })
        .error(function (data, status, headers, config) {

            alert(JSON.stringify(data));
            user.authenticated = false;
            $rootScope.user = {};
        });
    };
  1. 我的API后端API代码。
        [HttpPost]
    public HttpResponseMessage SignIn(UserDataModel user)
    {
        //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?
        if (this.ModelState.IsValid)
        {
            if (true) //perform authentication against db etc.
            {
                var response = this.Request.CreateResponse(HttpStatusCode.Created, true);
                FormsAuthentication.SetAuthCookie(user.UserName, false);

                return response;
            }

            return this.Request.CreateErrorResponse(HttpStatusCode.Forbidden, "Invalid username or password");
        }
        return this.Request.CreateErrorResponse(HttpStatusCode.BadRequest, this.ModelState);
    }
  1. 授权使用JWT库限制内容。
        config.MessageHandlers.Add(new JsonWebTokenValidationHandler
    {
      Audience = "123",
      SymmetricKey = "456"
    });
  1. 我的API方法
        [Authorize]
    public IEnumerable<string> Get()
    {
     return new string[] { "value1", "value2" };
    }

阅读 309

收藏
2020-07-04

共1个答案

小编典典

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

不幸的是,我无法用ASP.NET帮助您,但是通常JWT库会为您生成并验证令牌。您所要做的就是在每个请求中随调用generateencode在凭据(和机密)上verifydecode在令牌上。而且,您不需要在服务器上存储任何状态,也不需要发送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!

2020-07-04