问题:
>什么是最佳实践: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,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" }; }