使用webapi的AngularJS客户端路由和令牌认证
|
我想在SPA angularjs应用程序中使用asp.net mvc webapi作为后端和客户端路由(无cshtml)创建身份验证和授权的示例。下面是可用于设置完整示例的函数的示例。但我不能把它全部。任何帮助赞赏。
问题: >什么是最佳实践:Cookie或令牌? 示例代码: >登录表单 <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);
}
>授权 config.MessageHandlers.Add(new JsonWebTokenValidationHandler
{
Audience = "123",SymmetricKey = "456"
});
>我的API方法 [Authorize]
public IEnumerable<string> Get()
{
return new string[] { "value1","value2" };
}
是否使用cookie身份验证或(承载)令牌仍取决于您具有的应用程序类型。据我所知,还没有任何最佳做法。但是,由于你正在使用SPA,并且已经使用JWT库,我赞成基于令牌的方法。
不幸的是,我不能帮助你的ASP.NET,但通常JWT库生成和验证的令牌为你。所有你需要做的是对证书(和秘密)调用generate或encode,并对每个请求发送的令牌进行验证或解码。并且你不需要在服务器上存储任何状态,并且不需要发送cookie,你可能使用FormsAuthentication.SetAuthCookie(user.UserName,false)。 我相信你的库提供了一个例子,如何使用generate / encode和验证/解码令牌。 所以生成和验证不是你在客户端做的。 流程如下: >客户端将用户提供的登录凭据发送到服务器。 步骤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! (编辑:李大同) 【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容! |
