HttpContext.User,即IPrincipal
.net源代码
namespace System.Security.Principal { /// <summary>Defines the basic functionality of a principal object.</summary> [__DynamicallyInvokable, ComVisible(true)] public interface IPrincipal { /// <summary>Gets the identity of the current principal.</summary> /// <returns>The <see cref="T:System.Security.Principal.IIdentity" /> object associated with the current principal.</returns> [__DynamicallyInvokable] IIdentity Identity { [__DynamicallyInvokable] get; } /// <summary>Determines whether the current principal belongs to the specified role.</summary> /// <returns>true if the current principal is a member of the specified role; otherwise, false.</returns> /// <param name="role">The name of the role for which to check membership. </param> [__DynamicallyInvokable] bool IsInRole(string role); } }
IPrincipal.Identity属性(只读)
.net源代码
/// <summary>Defines the basic functionality of an identity object.</summary> [__DynamicallyInvokable, ComVisible(true)] public interface IIdentity { /// <summary>Gets the name of the current user.</summary> /// <returns>The name of the user on whose behalf the code is running.</returns> [__DynamicallyInvokable] string Name { [__DynamicallyInvokable] get; } /// <summary>Gets the type of authentication used.</summary> /// <returns>The type of authentication used to identify the user.</returns> [__DynamicallyInvokable] string AuthenticationType { [__DynamicallyInvokable] get; } /// <summary>Gets a value that indicates whether the user has been authenticated.</summary> /// <returns>true if the user was authenticated; otherwise, false.</returns> [__DynamicallyInvokable] bool IsAuthenticated { [__DynamicallyInvokable] get; } }
Identity的种类
MVC的授权过滤器 AuthorizeAttribute,即利用了Httpcontext.User来验证当前请求是否已被认证。
.net源代码如下
public class AuthorizeAttribute : FilterAttribute, IAuthorizationFilter { protected virtual bool AuthorizeCore(HttpContextBase httpContext) { if (httpContext == null) { throw new ArgumentNullException("httpContext"); } IPrincipal user = httpContext.User; return user.Identity.IsAuthenticated && (this._usersSplit.Length <= 0 || this._usersSplit.Contains(user.Identity.Name, StringComparer.OrdinalIgnoreCase)) && (this._rolesSplit.Length <= 0 || this._rolesSplit.Any(new Func<string, bool>(user.IsInRole))); } }