首页 文章

AngularJS客户端使用webapi进行路由和令牌身份验证

提问于
浏览
32

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

问题:

  • 什么是最佳实践:基于Cookie或令牌?

  • 如何在角度中创建持票人令牌以对每个请求进行授权?

  • 对API函数进行验证?

  • 如何在客户端保留用户签名的身份验证?

示例代码:

  • 登录表格
<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>
  • 认证角度控制器
$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 = {};
    });
};
  • 我的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);
}
  • 授权使用JWT库限制内容 .
config.MessageHandlers.Add(new JsonWebTokenValidationHandler
{
  Audience = "123",
  SymmetricKey = "456"
});
  • 我的API方法
[Authorize]
public IEnumerable<string> Get()
{
 return new string[] { "value1", "value2" };
}

1 回答

  • 91

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

    不幸的是,我无法帮助您使用ASP.NET,但通常JWT库会为您生成并验证令牌 . 您所要做的就是在凭证(和秘密)上调用 generateencode ,并在每个请求发送的令牌上调用 verifydecode . 你不需要发送一个cookie,你可能用 FormsAuthentication.SetAuthCookie(user.UserName, false) 做了什么 .

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

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

    流程如下:

    • 客户端将用户提供的登录凭据发送到服务器 .

    • 服务器验证凭据并使用生成的令牌进行响应 .

    • 客户端将令牌存储在某处(本地存储,cookie或仅存储在内存中) .

    • 客户端在每次向服务器发出请求时将令牌作为授权头发送 .

    • 服务器验证令牌,并通过发送请求的资源或401(或类似的东西)进行相应的操作 .

    Step 1 and 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 代替 . 界面是一样的 .

    Step 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');
    });
    

    And make sure to always use SSL!

相关问题