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

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

注册一个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网页

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

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

);

功能演示

本文参与腾讯云自媒体分享计划,欢迎正在阅读的你也加入,一起分享。

发表于

我来说两句

0 条评论
登录 后参与评论

相关文章

来自专栏刘望舒

Android PMS处理APK的复制

在上一篇文章Android包管理机制之PackageInstaller安装APK中,我们学习了PackageInstaller是如何安装APK的,最后会将APK...

23950
来自专栏函数式编程语言及工具

Akka(10): 分布式运算:集群-Cluster

   Akka-Cluster可以在一部物理机或一组网络连接的服务器上搭建部署。用Akka开发同一版本的分布式程序可以在任何硬件环境中运行,这样我们就可以确定以...

63090
来自专栏圣杰的专栏

Asp.net mvc 知多少(三)

本系列主要翻译自《ASP.NET MVC Interview Questions and Answers 》- By Shailendra Chauhan,想...

22560
来自专栏逸鹏说道

我这么玩Web Api(一)

帮助页面或用户手册(Microsoft and Swashbuckle Help Page) 前言   你需要为客户编写Api调用手册?你需要测试你的Api接口...

32350
来自专栏技术小讲堂

使用WCF进行跨平台开发之一(WCF的实现、控制台托管与.net平台的调用)1.创建项目结构2.契约的设计3.实现服务4.控制台托管服务5.在.net平台中调用WCF

     WCF是Windows Communication Foundation的缩写,是微软发展的一组数据通信的应用程序开发接口,它是.NET框架的一部分,...

41990
来自专栏java学习

servlet实现文件上传功能

最新通知 ●回复"每日一练"获取以前的题目! ●【新】Android视频更新了!(回复【安卓视频】获取下载链接) ●【新】Ajax知识点视频更新了!(回复【学习...

377120
来自专栏大内老A

WCF后续之旅(11): 关于并发、回调的线程关联性(Thread Affinity)

对于一般的多线程操作,比如异步地进行基于文件系统的IO操作;异步地调用Web Service;或者是异步地进行数据库访问等等,是和具体的线程无关的。也就是说,对...

251100
来自专栏马洪彪

Java生成条码二维码

一、概述 可用barcode4j或zxing等第三方库,推荐zxing。 barcode4j资料链接:http://barcode4j.sourceforge....

53380
来自专栏JetpropelledSnake

Django学习笔记之利用Form和Ajax实现注册功能

18750
来自专栏小尘哥的专栏

小程序(3):授权登录

判断是否授权,如果没有,则显示授权按钮。注意上面的open-type="getUserInfo",这个会自动调起授权框。看一下js

48340

扫码关注云+社区

领取腾讯云代金券