Form认证的几点说明
有的页面需要用户认证之后才可以进入,通常都是在Filter的OnActionExecuting方法中我们需要获取当前用户。有两种情况不必登录:1.用户是登录的,也就是认证过的。2.用户上次登录了,但没有退出就关闭了页面,且还Cookie还没有过期。这个时候
Request.IsAuthenticated=true
所以用户不必再登录。

如果用户退出,也就是调用SignOut()
public void SignOut()
{
_cachedUser = null;
FormsAuthentication.SignOut();
}
这个时候获取不到认证用户。

Filter就会让用户返回到登录页面。
var user = WorkContext.CurrentUser;
if (user == null)
{
filterContext.Result = new RedirectResult("~/Account/Logon?returnUrl=" + returnUrl);
}
另外,在Ninject中无法注入HttpContextBase,但可以讲其换成属性。
public HttpContextBase HttpContext
{
get { return new HttpContextWrapper(System.Web.HttpContext.Current); }
}
而对于Filter可以属性注入。
[Inject]
public IAuthenticationService AuthenticationService { get; set; }
LoginValidAttribute 源码:
public class LoginValidAttribute : ActionFilterAttribute
{
/// <summary>
/// 转到管理员登陆的界面
/// </summary>
private bool _isAdmin; public LoginValidAttribute(bool isadmin = false)
{
_isAdmin = isadmin;
} public override void OnActionExecuting(ActionExecutingContext filterContext)
{
var contr = filterContext.RouteData.Values["controller"].ToString();
var action = filterContext.RouteData.Values["action"].ToString();
var parmdatas = filterContext.ActionParameters;
var parms = "?";
var i = ;
var count = parmdatas.Count;
foreach (var parmdata in parmdatas)
{
i++;
if (i <= count - )
{
parms += parmdata.Key + "=" + parmdata.Value + "&";
}
else
{
parms += parmdata.Key + "=" + parmdata.Value; }
}
if (count == ) parms = "";
var returnUrl = string.Format("~/{0}/{1}{2}", contr, action, parms);
returnUrl = UrlHelper.GenerateContentUrl(returnUrl, filterContext.HttpContext); var user = WorkContext.CurrentUser;
if (user == null)
{
filterContext.Result = new RedirectResult("~/Account/Logon?returnUrl=" + returnUrl);
} // 如果已经登录 但不是角色,就需要跳转到只是页面 提示是管理员才能登录 } [Inject]
public IWorkContext WorkContext { get; set; } }
WebWorkContext:
public class WebWorkContext : IWorkContext
{
#region Const #endregion #region Fields private readonly IUserService _userService;
private User _cachedUser; #endregion public WebWorkContext( IUserService userService )
{
_userService = userService;
} #region Utilities protected virtual HttpCookie GetUserCookie()
{
if (HttpContext == null || HttpContext.Request == null)
return null; return HttpContext.Request.Cookies[PortalConfig.UserCookieName];
} protected virtual void SetUserCookie(Guid customerGuid)
{
if (HttpContext != null && HttpContext.Response != null)
{
var cookie = new HttpCookie(PortalConfig.UserCookieName);
cookie.HttpOnly = true;
cookie.Value = customerGuid.ToString();
if (customerGuid == Guid.Empty)
{
cookie.Expires = DateTime.Now.AddMonths(-);
}
else
{
int cookieExpires = * ; //TODO make configurable
cookie.Expires = DateTime.Now.AddHours(cookieExpires);
} HttpContext.Response.Cookies.Remove(PortalConfig.UserCookieName);
HttpContext.Response.Cookies.Add(cookie);
}
} #endregion public virtual User CurrentUser
{
get
{ User customer = AuthenticationService.GetAuthenticatedCustomer(); ; //load guest customer
if (customer == null || customer.Deleted || !customer.Active)
{
var customerCookie = GetUserCookie();
if (customerCookie != null && !String.IsNullOrEmpty(customerCookie.Value))
{
Guid customerGuid;
if (Guid.TryParse(customerCookie.Value, out customerGuid))
{
var customerByCookie = _userService.GetUserByGuid(customerGuid);
if (customerByCookie != null &&IsCurrentUser)
//this customer (from cookie) should not be registered
//!customerByCookie.IsRegistered())
customer = customerByCookie;
}
}
} //validation
if (customer!=null&&!customer.Deleted && customer.Active)
{
SetUserCookie(customer.UserGuid);
} return customer;
;
}
set
{
SetUserCookie(value.UserGuid);
_cachedUser = value;
}
} public User OriginalUserIfImpersonated { get; private set; }
public bool IsAdmin { get; set; }
public bool IsCurrentUser {
get { return AuthenticationService.IsCurrentUser; }
} public HttpContextBase HttpContext
{
get { return new HttpContextWrapper(System.Web.HttpContext.Current); }
} [Inject]
public IAuthenticationService AuthenticationService { get; set; }
}
FormsAuthenticationService:
public class FormsAuthenticationService : IAuthenticationService
{
private readonly IUserService _userService;
private readonly TimeSpan _expirationTimeSpan; private User _cachedUser; public FormsAuthenticationService(IUserService userService)
{
_userService = userService;
_expirationTimeSpan = FormsAuthentication.Timeout;
} public void SignIn(User user, bool createPersistentCookie)
{
var now = DateTime.UtcNow.ToLocalTime();
var ticket = new FormsAuthenticationTicket(, user.Username, now, now.Add(_expirationTimeSpan),
createPersistentCookie, user.Username, FormsAuthentication.FormsCookiePath);
var encryptedTicket = FormsAuthentication.Encrypt(ticket);
var cookie = new HttpCookie(FormsAuthentication.FormsCookieName, encryptedTicket) {HttpOnly = true};
if (ticket.IsPersistent)
{
cookie.Expires = ticket.Expiration;
}
cookie.Secure = FormsAuthentication.RequireSSL;
cookie.Path = FormsAuthentication.FormsCookiePath;
if (FormsAuthentication.CookieDomain != null)
{
cookie.Domain = FormsAuthentication.CookieDomain;
}
HttpContext.Response.Cookies.Add(cookie);
//nop源码中没有这一句,务必保证webconfig中的认证是form的。
// FormsAuthentication.SetAuthCookie(user.Username, createPersistentCookie);
_cachedUser = user;
} public void SignOut()
{
_cachedUser = null;
FormsAuthentication.SignOut();
} public User GetAuthenticatedCustomer()
{
if (_cachedUser != null) return _cachedUser;
if (HttpContext == null || HttpContext.Request == null || !HttpContext.Request.IsAuthenticated ||
!(HttpContext.User.Identity is FormsIdentity))
{
return null;
}
var formsIdentity = (FormsIdentity)HttpContext.User.Identity;
var user = GetAuthenticatedUserFromTicket(formsIdentity.Ticket);
if (user != null && user.Active && !user.Deleted )//&& user.IsRegistered()
_cachedUser = user;
return _cachedUser;
} public bool IsCurrentUser
{
get { return GetAuthenticatedCustomer() != null; }
} public virtual User GetAuthenticatedUserFromTicket(FormsAuthenticationTicket ticket)
{
if (ticket == null)
throw new ArgumentNullException("ticket"); var usernameOrEmail = ticket.Name; if (String.IsNullOrWhiteSpace(usernameOrEmail))
return null; var user = _userService.GetUserByUsername(usernameOrEmail); return user;
} public HttpContextBase HttpContext
{
get { return new HttpContextWrapper(System.Web.HttpContext.Current); }
}
}
Form认证的几点说明的更多相关文章
- SharePoint 2013 配置基于AD的Form认证
前 言 配置SharePoint 2013基于AD的Form认证,主要有三步: 1. 修改管理中心的web.config: 2. 修改STS Application的web.config: 3. 修改 ...
- Asp.Net实现FORM认证的一些使用技巧(转)
最近因为项目代码重构需要重新整理用户登录和权限控制的部分,现有的代码大体是参照了.NET的FORM认证,并结合了PORTAL KITS的登录控制,代码比较啰嗦,可维护性比较差.于是有了以下的几个需求( ...
- MVC4.0 使用Form认证,自定义登录页面路径Account/Login
使用MVC4.0的时候,一般遇到会员登录.注册功能,我们都会使用Form认证,给需要身份验证的Action进行授权(需要登录后才能访问的Action添加[Authorize]属性标签),登录.注册的时 ...
- MVC用户登陆验证及权限检查(Form认证)
1.配置Web.conf,使用Form认证方式 <system.web> <authentication mode="None" /> ...
- Asp.Net 之 使用Form认证实现用户登录 (LoginView的使用)
1. 创建一个WebSite,新建一个页面命名为SignIn.aspx,然后在页面中添加如下的代码 <div class="div_logView"> <asp: ...
- asp.net Form 认证【转】
第一部分 如何运用 Form 表单认证 一. 新建一个测试项目 为了更好说明,有必要新建一个测试项目(暂且为“FormTest”吧),包含三张页面足矣(Default.aspx.Logi ...
- Asp.Net实现FORM认证的一些使用技巧
原文转发:http://www.cnblogs.com/Showshare/archive/2010/07/09/1772886.html 最近因为项目代码重构需要重新整理用户登录和权限控制的部分,现 ...
- sharepoint:基于AD的FORM认证
//来源:http://www.cnblogs.com/jindahao/archive/2012/05/07/2487351.html 需求: 1. 认证要基于AD 2. 登入方式要页面的方式(fo ...
- 浅谈MVC Form认证
简单的谈一下MVC的Form认证. 在做MVC项目时,用户登录认证需要选用Form认证时,我们该怎么做呢?下面我们来简单给大家说一下. 首先说一下步骤 1.用户登录时,如果校验用户名密码通过后,需要调 ...
- Asp.net MVC Form认证,IIS改成集成模式后,FormsAuthentication.SetAuthCookie无效,Request.IsAuthenticated值,始终为false,页面提示HTTP 错误 401.0 - Unauthorized,您无权查看此目录或页面
最近公司领导要求,IIS网站要由经典模式改为集成模式,以提高性能.改完之后,登录成功跳转到主页之后,页面提示“”HTTP 错误 401.0 - Unauthorized“,“您无权查看此目录或页面”, ...
随机推荐
- Http协议与TCP协议简单理解(转)
在C#编写代码,很多时候会遇到Http协议或者TCP协议,这里做一个简单的理解.TCP协议对应于传输层,而HTTP协议对应于应用层,从本质上来说,二者没有可比性.Http协议是建立在TCP协议基础之上 ...
- ATL 获取flash信息
// This goes past the ATL includes #import "C:/WINDOWS/system32/Macromed/Flash/Flash9e.ocx" ...
- sql获取汉字的拼音首字母
if exists (select * from sysobjects where id = object_id(N'[fn_ChineseToSpell]') and xtype in (N'FN' ...
- ready与onload区别一
<!DOCTYPE html><html> <head> <title>ready与onload区别一</title> <meta c ...
- php生成器的使用
按照php的文档说明 一个生成器函数看起来像一个普通的函数,不同的是普通函数返回一个值,而一个生成器可以yield生成许多它所需要的值. 当一个生成器被调用的时候,它返回一个可以被遍历的对象.当你遍历 ...
- hibernate配置文件中的schema="dbo"在MySQL数据库不可用
把项目的数据库由SQL Server更改为MySQL之后,发现hibernate报错. 问题在于schema="dbo",使用SQL Sever数据库时正常,使用MySQL数据库需 ...
- Guidelines for accessing OneDrive from an app
Guidelines for accessing OneDrive from an app https://msdn.microsoft.com/en-us/library/windows/apps/ ...
- C++中有符号/无符号数比较
原创文章,欢迎阅读,禁止转载. 在我的程序中有如下代码编译被警告了 if(list.size()>msize){...} warning C4018: '<' : signed/unsig ...
- 【九度OJ】题目1054:字符串内排序
题目描述: 输入一个字符串,长度小于等于200,然后将输出按字符顺序升序排序后的字符串. 输入: 测试数据有多组,输入字符串. 输出: 对于每组输入,输出处理后的结果. 样例输入: bacd 样例输出 ...
- windows10 technical preview 无法激活