AngularJS客户方路由和令牌认证用的WebAPI [英] AngularJS clientside routing and token authentication with webapi

查看:156
本文介绍了AngularJS客户方路由和令牌认证用的WebAPI的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我要为在SPA验证和授权创建一个示例angularjs使用asp.net MVC的WebAPI作为后端和客户端的路由(无CSHTML)应用程序。下面是可以用来建立完整的例子只是功能为例。但我只是不容把它所有togehter。任何帮助AP preciated。

问题:


  1. 什么是最好的做法:基于Cookie或令牌

  2. 如何创建角承载令牌授权对每个请求?

  3. 在API函数验证?

  4. 如何preserve在客户端上登录的用户的autentication?

举例code:


  1. 登录表单

     <表格名称=形式的novalidate>
     <输入类型=文本NG模型=user.userName/>
     <输入类型=密码NG模型=user.password的/>
     <输入类型=提交值=登录数据-NG-点击=登入(用户)>
    < /表及GT;


  2. 认证角控制器

      $ scope.signin =功能(用户){
    $ http.post(URI +帐号/登入',用户)
        .success(功能(数据,状态,头,配置){
            user.authenticated = TRUE;
            $ rootScope.user =用户;
            $ location.path('/');
        })
        .error(功能(数据,状态,头,配置){        警报(JSON.stringify(数据));
            user.authenticated = FALSE;
            $ rootScope.user = {};
        });
    };


  3. 我的API后端API code。

      [HttpPost]
    公众的Htt presponseMessage签到(UserDataModel用户)
    {
        // FormsAuthetication仅仅是一个例子。我可以使用OWIN上下文来创建一个会话,饼干或者我应该只是对每个请求使用令牌认证?我如何preserve在客户端上登录的用户的autentication?
        如果(this.ModelState.IsValid)
        {
            如果(真)//执行对DB等认证
            {
                VAR响应= this.Request.CreateResponse(的HTTPStatus code.Created,真正的);
                FormsAuthentication.SetAuthCookie(user.UserName,FALSE);            返回响应;
            }        返回this.Request.CreateErrorResponse(的HTTPStatus code.Forbidden,无效的用户名或密码);
        }
        返回this.Request.CreateErrorResponse(的HTTPStatus code.BadRequest,this.ModelState);
    }


  4. 授权
    使用JWT库限制的内容。

      config.MessageHandlers.Add(新JsonWebTokenValidationHandler
    {
      观众=123
      SymmetricKey =456
    });


  5. 我的API方法

      [授权]
    公共IEnumerable的<串GT;得到()
    {
     返回新的字符串[] {值1,值2};
    }



解决方案

是否使用cookie认证或(承载)令牌还是取决于你的应用程序的类型。而据我所知,目前还没有任何的最佳做法呢。但是,由于您正在使用的水疗中心,并已经使用了智威汤逊图书馆,我赞成令牌为基础的方法。

不幸的是,我不能帮你ASP.NET,但通常JWT库生成和验证令牌给你。所有你所要做的就是调用生成连接code 上的凭据(和秘密)和验证德code 与每个请求发送的令牌。而你并不需要存储在服务器上的任何国家,也不需要发送一个cookie,你可能与 FormsAuthentication.SetAuthCookie(user.UserName,FALSE)。

我敢肯定你的库提供有关如何使用生成/ EN code,并确认/取消code标记的例子。

于是生成和验证是不是你在客户端做一些事情。

流程是这样的:


  1. 客户端发送用户提供登录凭据到服务器。

  2. 服务器进行身份验证凭证,并用生成的令牌进行响应。

  3. 客户端存储令牌地方(本地存储,Cookie或只是内存)。

  4. 客户端发送的令牌在每次请求到服务器的授权头。

  5. 服务器验证令牌和发送任何请求的资源,或401(或东西一样)采取相应的行动。

步骤1和3:

  app.controller('UserController的',函数($ HTTP,$窗口,$位置){
    $ scope.signin =功能(用户){
    $ http.post(URI +帐号/登入',用户)
        .success(功能(数据){
            //直到用户关闭浏览器窗口存储该令牌。
            $ window.sessionStorage.setItem('令牌',data.token);
            $ location.path('/');
        })
        .error(函数(){
            $ window.sessionStorage.removeItem('令牌');
            // TODO:显示类似用户名或密码无效。
        });
    };
});

的sessionStorage 只要用户拥有的页面打开保存的数据。如果你想自己处理的过期时间,你可以使用的localStorage 来代替。接口是相同的。

第四步:

要发送令牌在每次请求到服务器,你可以用什么角度调用一个拦截器。所有您需要做的就是让pviously存储令牌$ P $(如果有的话),并将它作为一个头到所有传出请求:

  app.factory('AuthInterceptor',函数($窗口,$ Q){
    返回{
        要求:功能(配置){
            config.headers = config.headers || {};
            如果($ window.sessionStorage.getItem('令牌')){
                config.headers.Authorization ='承载'+ $ window.sessionStorage.getItem('令牌');
            }
            返回配置|| $ q.when(配置);
        },
        回应:功能(响应){
            如果(response.status === 401){
                // TODO:重定向用户到登录页面。
            }
            返回响应|| $ q.when(响应);
        }
    };
});//注册pviously创建AuthInterceptor的$ P $。
的app.config(函数($ httpProvider){
    $ httpProvider.interceptors.push('AuthInterceptor');
});

并确保始终使用SSL!

I want to create an example for authentication and authorization in an SPA angularjs application using asp.net mvc webapi as the backend and client side routing (no cshtml). Below is just example of functions that can be used to set up the complete example. But I just can´t put it all togehter. Any help appreciated.

Questions:

  1. What is best practise: Cookie or Token based?
  2. How do I create the bearer token in angular to authorize on each request?
  3. Validation on API functions?
  4. How do I preserve the autentication signed in user on the client?

Example code:

  1. Sign in form

    <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>
    

  2. Authentication Angular Controller

    $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 = {};
        });
    };
    

  3. My API backend API Code.

    [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);
    }
    

  4. Authorization Using the JWT library for restricting content.

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

  5. My API methods

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

解决方案

Whether to use cookie authentication or (bearer) tokens still depends on the type of app you have. And as far as I know there aren't any best practice yet. But since you are working on a SPA, and are already using a JWT library, I would favor the token based approach.

Unfortunately, I cannot help you with ASP.NET, but usually JWT libraries generate and verify the token for you. All you have to do is call generate or encode on the credentials (and the secret) and verify or decode on the token sent with every request. And you don't need to store any state on the server and don't need to send a cookie, what you probably did with FormsAuthentication.SetAuthCookie(user.UserName, false).

I'm sure your library provides an example on how to use generate/encode and verify/decode tokens.

So generating and verifying is not something you do on the client side.

The flow goes something like this:

  1. Client sends the user provided login credentials to the server.
  2. Server authenticates credentials and responds with a generated token.
  3. Client stores the token somewhere (local storage, cookies, or just in memory).
  4. Client sends the token as an authorization header on every request to the server.
  5. Server verifies the token and acts accordingly with either sending the requested resource, or an 401 (or something alike).

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 keeps the data as long as the user has the page open. In case you want to handle expiration times yourself, you could use localStorage instead. The interface is the same.

Step 4:

To send the token on every request to the server, you can use what Angular calls an Interceptor. All you have to do is get the previously stored token (if any) and attach it as a header to all outgoing requests:

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!

这篇关于AngularJS客户方路由和令牌认证用的WebAPI的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆