asp.net 认证与授权
1.下面的例子在web.config文件中配置网站使用asp.net forms 身份认证方式:
<configuration>
<system.web>
<authentication mode="Forms">
<forms name="MyAppCookie"
loginUrl="~/Login.aspx"
protection="All"
timeout="30" path="/" />
</authentication>
...
</system.web>
</configuration>
Forms 认证设置:
| 属性 | 描述 |
| name |
The name of the HTTP cookie to use fo r authentication (defaults to .ASPXAUTH). If multiple applications are running on the same web server, you should give each application’s security cookie a unique name. |
| loginUrl | Your custom login page, where the user is redirected if no valid authentication cookie is found. The default value is Login.aspx. |
| protection | The type of encryption and validation used for the security cookie (can be All, None, Encryption, or Validation). Validation ensures the cookie isn’t changed during transit,and encryption (typically Triple-DES) is used to encode its contents. The default value is All. |
| timeout | The number of idle minutes before the c ookie expires. ASP.NET will refresh the cookie every time it receives a request. The default value is 30. |
| path | The path for cookies issued by the app lication. The default value (/) is recommended, because case mismatches can prevent the c ookie from being sent with a request. |
2.Authorization Rules(授权规则)
<authorization>
<allow users="*" />
<deny users="?" />
</authorization>
When evaluating rules, ASP.NET scans through the list from top to bottom and then continues with the settings in any .config file inherited from a parent directory, ending with the settings in the base machine.config file. As soon as it finds an applicable rule, it stops it s search. Thus, in the previous case, it will determine that the rule <allow users="*"> applies to the current request and will not evaluate the second line. This means these rules will allow all users, including anonymous users.
<authorization>
<deny users="?" />
<allow users="*" />
</authorization>
Now these rules will deny anonymous users (by matching the first rule) and allow all other users (by matching the second rule).
3.The Login Page(登录页)
ASP.NET provides a special FormsAuthentication class in the System.Web.Security namespace, which provides static methods that help manage the process.
public partial class Login : System.Web.UI.Page
{
protected void cmdLogin_Click(Object sender, EventArgs e)
{
if (txtPassword.Text.ToLower() == "secret")
{
FormsAuthentication.RedirectFromLoginPage(
txtName.Text, false);
}
else
{
lblStatus.Text = "Try again.";
}
}
}
The RedirectFromLoginPage() method requires two parameters. The first sets the name of the user. The second is a Boolean variable that specifies whether you want to create a persistent cookie (one that stays on the user’s hard drive for a longer period of time).
4.Retrieving the User’s Identity
Once the user is logged in, you can retrieve the identity through the built-in User property, as shown here:
protected void Page_Load(Object sender, EventArgs e)
{
lblMessage.Text = "You have reached the secured page, ";
lblMessage.Text += User.Identity.Name + ".";
}
5.Signing Out
private void cmdSignOut_Click(Object sender, EventArgs e)
{
FormsAuthentication.SignOut();
Response.Redirect("~/Login.aspx");
}
6.Persistent Cookies(持久cookie)
A persistent authentication cookie remains on the user’s hard drive and keeps the user signed in for hours, days, or weeks—even if the user closes and reopens the browser.
Creating a persistent cookie requires a bit more code than creating a standard forms authentication cookie. Instead of using the RedirectFromLoginPage() method, you need to manually create the authentication ticket, set its expiration time, encrypt it , attach it to the request, and then redirect the user to the requested page. All of these tasks are easy, but it’s important to perform them all in the correct order.
The following code examines a check box named chkPersist. If it’s selected, the code creates a persistent cookie that lasts for 20 days:
// Perform the authentication.
if (txtPassword.Text.ToLower() == "secret")
{
if (chkPersist.Checked)
{
// Use a persistent cookie that lasts 20 days.
// The timeout must be specified as a number of minutes.
int timeout = (int)TimeSpan.FromDays(20).TotalMinutes; // Create an authentication ticket.
FormsAuthenticationTicket ticket = new
FormsAuthenticationTicket(txtName.Text, true, cookietimeout); // Encrypt the ticket (so people can't steal it as it travels over
// the Internet).
string encryptedTicket = FormsAuthentication.Encrypt(ticket); // Create the cookie for the ticket, and put the ticket inside.
HttpCookie cookie = new HttpCookie(FormsAuthentication.FormsCookieName,
encryptedTicket);
// Give the cookie and the authentication ticket the same expiration.
cookie.Expires = ticket.Expiration; // Attach the cookie to the current response. It will now travel back to
// the client, and then back to the web server with every new request.
HttpContext.Current.Response.Cookies.Set(cookie); // Send the user to the originally requested page.
string requestedPage = FormsAuthentication.GetRedirectUrl(txtName.text,
false);
Response.Redirect(requestedPage, true);
}
else
{
// Use the standard authentication method.
FormsAuthentication.RedirectFromLoginPage(
txtName.Text, false);
}
}
It’s worth noting that the FormsAuthentication.SignOut() method will always remove the forms authentication cookie, regardless of whether it is a normal cookie or a persistent cookie.
asp.net 认证与授权的更多相关文章
- Asp.Net MVC-4-过滤器1:认证与授权
基础 过滤器体现了MVC框架中的Aop思想,虽然这种实现并不完美但在实际的开发过程中一般也足以满足需求了. 过滤器分类 依据上篇分析的执行时机的不同可以把过滤器按照实现不同的接口分为下面五类: IAu ...
- ASP.NET Core 认证与授权[1]:初识认证
在ASP.NET 4.X 中,我们最常用的是Forms认证,它既可以用于局域网环境,也可用于互联网环境,有着非常广泛的使用.但是它很难进行扩展,更无法与第三方认证集成,因此,在 ASP.NET Cor ...
- ASP.NET Core 认证与授权[3]:OAuth & OpenID Connect认证
在上一章中,我们了解到,Cookie认证是一种本地认证方式,通常认证与授权都在同一个服务中,也可以使用Cookie共享的方式分开部署,但局限性较大,而如今随着微服务的流行,更加偏向于将以前的单体应用拆 ...
- ASP.NET Core 认证与授权[5]:初识授权
经过前面几章的姗姗学步,我们了解了在 ASP.NET Core 中是如何认证的,终于来到了授权阶段.在认证阶段我们通过用户令牌获取到用户的Claims,而授权便是对这些的Claims的验证,如:是否拥 ...
- ASP.NET Core 认证与授权[6]:授权策略是怎么执行的?
在上一章中,详细介绍了 ASP.NET Core 中的授权策略,在需要授权时,只需要在对应的Controler或者Action上面打上[Authorize]特性,并指定要执行的策略名称即可,但是,授权 ...
- 【翻译】asp.net core2.1认证和授权解密
asp.net core2.1认证和授权解密 本篇文章翻译自:https://digitalmccullough.com/posts/aspnetcore-auth-system-demystifie ...
- ASP.NET Core WebAPI中使用JWT Bearer认证和授权
目录 为什么是 JWT Bearer 什么是 JWT JWT 的优缺点 在 WebAPI 中使用 JWT 认证 刷新 Token 使用授权 简单授权 基于固定角色的授权 基于策略的授权 自定义策略授权 ...
- ASP.NET Core 认证与授权[1]:初识认证 (笔记)
原文链接: https://www.cnblogs.com/RainingNight/p/introduce-basic-authentication-in-asp-net-core.html 在A ...
- 最简实例演示asp.net5中用户认证和授权(4)
上篇: 最简实例演示asp.net5中用户认证和授权(3) 上面我们把自定义认证和授权的相关的最小基础类和要实现的接口都实现了,下面就是如何来进行认证和授权的配置. 首先我们要告诉系统,我们的用户和角 ...
随机推荐
- TTY驱动程序架构
在Linux系统中,终端是一类字符型设备,它包括多种类型,通常使用tty来简称各种类型的终端设备. • 串口终端(/dev/ttyS*) 串口终端是使用计算机串口连接的终端设备.Linux把每个串行端 ...
- 分享O'Reilly最新C语言指针数据
1.推荐书名 Understanding.and.Using.C.Pointers.pdf 2. 本书目录 Table of Content Chapter 1. Introduction Chapt ...
- char const*, char*const, const char *const的区别
C++标准规定,const关键字放在类型或变量名之前等价的.所以,const char*和 char const*是一样的. const char* //常量指针---指向常量的指针----指针指 ...
- C语言中内存对齐方式
一.什么是对齐,以及为什么要对齐: 1. 现代计算机中内存空间都是按照byte划分的,从理论上讲似乎对任何类型的变量的访问可以从任何地址开始,但实际情况是在访问特定变量的时候经常在特定的内存地址访问, ...
- JavaScript高级程序设计之location对象
location对象用来处理URL的相关信息 1.获取查询字符串 // 获取查询字符串对象 var getQueryStringArgs = function () { ? location.sear ...
- Jni中C++和Java的参数传递
Jni中C++和Java的参数传递 如何使用JNI的一些基本方法和过程在网上多如牛毛,如果你对Jni不甚了解,不知道Jni是做什么的,如何建立一个基本的jni程序,或许可以参考下面下面这些文章:利用V ...
- 海蜘蛛ISPV6.1.5,目前破解版本中最稳定的!
海蜘蛛ISPV6.1.5,目前破解版本中最稳定的! 破解步骤如下: 一.安装完毕进控制台 二.使用muddyboot登陆 密码(123456) 三.输入root回车 四.输入regtools回车 五. ...
- Question about pairing/bonding?
Except that on android you can bypass the pairing dialog if you know the PIN in advance through a di ...
- Redis 客户端配置及示例
一.redis自定义配置节点 <configSections> <section name ="RedisConfig" type="Amy.Toolk ...
- STM32管教复用与重映射关系
摘自:http://blog.csdn.net/lincheng15/article/details/51789093 概括一下:复用就是一个引脚有几个功能,1.做普通IO输入输出 2.其他外设的输入 ...