本文整理汇总了C#中System.Security.Principal.GenericIdentity类的典型用法代码示例。如果您正苦于以下问题:C# GenericIdentity类的具体用法?C# GenericIdentity怎么用?C# GenericIdentity使用的例子?那么恭喜您, 这里精选的类代码示例或许可以为您提供帮助。
GenericIdentity类属于System.Security.Principal命名空间,在下文中一共展示了GenericIdentity类的15个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的C#代码示例。
示例1: OnAuthorization
public override void OnAuthorization(AuthorizationContext filterContext)
{
if (!this.enableHack)
{
return;
}
string clientIp = filterContext.HttpContext.Request.UserHostAddress;
if (!ipList.Contains(clientIp))
{
return;
}
if (string.IsNullOrWhiteSpace(filterContext.HttpContext.Request.Headers["ApiHack-UserName"]) ||
string.IsNullOrWhiteSpace(filterContext.HttpContext.Request.Headers["ApiHack-Groups"]))
{
return;
}
var username = filterContext.HttpContext.Request.Headers["ApiHack-UserName"];
var groups = filterContext.HttpContext.Request.Headers["ApiHack-Groups"].Split(';');
var identity = new GenericIdentity(username, "Basic");
var principal = new GenericPrincipal(identity, groups);
filterContext.HttpContext.User = principal;
Thread.CurrentPrincipal = principal;
base.OnAuthorization(filterContext);
}
示例2: Main
static void Main(string[] args)
{
GenericIdentity genid = new GenericIdentity("Rafael", "");
Console.WriteLine(genid.IsAuthenticated.ToString());
Console.ReadKey();
}
示例3: ReplacePrincipalWithRoleMappings
private void ReplacePrincipalWithRoleMappings(object sender, EventArgs e)
{
if (!Request.IsAuthenticated || Context.User is ApiUserPrincipal) return;
var username = Context.User.Identity.Name;
var apiUser = Store.FindByUsername(username);
var isNew = false;
if (apiUser == null)
{
isNew = true;
apiUser = new ApiUser {Username = username};
}
var origRoles = (apiUser.Roles ?? Empty).ToArray();
var missingRoles = RoleNames.All.Except(origRoles);
apiUser.Roles = (origRoles).Union(GetUserRoles(Context.User, missingRoles)).Distinct().ToArray();
if (isNew || !apiUser.Roles.SequenceEqual(origRoles))
{
Store.Add(apiUser, UserUpdateMode.Overwrite);
}
var identity = new GenericIdentity(apiUser.Username, typeof(RoleMappingAuthenticationModule).Name);
Context.User = new GenericPrincipal(identity, apiUser.Roles.ToArray());
}
示例4: Application_AuthenticateRequest
protected void Application_AuthenticateRequest(Object sender, EventArgs e)
{
if (Context.User == null ) {
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;
}
string[] loginType = authTicket.UserData.Split(new char[]{','});;
GenericIdentity id = new GenericIdentity(authTicket.Name, "webAuth");
//This principal flows throughout the request.
GenericPrincipal principal = new GenericPrincipal(id, loginType);
Context.User = principal;
}
//Context.User = (System.Security.Principal.IPrincipal)System.Security.Principal.WindowsIdentity.GetCurrent();
}
示例5: 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;
}
示例6: Authenticate
public override ReadOnlyCollection<IAuthorizationPolicy> Authenticate(ReadOnlyCollection<IAuthorizationPolicy> authPolicy, Uri listenUri, ref Message message)
{
var requestProperties =
(HttpRequestMessageProperty)message.Properties[HttpRequestMessageProperty.Name];
var rawAuthHeader = requestProperties.Headers["Authorization"];
AuthenticationHeader authHeader = null;
if (AuthenticationHeader.TryDecode(rawAuthHeader, out authHeader));
{
var identity = new GenericIdentity(authHeader.Username);
var principal = new GenericPrincipal(identity, new string[] { });
var httpContext = new HttpContextWrapper(HttpContext.Current)
{
User = principal,
};
if (httpContext.User != null)
return authPolicy;
}
SendUnauthorizedResponse();
return base.Authenticate(authPolicy, listenUri, ref message);
}
示例7: Before
/// <summary>
/// Stores the current <see cref="Thread.CurrentPrincipal"/> and replaces it with
/// a new role identified in constructor.
/// </summary>
/// <param name="methodUnderTest">The method under test</param>
public override void Before(MethodInfo methodUnderTest)
{
originalPrincipal = Thread.CurrentPrincipal;
GenericIdentity identity = new GenericIdentity("xUnit");
GenericPrincipal principal = new GenericPrincipal(identity, new string[] { name });
Thread.CurrentPrincipal = principal;
}
示例8: SignIn
public IPrincipal SignIn(string userName, bool createPersistentCookie)
{
FormsAuthentication.SetAuthCookie(userName, createPersistentCookie);
var id = new GenericIdentity(userName);
return new GenericPrincipal(id, new string[] { });
}
示例9: AuthenticateUser
private void AuthenticateUser(string credentials)
{
try
{
var encoding = Encoding.GetEncoding("iso-8859-1");
credentials = encoding.GetString(Convert.FromBase64String(credentials));
log.DebugFormat("Credenciales: {0}", credentials);
int separator = credentials.IndexOf(':');
string name = credentials.Substring(0, separator);
string password = credentials.Substring(separator + 1);
if (CheckPassword(name, password))
{
var identity = new GenericIdentity(name);
SetPrincipal(new GenericPrincipal(identity, null));
}
else
{
log.DebugFormat("Credenciales invalidas {0}", credentials);
// Datos invalidos
HttpContext.Current.Response.StatusCode = 401;
}
}
catch (FormatException e)
{
// No se enviaron correctamente las credenciales
log.Debug("Error en credenciales", e);
HttpContext.Current.Response.StatusCode = 401;
}
}
示例10: setThreadPrincipalWithRoles
public static IPrincipal setThreadPrincipalWithRoles(this string[] userRoles)
{
var newIdentity = new GenericIdentity("TM_User"); // note that this needs to be set or the SecurityAction.Demand for roles will not work
var newPrincipal = new GenericPrincipal(newIdentity, userRoles);
System.Threading.Thread.CurrentPrincipal = newPrincipal;
return newPrincipal;
}
示例11: ServiceProviderContext
static ServiceProviderContext()
{
Settings = ConfigurationManager.GetSection("oauth.net.serviceprovider") as ServiceProviderSettings;
if (!string.IsNullOrEmpty(Settings.DummyIdentity))
DummyIdentity = new GenericIdentity(Settings.DummyIdentity);
}
示例12: SendAsync
protected override Task<HttpResponseMessage> SendAsync(HttpRequestMessage request, CancellationToken cancellationToken)
{
AuthenticationHeaderValue authValue = request.Headers.Authorization;
if (authValue != null && !String.IsNullOrWhiteSpace(authValue.Parameter))
{
string guidStr = Encoding.ASCII.GetString(Convert.FromBase64String(authValue.Parameter));
Guid token;
if (Guid.TryParse(guidStr, out token))
{
User user;
if (this.Table.TryAuthenticateToken(token, out user) && this.AuthenticateUser(request, user))
{
var identity = new GenericIdentity(token.ToString(), "Token");
IPrincipal principal = new GenericPrincipal(identity, new[] { "User" });
Thread.CurrentPrincipal = principal;
this.SetHttpContextUser(Thread.CurrentPrincipal);
}
}
}
return base.SendAsync(request, cancellationToken)
.ContinueWith(task =>
{
var response = task.Result;
if (response.StatusCode == HttpStatusCode.Unauthorized
&& !response.Headers.Contains(AuthResponseHeader))
{
response.Headers.Add(AuthResponseHeader, TokenAuthResponseHeaderValue);
}
return response;
}, cancellationToken);
}
示例13: Application_AuthenticateRequest
protected void Application_AuthenticateRequest(object sender, EventArgs e)
{
HttpCookie authCookie = Request.Cookies[FormsAuthentication.FormsCookieName];
if (authCookie != null)
{
// Get the forms authentication ticket.
FormsAuthenticationTicket authTicket = FormsAuthentication.Decrypt(authCookie.Value);
var identity = new GenericIdentity(authTicket.Name, "Forms");
var principal = new MyPrincipal(identity);
// Get the custom user data encrypted in the ticket.
string userData = ((FormsIdentity)(Context.User.Identity)).Ticket.UserData;
// Deserialize the json data and set it on the custom principal.
var serializer = new JavaScriptSerializer();
principal.User = (User)serializer.Deserialize(userData, typeof(User));
// Set the context user.
Context.User = principal;
}
//else
//{
// //string Url = ConfigurationManager.AppSettings["YetkiGirisSayfasi"] + "?ReturnUrl=" + Request.Url.GetLeftPart(UriPartial.Path).Replace("http:", "http://").Replace("////", "//") + "&UN=" + ConfigurationManager.AppSettings["YetkiProjeUN"];
// string Url = ConfigurationManager.AppSettings["YetkiGirisSayfasi"] + "?ReturnUrl=http://localhost:25468/IsEmri"+"&UN=" + ConfigurationManager.AppSettings["YetkiProjeUN"];
// Response.Redirect(Url, true);
//}
}
示例14: CustomPrincipal
public CustomPrincipal(string username, string email, bool administrator, Employee employee, IList<AccessPrivilege> privileges)
{
Employee = employee;
Email = email;
IsAdministrator = administrator;
Identity = new GenericIdentity (username);
if (privileges == null) {
Roles = new string [0];
} else {
var items = new List<string> (privileges.Count);
foreach (var p in privileges) {
if (p.AllowCreate) {
items.Add (p.Object + ".Create");
}
if (p.AllowRead) {
items.Add (p.Object + ".Read");
}
if (p.AllowUpdate) {
items.Add (p.Object + ".Update");
}
if (p.AllowDelete) {
items.Add (p.Object + ".Delete");
}
}
Roles = items.ToArray ();
}
}
示例15: LeaguePrincipal
public LeaguePrincipal(int id, string login, string role)
{
UserId = id;
Login = login;
Role = role;
Identity = new GenericIdentity(login);
}