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

Cla*_*ger 32 authentication authorization asp.net-web-api 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>
    
    Run Code Online (Sandbox Code Playgroud)
  2. 身份验证角度控制器

    $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 = {};
        });
    };
    
    Run Code Online (Sandbox Code Playgroud)
  3. 我的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);
    }
    
    Run Code Online (Sandbox Code Playgroud)
  4. 授权使用JWT库来限制内容.

    config.MessageHandlers.Add(new JsonWebTokenValidationHandler
    {
      Audience = "123",
      SymmetricKey = "456"
    });
    
    Run Code Online (Sandbox Code Playgroud)
  5. 我的API方法

    [Authorize]
    public IEnumerable<string> Get()
    {
     return new string[] { "value1", "value2" };
    }
    
    Run Code Online (Sandbox Code Playgroud)

ber*_*rdw 91

是否使用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."
        });
    };
});
Run Code Online (Sandbox Code Playgroud)

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');
});
Run Code Online (Sandbox Code Playgroud)

并确保始终使用SSL!