当前位置:
首页 > 高等教育 > 工学 > Angularjs通过aspnetwebapi认证登录.docx
Angularjs通过aspnetwebapi认证登录.docx
- 文档编号:8121403
- 上传时间:2023-01-28
- 格式:DOCX
- 页数:18
- 大小:106.41KB
Angularjs通过aspnetwebapi认证登录.docx
《Angularjs通过aspnetwebapi认证登录.docx》由会员分享,可在线阅读,更多相关《Angularjs通过aspnetwebapi认证登录.docx(18页珍藏版)》请在冰豆网上搜索。
![Angularjs通过aspnetwebapi认证登录.docx](https://file1.bdocx.com/fileroot1/2023-1/28/eab9ffbe-992f-4140-b530-8ae3341d1913/eab9ffbe-992f-4140-b530-8ae3341d19131.gif)
Angularjs通过aspnetwebapi认证登录
Angularjs通过webapi认证登录
Angularjs利用mvc提供的identity,membership实现居于数据库的用户名/密码的认证登录
环境
V2013
Amvc+webapi
Individualuseraccounts
Angularjs
Underscore
新建一个mvc+webapiproject
注册一个test用户用于测试
新建一个用于登录验证用户名密码的webapicontroller代码如下
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
public class LoginController:
ApiController
{
[HttpGet]
publicstringGet()
{
AuthenticationManager.SignOut();
return "Success";
}
private IAuthenticationManagerAuthenticationManager
{
get
{
return HttpContext.Current.GetOwinContext().Authentication;
}
}
UserManagerUserManager= new UserManager(new UserStore(new ApplicationDbContext()));
[HttpPost]
publicHttpResponseMessagePostLogin(LoginViewModelmodel)
{
var user=UserManager.Find(model.UserName,model.Password);
if (user!
= null)
{
var identity=UserManager.CreateIdentity(user,DefaultAuthenticationTypes.ApplicationCookie);
AuthenticationManager.SignIn(new AuthenticationProperties(){IsPersistent= false },identity);
//FormsAuthentication.SetAuthCookie(model.UserName,false);
return Request.CreateResponse(HttpStatusCode.OK, "S");
}
else
{
return Request.CreateErrorResponse(HttpStatusCode.NotFound, "Invalidusernameorpassword.");
}
}
}
新建Index.html网页
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
DOCTYPE html>
//www.w3.org/1999/xhtml"ng-app="app">
登录Login.html子页面
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
RememberMe
{{message}}
-->
Home.html登录进去的首页
认证流程
angularjs代码
var app =angular.module("app",['ngRoute']);
app.config(function($routeProvider) {
$routeProvider.when('/login', {
templateUrl:
'templates/login.html',
controller:
'LoginController'
});
$routeProvider.when('/home', {
templateUrl:
'templates/home.html',
controller:
'HomeController'
});
$routeProvider.otherwise({redirectTo:
'/login'});
});
定义route,默认显示login登录界面
app.factory("SessionService", function () {
return {
get:
function (key) {
return sessionStorage.getItem(key);
},
set:
function (key, val) {
return sessionStorage.setItem(key, val);
},
unset:
function (key) {
return sessionStorage.removeItem(key);
}
}
});
保存登录session,
app.factory("AuthenticationService", function ($http, $location, SessionService, MessageService) {
var cacheSession = function () {
SessionService.set('authenicated',true);
};
var uncacheSession = function () {
SessionService.unset('authenicated');
};
var loginError = function (response) {
MessageService.show(response.Message);
};
return {
login:
function (credentials) {
//if(credentials.UserName!
=="admin"||
//credentials.Password!
=="admin"){
//alert("Usernamemustbe'admin/admin'");
//}
//else{
//$location.path('/home');
//}
//return$http.post("/api/Login",credentials)
var login = $http.post("/api/Login", credentials);
login.success(cacheSession);
login.success(MessageService.clean);
login.error(loginError);
return login;
},
logout:
function(){
//$location.path('/login');
//return$http.get("/api/Login");
var logout = $http.get("/api/Login");
logout.success(uncacheSession);
return logout;
},
isLoggedIn:
function () {
return SessionService.get('authenicated');
}
};
});
与后台webapi交互认证用户名/密码服务
app.controller("LoginController", function ($scope, $location,$http, AuthenticationService) {
$scope.credentials = { UserName:
"", Password:
"", RememberMe:
false};
$scope.login = function () {
AuthenticationService.login($scope.credentials).success(function () {
$location.path("/home");
});
}
});
Login方法登录成功重定向home页面
为了防止用户直接在地址栏输入/home跳过登录界面
app.run(function ($rootScope, $location, AuthenticationService, MessageService) {
var routesThatRequireAuth = ['/home'];
$rootScope.$on('$routeChangeStart', function (event,next,current) {
if(_(routesThatRequireAuth).contains($location.path()) &&
!
AuthenticationService.isLoggedIn()) {
MessageService.show("Pleaselogin");
$location.path('/login');
}
});
});
必须登录过才能访问/home页面
Homecontroller代码
app.controller("HomeController", function ($scope, $location, $http, AuthenticationService) {
$scope.credentials = { UserName:
"", Password:
"", RememberMe:
false };
$scope.logout = function () {
AuthenticationService.logout().success(function () {
$location.path("/login");
});
};
$scope.getvalue = function () {
var url = "/api/values";
$http.get(url).success(function (data) {
console.log(data);
})
.error(function (data) {
console.log(data);
});
};
//$scope.getvalue();
$scope.expiry = function () {
var url = "/api/values";
$http.post(url).success(function (data) {
console.log(data);
})
.error(function (data) {
console.log(data);
});
};
//$scope.expiry();
});
ValuesControllerAuthroize属性,必须认证通过才能访问
[Authorize]
public class ValuesController :
ApiController
{
//GETapi/
//[Authorize]
public IEnumerable Get()
{
return new string[]{ "value1", "value2" };
}
Homecontroller中可以logout登出,和getvalue获取需要认证的webapi。
如果用户长时间在home页面服务器端session过期后在调用getvalue方法会访问401错误。
这是如果捕获到401错误,那么就要重定向到/login页面
下面的代码就是用捕获401错误
app.config(function ($httpProvider) {
var LogOutUserOn401 = function ($location, $q, SessionService, MessageService) {
var success = function (response) {
//alert("success"+response.status);
return response;
};
var error = function (response) {
//alert("error:
"+response.status);
if (response.status === 401) {
SessionService.unset('authenicated');
MessageService.show(response.Message);
$location.path('/login');
return $q.reject(response);
} else {
return $q.reject(response);
}
};
return function (promise) {
return promise.then(success, error);
};
};
$httpProvider.responseInterceptors.push(LogOutUserOn401);
});
注意:
默认情况下mvc如果认证过期返回的302重定向到mvc提供的登录界面而不是返回401错误代码,就需要修改Startup.Auth.cs
public void ConfigureAuth(IAppBuilder app)
{
//Enabletheapplicationtouseacookietostoreinformationforthesignedinuser
//app.UseCookieAuthentication(newCookieAuthenticationOptions
//{
//AuthenticationType=DefaultAuthenticationTypes.ApplicationCookie,
//LoginPath=newPathString("/Account/Login")
//});
app.UseCookieAuthentication(new CookieAuthenticationOptions()
);
功能演示