本文整理汇总了C#中System.Security.Claims.Claim类的典型用法代码示例。如果您正苦于以下问题:C# Claim类的具体用法?C# Claim怎么用?C# Claim使用的例子?那么恭喜您, 这里精选的类代码示例或许可以为您提供帮助。
Claim类属于System.Security.Claims命名空间,在下文中一共展示了Claim类的15个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的C#代码示例。
示例1: GenerateUserToken
/// <summary>
/// Generate Token from user information
/// </summary>
/// <param name="Id">User id</param>
/// <param name="username">UserName</param>
/// <returns>TokenResponse</returns>
public TokenResponse GenerateUserToken(long Id, string username)
{
var now = DateTime.UtcNow;
var claims = new Claim[]
{
new Claim("id", Id.ToString()),
new Claim("name", username),
new Claim(JwtRegisteredClaimNames.Iat, ToUnixEpochDate(now).ToString(), ClaimValueTypes.Integer64)
};
// Create the JWT and write it to a string
var jwt = new JwtSecurityToken(
issuer: this.options.Issuer,
audience: this.options.Audience,
claims: claims,
notBefore: now,
expires: now.Add(this.options.Expiration),
signingCredentials: this.options.SigningCredentials ?? TokenProvider.DefaultSigningCredentials());
var encodedJwt = new JwtSecurityTokenHandler().WriteToken(jwt);
return new TokenResponse
{
access_token = encodedJwt,
expires_in = (ulong)this.options.Expiration.TotalSeconds
};
}
示例2: JsonClaim
public JsonClaim(Claim claim)
{
if (claim == null) throw new ArgumentNullException("claim");
if (!claim.ValueType.StartsWith("Json:"))
throw new ArgumentException("Claim has unsupported ValueType", "claim");
Claim = claim;
}
示例3: Main
static void Main(string[] args)
{
// NOTE: The below is a sample of how we may construct a ClaimsPrincipal instance over two ClaimsIdentity instances:
// one for the tenant identity and the the other for the user idenetity. When a request come to the web server, we can determine the
// tenant's identity at the very early stages of the request lifecycle. Then, we can try to authenticate the user based on the
// information passed through the request headers (this could be bearer token, basic auth, etc.).
const string tenantId = "f35fe69d-7aef-4f1a-b645-0de4176cd441";
const string tenantName = "bigcompany";
IEnumerable<Claim> tenantClaims = new Claim[]
{
new Claim(ClaimTypes.NameIdentifier, tenantId, ClaimValueTypes.String, AuthServerName),
new Claim(ClaimTypes.Name, tenantName, ClaimValueTypes.String, AuthServerName)
};
const string userId = "d4903f71-ca06-4671-a3df-14f7e02a0008";
const string userName = "tugberk";
const string twitterToken = "30807826f0d74ed29d69368ea5faee2638b0e931566b4e4092c1aca9b4db04fe";
const string facebookToken = "35037356a183470691504cd163ce2f835419978ed81c4b7781ae3bbefdea176a";
IEnumerable<Claim> userClaims = new Claim[]
{
new Claim(ClaimTypes.NameIdentifier, userId, ClaimValueTypes.String, AuthServerName),
new Claim(ClaimTypes.Name, userName, ClaimValueTypes.String, AuthServerName),
new Claim("token", twitterToken, ClaimValueTypes.String, AuthServerName, "Twitter"),
new Claim("token", facebookToken, ClaimValueTypes.String, AuthServerName, "Facebook")
};
ClaimsIdentity tenantIdentity = new ClaimsIdentity(tenantClaims, TenantAuthType, ClaimTypes.Name, ClaimTypes.Role);
ClaimsIdentity userIdentity = new ClaimsIdentity(userClaims, UserAuthType, ClaimTypes.Name, ClaimTypes.Role);
ClaimsPrincipal principal = new ClaimsPrincipal(new[] { tenantIdentity, userIdentity });
}
示例4: CreateWithUserId
public static ClaimsPrincipal CreateWithUserId(long authorId)
{
var claim = new Claim(ToBeImplementedClaims.IdClaim, authorId.ToString());
var identity = new ClaimsIdentity(Enumerable.Repeat(claim, 1));
var claimsprincipal = new ClaimsPrincipal(identity);
return claimsprincipal;
}
示例5: GetValue
private static object GetValue(Claim claim)
{
if (claim.ValueType == ClaimValueTypes.Integer ||
claim.ValueType == ClaimValueTypes.Integer32)
{
Int32 value;
if (Int32.TryParse(claim.Value, out value))
{
return value;
}
}
if (claim.ValueType == ClaimValueTypes.Integer64)
{
Int64 value;
if (Int64.TryParse(claim.Value, out value))
{
return value;
}
}
if (claim.ValueType == ClaimValueTypes.Boolean)
{
bool value;
if (bool.TryParse(claim.Value, out value))
{
return value;
}
}
return claim.Value;
}
示例6: UserClaim
public UserClaim(Claim claim)
{
if (claim == null) throw new ArgumentNullException("claim");
Type = claim.Type;
Value = claim.Value;
}
示例7: ValidatePrincipal
public Task ValidatePrincipal(CookieValidatePrincipalContext context)
{
//
// TODO: uncomment this after next release of aspnet core
// and fix the broken
// it needs to resolve options per tenant
//await securityStampValidator.ValidateAsync(context);
var tenant = context.HttpContext.GetTenant<SiteContext>();
if (tenant == null)
{
context.RejectPrincipal();
}
var siteGuidClaim = new Claim("SiteGuid", tenant.Id.ToString());
if (!context.Principal.HasClaim(siteGuidClaim.Type, siteGuidClaim.Value))
{
logger.LogInformation("rejecting principal because it does not have siteguid");
context.RejectPrincipal();
}
//TODO: should we lookup the user here and reject if locked out or deleted?
return Task.FromResult(0);
}
示例8: BackendCredentialsClaim
public BackendCredentialsClaim(Claim claim)
: base(claim.Type, claim.Value)
{
Contract.Requires<ArgumentException>(claim.Type == TYPE, "Invalid Claim Type");
SplitValue(claim.Value, out User, out Password);
}
示例9: CreateIdentity
public static ClaimsIdentity CreateIdentity(Data.User user)
{
var claimsIdentity = new ClaimsIdentity(DefaultAuthenticationTypes.ApplicationCookie, ClaimTypes.Name, ClaimTypes.Role);
claimsIdentity.AddClaim(new Claim(ClaimTypes.NameIdentifier, user.Id.ToString()));
claimsIdentity.AddClaim(new Claim(ClaimTypes.Email, user.EmailAddress));
claimsIdentity.AddClaim(new Claim(ClaimTypes.Name, user.UserName));
claimsIdentity.AddClaim(
new Claim("http://schemas.microsoft.com/accesscontrolservice/2010/07/claims/identityprovider",
"ASP.NET Identity",
"http://www.w3.org/2001/XMLSchema#string"));
if (user.IsAdmin)
{
var adminClaim = new Claim(ClaimTypes.Role, AdministratorRole); // , null, ClaimIssuerName);
claimsIdentity.AddClaim(adminClaim);
}
// Cannot assign null-value to new claim
if (null != user.Cultures)
{
claimsIdentity.AddClaim(new Claim(ClaimTypes.UserData, user.Cultures));
}
return claimsIdentity;
}
开发者ID:transformersprimeabcxyz,项目名称:ResourceFirstTranslations,代码行数:25,代码来源:RftAuthenticationManager.cs
示例10: Should_remove_claim
public void Should_remove_claim()
{
var user = TestData.GetTestUserJohn();
var claimToDelete = new Claim(ClaimTypes.Email, "[email protected]");
var task = _target.RemoveClaimAsync(user, claimToDelete);
task.Wait();
var db = Database.Open();
var claims = db.AspNetUserClaims.FindAllByUserId(TestData.John_UserId).ToList();
Assert.That(claims.Count, Is.EqualTo(1));
bool foundClaim=false;
foreach (var claim in claims)
{
if (claim.ClaimType == ClaimTypes.Email)
{
foundClaim = true;
}
}
Assert.That(foundClaim, Is.False);;
}
示例11: ValidateToken
private async Task<IEnumerable<Claim>> ValidateToken(string token)
{
HttpClient clientRequest = new HttpClient();
clientRequest.BaseAddress = new Uri("http://localhost:10100/");
clientRequest.DefaultRequestHeaders.Accept.Add(
new MediaTypeWithQualityHeaderValue("application/json"));
var response = clientRequest.PostAsJsonAsync("authorize/verify", token).Result;
if (!response.IsSuccessStatusCode)
{
return null;
}
var content = await response.Content.ReadAsStringAsync();
ValidateResult result = JsonConvert.DeserializeObject<ValidateResult>(content);
var claim = new Claim(result.Type, result.Value);
List<Claim> claims = new List<Claim>(1);
claims.Add(claim);
return claims;
}
示例12: ValidateToken
public ClaimsPrincipal ValidateToken(string securityToken, TokenValidationParameters validationParameters, out SecurityToken validatedToken)
{
//eyJ0eXAiOiJKV1QiLCJhbGciOiJIUzI1NiJ9.eyJ1bmlxdWVfbmFtZSI6Ikphc29uIExlZSIsInN1YiI6Ikphc29uIExlZSIsInJvbGUiOlsiTWFuYWdlciIsIlN1cGVydmlzb3IiXSwiaXNzIjoiaHR0cDovL2p3dGF1dGh6c3J2LmF6dXJld2Vic2l0ZXMubmV0IiwiYXVkIjoiUm9ja2V0IiwiZXhwIjoxNDQxOTgwMjE5LCJuYmYiOjE0NDE5NzY2MTl9.yegylhGkz5uasu5E--aEbCAHfi5aE9Z17_pZAE63Bog
validatedToken = null;
var key = "IxrAjDoa2FqElO7IhrSrUJELhUckePEPVpaePlS_Xaw";
try
{
var raw = JsonWebToken.Decode(securityToken, key);
var payLoad = JsonConvert.DeserializeObject<List<KeyValuePair<string, string>>>(raw);
var claims = new List<Claim>();
foreach (var row in payLoad)
{
var claim = new Claim(row.Key, row.Value);
claims.Add(claim);
}
var claimsIdentity = new ClaimsIdentity(claims, "jwt");
return new ClaimsPrincipal(claimsIdentity);
}
catch (Exception ex)
{
return null;
}
}
示例13: Setup
private void Setup()
{
var myClaim = new Claim("http://myclaims/customer", "add");
var currentIdentity = new CorpIdentity("stevenh", myClaim);
var principal = new ClaimsPrincipal(currentIdentity);
Thread.CurrentPrincipal = principal;
}
示例14: CreateAsync
public virtual Task<ClaimsIdentity> CreateAsync(User user, string authenticationType, IEnumerable<string> userRoles, IEnumerable<Claim> userClaims)
{
var claimsIdentity = new ClaimsIdentity(authenticationType, this.UserNameClaimType, this.RoleClaimType);
claimsIdentity.AddClaim(new Claim(this.UserIdClaimType, user.Id, DefaultClaimValueType));
claimsIdentity.AddClaim(new Claim(this.UserNameClaimType, user.UserName, DefaultClaimValueType));
claimsIdentity.AddClaim(new Claim(IdentityProviderClaimType, DefaultIdentityProviderClaimValue, DefaultClaimValueType));
// TODO: Support Security Stamp.
var claim = new Claim(this.SecurityStampClaimType, user.SecurityStamp);
claimsIdentity.AddClaim(claim);
// TODO: Support User Roles, Ensure Roles are loaded.
if (userRoles != null)
{
foreach (var userRole in userRoles)
{
claimsIdentity.AddClaim(new Claim(this.RoleClaimType, userRole, DefaultClaimValueType));
}
}
// TODO: Support User Claims.
if (userClaims != null)
{
foreach (var userClaim in userClaims)
{
claimsIdentity.AddClaim(userClaim);
}
}
return Task.FromResult(claimsIdentity);
}
开发者ID:Perfectial,项目名称:Perfectial.EntityFramework.Enterprise.Sample,代码行数:31,代码来源:ClaimsIdentityFactory.cs
示例15: ProcessLogoutNameIdentifier
private static Saml2NameIdentifier ProcessLogoutNameIdentifier(Claim claim)
{
var fields = DelimitedString.Split(claim.Value);
var saml2NameIdentifier = new Saml2NameIdentifier(fields[4]);
if (!string.IsNullOrEmpty(fields[0]))
{
saml2NameIdentifier.NameQualifier = fields[0];
}
if (!string.IsNullOrEmpty(fields[1]))
{
saml2NameIdentifier.SPNameQualifier = fields[1];
}
if (!string.IsNullOrEmpty(fields[2]))
{
saml2NameIdentifier.Format = new Uri(fields[2]);
}
if (!string.IsNullOrEmpty(fields[3]))
{
saml2NameIdentifier.SPProvidedId = fields[3];
}
return saml2NameIdentifier;
}