Angularjs 通过asp.net web api认证登录
Angularjs 通過asp.net web api認證登錄
Angularjs利用asp.net mvc提供的asp.net identity,membership實現(xiàn)居于數(shù)據(jù)庫的用戶名/密碼的認證登錄
環(huán)境
Vs.net 2013
Asp.net mvc + web api
Individual user accounts
Angularjs
Underscore
?
新建一個asp.net mvc+ web api project
注冊一個test用戶用于測試
新建一個用于登錄驗證用戶名密碼的webapi controller 代碼如下
public class LoginController : ApiController{[HttpGet]public string Get(){AuthenticationManager.SignOut();return "Success";}private IAuthenticationManager AuthenticationManager{get{return HttpContext.Current.GetOwinContext().Authentication;}}UserManager<ApplicationUser> UserManager = new UserManager<ApplicationUser>(new UserStore<ApplicationUser>(new ApplicationDbContext()));[HttpPost]public HttpResponseMessage PostLogin(LoginViewModel model){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, "Invalid username or password.");}}}
?
新建Index.html網(wǎng)頁
<!DOCTYPE html><html xmlns="http://www.w3.org/1999/xhtml" ng-app="app"><head><title></title><link href="Content/bootstrap.css" rel="stylesheet" /><script src="Scripts/bootstrap.js"></script><script src="Scripts/jquery-1.10.2.js"></script><script src="Scripts/angular.js"></script><script src="Scripts/angular-route.js"></script><script src="Scripts/app.js"></script><script src="Scripts/underscore.js"></script></head><body><div class="row"><div class="large-12"><div id="view" ng-view></div></div></div></body></html>
?
登錄Login.html 子頁面
<div class="col-md-4 col-md-offset-4" login-directive><!--<div class="panel panel-default"><div class="panel-heading"><h3 class="panel-title">Please sign in</h3></div><div class="panel-body"><form accept-charset="UTF-8" role="form" name="form"><fieldset><div class="form-group"><input class="form-control" placeholder="E-mail" name="email" type="text" ng-model="credentials.UserName" required></div><div class="form-group"><input class="form-control" placeholder="Password" name="password" type="password" value="" ng-model="credentials.Password" required></div><div class="checkbox"><label><input name="remember" type="checkbox" value="Remember Me" ng-model="credentials.RememberMe"> Remember Me</label></div><p class="text-danger" ng-show="message">{{message}}</p><input class="btn btn-lg btn-success btn-block" ng-click="login()" ng-disabled="form.$invalid" type="submit" value="Login"></fieldset></form></div></div>--></div>
?
Home.html登錄進去的首頁
<div class="container">
。。。。。。
?
</div>
?
認證流程
?
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("Username must be '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');
}
};
?
});
與后臺web api交互認證用戶名/密碼 服務(wù)
?
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("Please login");
$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();
?
});
?
ValuesController Authroize屬性,必須認證通過才能訪問
?
[Authorize]
public class ValuesController : ApiController
{
// GET api/<controller>
//[Authorize]
public IEnumerable<string> Get()
{
return new string[] { "value1", "value2" };
}
?
Homecontroller中可以logout登出,和getvalue獲取需要認證的webapi。如果用戶長時間在home頁面服務(wù)器端session過期后在調(diào)用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)
{
// Enable the application to use a cookie to store information for the signed in user
//app.UseCookieAuthentication(new CookieAuthenticationOptions
//{
// AuthenticationType = DefaultAuthenticationTypes.ApplicationCookie,
// LoginPath = new PathString("/Account/Login")
//});
app.UseCookieAuthentication(new CookieAuthenticationOptions()
);
功能演示
?
轉(zhuǎn)載于:https://www.cnblogs.com/neozhu/p/3744984.html
總結(jié)
以上是生活随笔為你收集整理的Angularjs 通过asp.net web api认证登录的全部內(nèi)容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: 梦到羊排骨是什么意思
- 下一篇: PANIC: Unreachable c