本文整理汇总了C#中System.Security.Principal.GenericPrincipal类的典型用法代码示例。如果您正苦于以下问题:C# GenericPrincipal类的具体用法?C# GenericPrincipal怎么用?C# GenericPrincipal使用的例子?那么恭喜您, 这里精选的类代码示例或许可以为您提供帮助。
GenericPrincipal类属于System.Security.Principal命名空间,在下文中一共展示了GenericPrincipal类的15个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的C#代码示例。
示例1: Application_AuthenticateRequest
/// <summary>
/// Handles the AuthenticateRequest event of the Application control.
/// </summary>
/// <param name="sender">The source of the event.</param>
/// <param name="e">The <see cref="EventArgs" /> instance containing the event data.</param>
protected void Application_AuthenticateRequest(object sender, EventArgs e)
{
var authCookie = Request.Cookies[FormsAuthentication.FormsCookieName];
if (authCookie != null)
{
try
{
var authTicket = FormsAuthentication.Decrypt(authCookie.Value);
if (authTicket != null)
{
var identity = new GenericIdentity(authTicket.Name, "Forms");
var roles = authTicket.UserData.Split(new[] { ',' }, StringSplitOptions.RemoveEmptyEntries).Distinct().ToArray();
var principal = new GenericPrincipal(identity, roles);
Context.User = principal;
}
}
catch
{
Session.Clear();
FormsAuthentication.SignOut();
}
}
cmsHost.OnAuthenticateRequest(this);
}
示例2: OnAuthenticateRequest
private void OnAuthenticateRequest(object sender, EventArgs e)
{
var app = sender as HttpApplication;
var credentials = app.Context.Request.Headers["Authorization"];
if (string.IsNullOrEmpty(credentials)) return;
//var userPassword = System.Convert.FromBase64String(credentials);
//var userString = (new System.Text.UTF8Encoding()).GetString(userPassword);
var encodedPassword = AuthenticationHeaderValue.Parse(credentials).Parameter;
var userPassword = new System.Text.UTF8Encoding().GetString(System.Convert.FromBase64String(encodedPassword));
var passwordParts = userPassword.Split(':');
var userName = passwordParts[0];
var password = passwordParts[1];
if (!WebSecurity.Initialized)
throw new System.ApplicationException("WebSecurity database became unitialized");
if (Membership.Provider.ValidateUser(userName, password))
{
var identity = new BasicIdentity(userName);
var roles = Roles.Provider.GetRolesForUser(userName);
var principal = new GenericPrincipal(identity, roles);
app.Context.User = principal;
if (HttpContext.Current != null)
HttpContext.Current.User = principal;
}
}
示例3: SendAsync
protected override Task<HttpResponseMessage> SendAsync(HttpRequestMessage request, CancellationToken cancellationToken) {
HttpRequestMessage r = request;
if (r.Headers.Authorization == null) {
return Login();
}
AuthenticationHeaderValue auth = r.Headers.Authorization;
byte[] decodedBytes = Convert.FromBase64String(auth.Parameter);
string decodedUserAndPassword = Encoding.UTF8.GetString(decodedBytes);
string[] userAndPassword = decodedUserAndPassword.Split(':');
string user = userAndPassword[0];
string password = userAndPassword[1];
UserCredentials credentials = Validate(user, password);
if (credentials != null) {
var p = new GenericPrincipal(new GenericIdentity(credentials.User), credentials.Roles.ToArray());
Thread.CurrentPrincipal = p;
return base.SendAsync(request, cancellationToken);
}
// fail
return Login();
}
示例4: setupNormalRequestValues
public API_Moq_HttpContext setupNormalRequestValues()
{
var genericIdentity = new GenericIdentity("genericIdentity");
var genericPrincipal = new GenericPrincipal(genericIdentity, new string[] {});
MockContext.Setup(context => context.User).Returns(genericPrincipal);
MockContext.Setup(context => context.Cache).Returns(HttpRuntime.Cache);
MockContext.Setup(context => context.Server.MapPath(It.IsAny<string>())).Returns((string path) => this.BaseDir.pathCombine(path));
//Request
MockRequest.Setup(request =>request.InputStream ).Returns(new MemoryStream());
MockRequest.Setup(request =>request.Headers ).Returns(new NameValueCollection());
MockRequest.Setup(request =>request.QueryString ).Returns(new NameValueCollection());
MockRequest.Setup(request =>request.Form ).Returns(new NameValueCollection());
//Response
var outputStream = new MemoryStream();
MockResponse.Setup(response =>response.OutputStream).Returns(outputStream);
//var writer = new StringWriter();
// context.Expect(ctx => ctx.Response.Output).Returns(writer);
MockResponse.Setup(response =>response.Write(It.IsAny<string>())).Callback((string code) => outputStream.Write(code.asciiBytes(), 0, code.size()));
var cache = new Mock<HttpCachePolicyBase>();
MockResponse.SetupGet(response => response.Cache).Returns(cache.Object);
return this;
}
示例5: SendAsync
protected async override System.Threading.Tasks.Task<HttpResponseMessage> SendAsync( HttpRequestMessage request, System.Threading.CancellationToken cancellationToken )
{
var authHeader = request.Headers.Authorization;
if ( authHeader != null )
{
if ( authHeader.Scheme.Equals( "encryptKey", StringComparison.OrdinalIgnoreCase ) &&
!String.IsNullOrWhiteSpace( authHeader.Parameter ) )
{
var key = authHeader.Parameter;
if ( IsVerified( key ) )
{
var currentPrincipal = new GenericPrincipal( new GenericIdentity( "User" ), null );
request.GetRequestContext().Principal = currentPrincipal;
}
}
}
return await base.SendAsync( request, cancellationToken )
.ContinueWith( task =>
{
var response = task.Result;
if ( response.StatusCode == HttpStatusCode.Unauthorized &&
!response.Headers.Contains( basicAuthResponseHeader ) )
response.Headers.Add( basicAuthResponseHeader, basicAuthResponseHeaderValue );
return response;
} );
}
示例6: CreateLoginUserTicket
/// <summary>
/// 创建登录用户的票据信息
/// </summary>
/// <param name="strUserName"></param>
public static string CreateLoginUserTicket(string userId)
{
DateTime loginTime = DateTime.Now;//用户的登录时间
//构造Form验证的票据信息
///把登录时间和用户ID写进Cookie中,后面可以用于判断用户的登录时间间隔
FormsAuthenticationTicket ticket = new FormsAuthenticationTicket(1, userId, DateTime.Now, DateTime.Now.AddMinutes(90),
true, string.Format("{0}:{1}", userId, loginTime), FormsAuthentication.FormsCookiePath);
string ticString = FormsAuthentication.Encrypt(ticket);
//把票据信息写入Cookie和Session
//SetAuthCookie方法用于标识用户的Identity状态为true
HttpContext.Current.Response.Cookies.Add(new HttpCookie("UserLoginCookieToken", ticString));
FormsAuthentication.SetAuthCookie(userId, true);
HttpContext.Current.Session["USER_LOGON_TICKET"] = ticString;
//重写HttpContext中的用户身份,可以封装自定义角色数据;
//判断是否合法用户,可以检查:HttpContext.User.Identity.IsAuthenticated的属性值
string[] roles = ticket.UserData.Split(',');
IIdentity identity = new FormsIdentity(ticket);
IPrincipal principal = new GenericPrincipal(identity, roles);
HttpContext.Current.User = principal;
return ticString;//返回票据
}
示例7: Application_AuthenticateRequest
void Application_AuthenticateRequest(object sender, EventArgs e)
{
string cookieName = FormsAuthentication.FormsCookieName;
HttpCookie authCookie = Context.Request.Cookies[cookieName];
if (null == authCookie)
{
//There is no authentication cookie.
return;
}
FormsAuthenticationTicket authTicket = null;
try
{
authTicket = FormsAuthentication.Decrypt(authCookie.Value);
}
catch (Exception ex)
{
//Write the exception to the Event Log.
return;
}
if (null == authTicket)
{
//Cookie failed to decrypt.
return;
}
//When the ticket was created, the UserData property was assigned a
//pipe-delimited string of group names.
string[] groups = authTicket.UserData.Split(new char[] { '|' });
//Create an Identity.
GenericIdentity id = new GenericIdentity(authTicket.Name, "LdapAuthentication");
//This principal flows throughout the request.
GenericPrincipal principal = new GenericPrincipal(id, groups);
Context.User = principal;
}
示例8: OnAuthenticateRequest
private static void OnAuthenticateRequest(object sender, EventArgs e)
{
var application = (HttpApplication) sender;
HttpContext context = application.Context;
if (context.User != null && context.User.Identity.IsAuthenticated)
return;
string cookieName = FormsAuthentication.FormsCookieName;
HttpCookie cookie = application.Request.Cookies[cookieName.ToUpper()];
if (cookie == null)
return;
try
{
FormsAuthenticationTicket ticket = FormsAuthentication.Decrypt(cookie.Value);
var identity = new CustomIdentity(AccountEntry.Deserialize(ticket.UserData), ticket.Name);
var principal = new GenericPrincipal(identity, identity.GetRoles());
context.User = principal;
Thread.CurrentPrincipal = principal;
}
catch
{
}
}
示例9: OnAuthorization
protected override void OnAuthorization(AuthorizationContext filterContext)
{
base.OnAuthorization(filterContext);
//Zapisanie pryncypala z rolami
if (HttpContext.User != null && HttpContext.User.Identity!=null && !string.IsNullOrEmpty(HttpContext.User.Identity.Name))
{
string[] tablicaRol = new string[1];
string nazwaUzytkownika = HttpContext.User.Identity.Name;
var rola = WroBL.Logowanie.RolaUzytkownika(nazwaUzytkownika);
if (rola != WroBL.Logowanie.Rola.Gosc)
{
tablicaRol[0] = WroBL.Logowanie.NazwaRoli(rola);
GenericPrincipal principal = new GenericPrincipal(HttpContext.User.Identity, tablicaRol);
HttpContext.User = principal;
}
//Update daty ostatniego zalogowania
if (HttpContext.User.Identity.Name != null && WroBL.Logowanie.UzytkownikIstnieje(nazwaUzytkownika))
WroBL.Logowanie.ZaktualizujDateOstatniegoLogowania(nazwaUzytkownika,true);
}
}
示例10: NewsletterDaemon
public NewsletterDaemon(Federation fed, string rootURL, string newslettersFrom,
string headInsert, bool sendAsAttachments, string authenticateAs)
{
_federation = fed;
_rootUrl = rootURL;
_newslettersFrom = newslettersFrom;
_headInsert = headInsert;
_sendAsAttachments = sendAsAttachments;
AuthorizationRuleWho who = AuthorizationRuleWho.Parse(authenticateAs);
if (who.WhoType == AuthorizationRuleWhoType.GenericAnonymous)
{
_principal = new GenericPrincipal(new GenericIdentity(""), null);
}
else if (who.WhoType == AuthorizationRuleWhoType.User)
{
_principal = new GenericPrincipal(new GenericIdentity(who.Who), null);
}
else
{
throw new ArgumentException("Newsletters can only authenticate as 'anonymous' or as a particular user. Illegal value: " +
authenticateAs, "authenticateAs");
}
}
示例11: AgentGenericPrincipal
public static GenericPrincipal AgentGenericPrincipal()
{
//AgentId = 1,
var ident = new GenericIdentity("mike");
var principal = new GenericPrincipal(ident, new[] { LookUpRoles.AgentRole });
return principal;
}
示例12: OnAuthorization
public void OnAuthorization(AuthorizationContext filterContext)
{
HttpCookie authCookie = filterContext.HttpContext.Request.Cookies[FormsAuthentication.FormsCookieName];
if ((authCookie != null) && (!filterContext.HttpContext.Session.IsNewSession) )
{
FormsAuthenticationTicket authTicket = FormsAuthentication.Decrypt(authCookie.Value);
var identity = new GenericIdentity(authTicket.Name, "Forms");
var principal = new GenericPrincipal(identity, new string[] { authTicket.UserData });
filterContext.HttpContext.User = principal;
}
var Controller = filterContext.ActionDescriptor.ControllerDescriptor.ControllerName;
var Action = filterContext.ActionDescriptor.ActionName;
var User = filterContext.HttpContext.User;
var IP = filterContext.HttpContext.Request.UserHostAddress;
var isAccessAllowed = ACL.IsAccessAllowed(Controller, Action, User, IP);
if (!isAccessAllowed)
{
//FormsAuthentication.RedirectToLoginPage();
filterContext.HttpContext.Response.Redirect("/Pages/Login", true);
// filterContext.Result = new HttpUnauthorizedResult();
// return;
}
}
示例13: Main
static void Main(string[] args)
{
GenericPrincipal principal = new GenericPrincipal(new GenericIdentity("Miguel"), new string[] { "CarRentalAdmin" });
Thread.CurrentPrincipal = principal;
ObjectBase.Container = MEFLoader.Init();
Console.WriteLine("Starting up services");
Console.WriteLine("");
SM.ServiceHost hostInventoryManager = new SM.ServiceHost(typeof(InventoryManager));
SM.ServiceHost hostRentalManager = new SM.ServiceHost(typeof(RentalManager));
SM.ServiceHost hostAccountManager = new SM.ServiceHost(typeof(AccountManager));
StartService(hostInventoryManager, "InventoryManager");
StartService(hostRentalManager, "RentalManager");
StartService(hostAccountManager, "AccountManager");
System.Timers.Timer timer = new Timer(10000);
timer.Elapsed += OnTimerElapsed;
timer.Start();
Console.WriteLine("");
Console.WriteLine("Press [Enter] to exit.");
Console.ReadLine();
timer.Stop();
Console.WriteLine("Reservation Monitor Stopped");
StopService(hostInventoryManager, "InventoryManager");
StopService(hostRentalManager, "RentalManager");
StopService(hostAccountManager, "AccountManager");
}
示例14: Application_AuthenticateRequest
protected void Application_AuthenticateRequest(object sender, EventArgs e)
{
if ((HttpContext.Current.User == null) ||
(!HttpContext.Current.User.Identity.IsAuthenticated)) return;
// Get Forms Identity From Current User
var id = (FormsIdentity)HttpContext.Current.User.Identity;
// Create a custom Principal Instance and assign to Current User (with caching)
var principal = (GenericPrincipal)HttpContext.Current.Cache.Get(id.Name);
if (principal == null)
{
// Create and populate your Principal object with the needed data and Roles.
principal = new GenericPrincipal(id, new string[0]);
HttpContext.Current.Cache.Add(
id.Name,
principal,
null,
System.Web.Caching.Cache.NoAbsoluteExpiration,
new TimeSpan(0, 30, 0),
System.Web.Caching.CacheItemPriority.Default,
null);
}
HttpContext.Current.User = principal;
}
示例15: OnAuthenticateRequest
private static void OnAuthenticateRequest(object sender, EventArgs eventArgs)
{
var httpApplication = (HttpApplication)sender;
var cookieName = FormsAuthentication.FormsCookieName;
var cookie = httpApplication.Request.Cookies[cookieName.ToUpper()];
if (cookie == null)
return;
try
{
var ticket = FormsAuthentication.Decrypt(cookie.Value);
if (ticket == null || ticket.Expired)
return;
var accountData = AccountData.Deserialize(ticket.UserData);
var identity = new FrameplateIdentity(accountData, ticket.Name);
var principal = new GenericPrincipal(identity, accountData.Roles);
httpApplication.Context.User = principal;
Thread.CurrentPrincipal = principal;
}
catch
{
}
}