码迷,mamicode.com
首页 > Windows程序 > 详细

Angularjs 通过asp.net web api认证登录

时间:2014-05-27 00:14:15      阅读:756      评论:0      收藏:0      [点我收藏+]

标签:style   c   class   blog   code   java   

Angularjs 通过asp.net web api认证登录

Angularjs利用asp.net mvc提供的asp.net identity,membership实现居于数据库的用户名/密码的认证登录

环境

Vs.net 2013

Asp.net mvc + web api

Individual user accounts

Angularjs

Underscore

 

新建一个asp.net mvc+ web api project

bubuko.com,布布扣

注册一个test用户用于测试

新建一个用于登录验证用户名密码的webapi controller 代码如下

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]
 
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网页

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

 

bubuko.com,布布扣bubuko.com,布布扣bubuko.com,布布扣

认证流程

 

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交互认证用户名/密码 服务

 

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页面服务器端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)

{

// 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()

);

功能演示

bubuko.com,布布扣

bubuko.com,布布扣

 

Angularjs 通过asp.net web api认证登录,布布扣,bubuko.com

Angularjs 通过asp.net web api认证登录

标签:style   c   class   blog   code   java   

原文地址:http://www.cnblogs.com/neozhu/p/3744984.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!