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

2020-12-13 01:37

阅读:572

YPE html>

标签: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

soscw.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 UserManager = new UserManager(new UserStore(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网页

  

 

登录Login.html 子页面

  

 

Home.html登录进去的首页

div class="container">

。。。。。。

 

div>

 

soscw.com,搜素材soscw.com,搜素材soscw.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/

//[Authorize]

public IEnumerablestring> 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()

);

功能演示

soscw.com,搜素材

soscw.com,搜素材

 

Angularjs 通过asp.net web api认证登录,搜素材,soscw.com

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

标签:style   c   class   blog   code   java   

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


评论


亲,登录后才可以留言!