本文整理汇总了C#中System.Security.Claims.ClaimsPrincipal.AddIdentity方法的典型用法代码示例。如果您正苦于以下问题:C# ClaimsPrincipal.AddIdentity方法的具体用法?C# ClaimsPrincipal.AddIdentity怎么用?C# ClaimsPrincipal.AddIdentity使用的例子?那么恭喜您, 这里精选的方法代码示例或许可以为您提供帮助。您也可以进一步了解该方法所在类System.Security.Claims.ClaimsPrincipal
的用法示例。
在下文中一共展示了ClaimsPrincipal.AddIdentity方法的15个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的C#代码示例。
示例1: AddUserIdentity
/// <summary>
/// Add an additional ClaimsIdentity to the ClaimsPrincipal in the "server.User" environment key
/// </summary>
/// <param name="identity"></param>
public void AddUserIdentity(IIdentity identity)
{
if (identity == null)
{
throw new ArgumentNullException("identity");
}
var newClaimsPrincipal = new ClaimsPrincipal(identity);
IPrincipal existingPrincipal = _context.Request.User;
if (existingPrincipal != null)
{
var existingClaimsPrincipal = existingPrincipal as ClaimsPrincipal;
if (existingClaimsPrincipal == null)
{
IIdentity existingIdentity = existingPrincipal.Identity;
if (existingIdentity.IsAuthenticated)
{
newClaimsPrincipal.AddIdentity(existingIdentity as ClaimsIdentity ?? new ClaimsIdentity(existingIdentity));
}
}
else
{
foreach (var existingClaimsIdentity in existingClaimsPrincipal.Identities)
{
if (existingClaimsIdentity.IsAuthenticated)
{
newClaimsPrincipal.AddIdentity(existingClaimsIdentity);
}
}
}
}
_context.Request.User = newClaimsPrincipal;
}
示例2: GetAccessToken
public ActionResult GetAccessToken(string code)
{
var query = new Dictionary<string, string>();
query.Add("client_id", Constants.GITHUB_CLIENT_ID);
query.Add("client_secret", Constants.GITHUB_CLIENT_SEC);
query.Add("code", code);
query.Add("state", Constants.GITHUB_OAUTH_STATE);
// send request
JObject resp = Utility.MakeJsonHttpRequest(Constants.GITHUB_AK_URL, query);
string accessToken = (string)resp["access_token"];
// call sts and return
// build cliam
var claim = new ClaimsPrincipal();
var id = new ClaimsIdentity();
id.AddClaim(new Claim(Constants.CLAIM_TYPE_GITHUB_AK, accessToken));
claim.AddIdentity(id);
// send claim
var sigingCredentials = new X509SigningCredentials(Utility.GetCertificate(Constants.CERTIFICATE_NAME));
var config = new SecurityTokenServiceConfiguration(Constants.ISSUER_NAME, sigingCredentials);
var sts = new CustomSecurityTokenService(config);
var requestMessage = (SignInRequestMessage)WSFederationMessage.CreateFromUri(Request.Url);
var responesMessage = FederatedPassiveSecurityTokenServiceOperations.ProcessSignInRequest(requestMessage, claim, sts);
var formData = responesMessage.WriteFormPost();
return new ContentResult() { Content = formData, ContentType = "text/html" };
}
示例3: Authenticate
public override ClaimsPrincipal Authenticate(string resourceName, ClaimsPrincipal incomingPrincipal)
{
var id = new ClaimsIdentity("ClaimsAuthenticationManager");
id.AddClaim(new Claim(ClaimTypes.Role, "RoleFromClaimsAuthManager", null, "ClaimsAuthenticationManagerMock"));
incomingPrincipal.AddIdentity(id);
return incomingPrincipal;
}
示例4: AddingPreservesNewIdentitiesAndDropsEmpty
public void AddingPreservesNewIdentitiesAndDropsEmpty()
{
var context = new DefaultHttpContext();
var existingPrincipal = new ClaimsPrincipal(new ClaimsIdentity());
var identityNoAuthTypeWithClaim = new ClaimsIdentity();
identityNoAuthTypeWithClaim.AddClaim(new Claim("identityNoAuthTypeWithClaim", "yes"));
existingPrincipal.AddIdentity(identityNoAuthTypeWithClaim);
var identityEmptyWithAuthType = new ClaimsIdentity("empty");
existingPrincipal.AddIdentity(identityEmptyWithAuthType);
context.User = existingPrincipal;
context.User.Identity.IsAuthenticated.ShouldBe(false);
var newPrincipal = new ClaimsPrincipal();
var newEmptyIdentity = new ClaimsIdentity();
var identityTwo = new ClaimsIdentity("yep");
newPrincipal.AddIdentity(newEmptyIdentity);
newPrincipal.AddIdentity(identityTwo);
SecurityHelper.AddUserPrincipal(context, newPrincipal);
// Preserve newPrincipal order
context.User.Identity.IsAuthenticated.ShouldBe(false);
context.User.Identity.Name.ShouldBe(null);
var principal = context.User;
principal.Identities.Count().ShouldBe(4);
principal.Identities.Skip(0).First().ShouldBe(newEmptyIdentity);
principal.Identities.Skip(1).First().ShouldBe(identityTwo);
principal.Identities.Skip(2).First().ShouldBe(identityNoAuthTypeWithClaim);
principal.Identities.Skip(3).First().ShouldBe(identityEmptyWithAuthType);
// This merge should drop newEmptyIdentity since its empty
SecurityHelper.AddUserPrincipal(context, new GenericPrincipal(new GenericIdentity("Test3", "Gamma"), new string[0]));
context.User.Identity.AuthenticationType.ShouldBe("Gamma");
context.User.Identity.Name.ShouldBe("Test3");
principal = context.User;
principal.Identities.Count().ShouldBe(4);
principal.Identities.Skip(0).First().Name.ShouldBe("Test3");
principal.Identities.Skip(1).First().ShouldBe(identityTwo);
principal.Identities.Skip(2).First().ShouldBe(identityNoAuthTypeWithClaim);
principal.Identities.Skip(3).First().ShouldBe(identityEmptyWithAuthType);
}
示例5: SetFakeUser
public static void SetFakeUser(this Controller controller, string userId)
{
SetFakeHttpContextIfNotAlreadySet(controller);
var claimsPrincipal = new ClaimsPrincipal();
claimsPrincipal.AddIdentity(new ClaimsIdentity(new List<Claim> { new Claim(ClaimTypes.NameIdentifier, userId) }));
Mock.Get(controller.HttpContext).SetupGet(httpContext => httpContext.User).Returns(claimsPrincipal);
}
示例6: AddingPreservesNewIdentitiesAndDropsEmpty
public void AddingPreservesNewIdentitiesAndDropsEmpty()
{
var existingPrincipal = new ClaimsPrincipal(new ClaimsIdentity());
var identityNoAuthTypeWithClaim = new ClaimsIdentity();
identityNoAuthTypeWithClaim.AddClaim(new Claim("identityNoAuthTypeWithClaim", "yes"));
existingPrincipal.AddIdentity(identityNoAuthTypeWithClaim);
var identityEmptyWithAuthType = new ClaimsIdentity("empty");
existingPrincipal.AddIdentity(identityEmptyWithAuthType);
Assert.False(existingPrincipal.Identity.IsAuthenticated);
var newPrincipal = new ClaimsPrincipal();
var newEmptyIdentity = new ClaimsIdentity();
var identityTwo = new ClaimsIdentity("yep");
newPrincipal.AddIdentity(newEmptyIdentity);
newPrincipal.AddIdentity(identityTwo);
var user = SecurityHelper.MergeUserPrincipal(existingPrincipal, newPrincipal);
// Preserve newPrincipal order
Assert.False(user.Identity.IsAuthenticated);
Assert.Null(user.Identity.Name);
Assert.Equal(4, user.Identities.Count());
Assert.Equal(newEmptyIdentity, user.Identities.Skip(0).First());
Assert.Equal(identityTwo, user.Identities.Skip(1).First());
Assert.Equal(identityNoAuthTypeWithClaim, user.Identities.Skip(2).First());
Assert.Equal(identityEmptyWithAuthType, user.Identities.Skip(3).First());
// This merge should drop newEmptyIdentity since its empty
user = SecurityHelper.MergeUserPrincipal(user, new GenericPrincipal(new GenericIdentity("Test3", "Gamma"), new string[0]));
Assert.Equal("Gamma", user.Identity.AuthenticationType);
Assert.Equal("Test3", user.Identity.Name);
Assert.Equal(4, user.Identities.Count());
Assert.Equal("Test3", user.Identities.Skip(0).First().Name);
Assert.Equal(identityTwo, user.Identities.Skip(1).First());
Assert.Equal(identityNoAuthTypeWithClaim, user.Identities.Skip(2).First());
Assert.Equal(identityEmptyWithAuthType, user.Identities.Skip(3).First());
}
示例7: SetFakeUserAndUserType
public static void SetFakeUserAndUserType(this Controller controller, string userId, UserType userType)
{
SetFakeHttpContextIfNotAlreadySet(controller);
var claimsPrincipal = new ClaimsPrincipal();
claimsPrincipal.AddIdentity(new ClaimsIdentity(new List<Claim>
{
new Claim(ClaimTypes.NameIdentifier, userId),
new Claim(AllReady.Security.ClaimTypes.UserType, Enum.GetName(typeof (UserType), userType))
}));
Mock.Get(controller.HttpContext).SetupGet(httpContext => httpContext.User).Returns(claimsPrincipal);
}
示例8: ClaimsPrincipal
public static ClaimsPrincipal ClaimsPrincipal(string userName = null)
{
var currentIdentity = Thread.CurrentPrincipal.Identity;
var name = userName ?? currentIdentity.Name;
var identity = new ClaimsIdentity();
identity.AddClaim(new Claim("nameidentifier",name));
var principal = new ClaimsPrincipal();
principal.AddIdentity(identity);
return principal;
}
示例9: OrgAdminsCanEditAllReadyTasks
public void OrgAdminsCanEditAllReadyTasks()
{
var claimsPrincipal = new ClaimsPrincipal();
claimsPrincipal.AddIdentity(new ClaimsIdentity(new List<Claim>
{
new Claim(ClaimTypes.NameIdentifier, "1"),
new Claim(AllReady.Security.ClaimTypes.UserType, Enum.GetName(typeof (UserType), UserType.OrgAdmin))
}));
var sut = new DetermineIfATaskIsEditable();
var result = sut.For(claimsPrincipal, null, null);
Assert.True(result);
}
示例10: ValidateUser
public ClaimsPrincipal ValidateUser(string token)
{
try
{
//Claims don't deserialize :(
//var jwttoken = JsonWebToken.DecodeToObject<JwtToken>(token, configProvider.GetAppSetting("securekey"));
var decodedtoken = JsonWebToken.DecodeToObject(token, _configProvider.GetAppSetting("securekey")) as Dictionary<string, object>;
if (decodedtoken == null)
return null;
var jwttoken = new JwtToken()
{
Audience = (string)decodedtoken["Audience"],
Issuer = (string)decodedtoken["Issuer"],
Expiry = DateTime.Parse(decodedtoken["Expiry"].ToString()),
};
if (decodedtoken.ContainsKey("Claims"))
{
var claims = new List<Claim>();
for (int i = 0; i < ((ArrayList)decodedtoken["Claims"]).Count; i++)
{
var type = ((Dictionary<string, object>)((ArrayList)decodedtoken["Claims"])[i])["Type"].ToString();
var value = ((Dictionary<string, object>)((ArrayList)decodedtoken["Claims"])[i])["Value"].ToString();
claims.Add(new Claim(type, value));
}
jwttoken.Claims = claims;
}
if (jwttoken.Expiry < DateTime.UtcNow)
{
return null;
}
//TODO Tidy on 3.8 Mono release
var claimsPrincipal = new ClaimsPrincipal();
var claimsIdentity = new ClaimsIdentity("Token");
claimsIdentity.AddClaims(jwttoken.Claims);
claimsPrincipal.AddIdentity(claimsIdentity);
return claimsPrincipal;
}
catch (Exception)
{
return null;
}
}
示例11: AddUserIdentity
/// <summary>
/// Add an additional ClaimsIdentity to the ClaimsPrincipal
/// </summary>
/// <param name="identity"></param>
public static void AddUserIdentity([NotNull] HttpContext context, [NotNull] IIdentity identity)
{
var newClaimsPrincipal = new ClaimsPrincipal(identity);
ClaimsPrincipal existingPrincipal = context.User;
if (existingPrincipal != null)
{
foreach (var existingClaimsIdentity in existingPrincipal.Identities)
{
if (existingClaimsIdentity.IsAuthenticated)
{
newClaimsPrincipal.AddIdentity(existingClaimsIdentity);
}
}
}
context.User = newClaimsPrincipal;
}
示例12: ClaimsPrincipal
public void AllReadyTaskThatHasInstanceOfEventAndEventHasInstanceOfCampaignAndCampaignHasInstanceOfOrganizerAndOrganizerIdEqualsUserIdIsEditable()
{
const string userId = "1";
var claimsPrincipal = new ClaimsPrincipal();
claimsPrincipal.AddIdentity(new ClaimsIdentity(new List<Claim>
{
new Claim(ClaimTypes.NameIdentifier, "1"),
new Claim(AllReady.Security.ClaimTypes.UserType, Enum.GetName(typeof (UserType), UserType.BasicUser))
}));
var allReadyTask = new AllReadyTask { Event = new Event { Campaign = new Campaign { Organizer = new ApplicationUser { Id = userId }}}};
var sut = new DetermineIfATaskIsEditable();
var result = sut.For(claimsPrincipal, allReadyTask, null);
Assert.True(result);
}
示例13: OnAuthorizationAsync
/// <inheritdoc />
public virtual async Task OnAuthorizationAsync([NotNull] AuthorizationContext context)
{
// Build a ClaimsPrincipal with the Policy's required authentication types
if (Policy.ActiveAuthenticationSchemes != null && Policy.ActiveAuthenticationSchemes.Any())
{
var newPrincipal = new ClaimsPrincipal();
foreach (var scheme in Policy.ActiveAuthenticationSchemes)
{
var result = (await context.HttpContext.Authentication.AuthenticateAsync(scheme))?.Principal;
if (result != null)
{
newPrincipal.AddIdentities(result.Identities);
}
}
// If all schemes failed authentication, provide a default identity anyways
if (newPrincipal.Identity == null)
{
newPrincipal.AddIdentity(new ClaimsIdentity());
}
context.HttpContext.User = newPrincipal;
}
// Allow Anonymous skips all authorization
if (context.Filters.Any(item => item is IAllowAnonymous))
{
return;
}
var httpContext = context.HttpContext;
var authService = httpContext.RequestServices.GetRequiredService<IAuthorizationService>();
// Note: Default Anonymous User is new ClaimsPrincipal(new ClaimsIdentity())
if (httpContext.User == null ||
!httpContext.User.Identities.Any(i => i.IsAuthenticated) ||
!await authService.AuthorizeAsync(httpContext.User, context, Policy))
{
context.Result = new ChallengeResult(Policy.ActiveAuthenticationSchemes.ToArray());
}
}
示例14: InteropSerializerCanReadNewTicket
public void InteropSerializerCanReadNewTicket()
{
var user = new ClaimsPrincipal();
var identity = new ClaimsIdentity("scheme");
identity.AddClaim(new Claim("Test", "Value"));
user.AddIdentity(identity);
var expires = DateTime.Today;
var issued = new DateTime(1979, 11, 11);
var properties = new Http.Authentication.AuthenticationProperties();
properties.IsPersistent = true;
properties.RedirectUri = "/redirect";
properties.Items["key"] = "value";
properties.ExpiresUtc = expires;
properties.IssuedUtc = issued;
var newTicket = new AuthenticationTicket(user, properties, "scheme");
var newSerializer = new TicketSerializer();
var bytes = newSerializer.Serialize(newTicket);
var interopSerializer = new AspNetTicketSerializer();
var interopTicket = interopSerializer.Deserialize(bytes);
Assert.NotNull(interopTicket);
var newIdentity = interopTicket.Identity;
Assert.NotNull(newIdentity);
Assert.Equal("scheme", newIdentity.AuthenticationType);
Assert.True(newIdentity.HasClaim(c => c.Type == "Test" && c.Value == "Value"));
Assert.NotNull(interopTicket.Properties);
Assert.True(interopTicket.Properties.IsPersistent);
Assert.Equal("/redirect", interopTicket.Properties.RedirectUri);
Assert.Equal("value", interopTicket.Properties.Dictionary["key"]);
Assert.Equal(expires, interopTicket.Properties.ExpiresUtc);
Assert.Equal(issued, interopTicket.Properties.IssuedUtc);
}
示例15: Should_Override_User_In_Owin_Environment
public void Should_Override_User_In_Owin_Environment()
{
//Given
var fakeTokenValidator = A.Fake<ITokenValidator>();
var secureuser = new ClaimsPrincipal();
var claimsIdentity = new ClaimsIdentity("Token");
claimsIdentity.AddClaim(new Claim("http://schemas.microsoft.com/ws/2008/06/identity/claims/role", "DumbUser"));
secureuser.AddIdentity(claimsIdentity);
A.CallTo(() => fakeTokenValidator.ValidateUser(A<string>.Ignored))
.Returns(secureuser);
var owinhttps = GetStatelessAuth(GetNextFunc(), tokenValidator: fakeTokenValidator);
//TODO Tidy on 3.8 Mono release
var overriddenUser = new ClaimsPrincipal();
var overriddenIdentity = new ClaimsIdentity("Token");
overriddenIdentity.AddClaim(new Claim("http://schemas.microsoft.com/ws/2008/06/identity/claims/role", "Administrator"));
overriddenUser.AddIdentity(overriddenIdentity);
var environment = new Dictionary<string, object>
{
{ "owin.RequestHeaders", new Dictionary<string, string[]>() { { "Authorization", new[] { "mysecuretoken" } } } },
{ "owin.RequestPath", "/" },
{ "owin.RequestMethod", "GET" },
{ ServerUser, overriddenUser }
};
//When
var task = owinhttps.Invoke(environment);
//Then
var user = environment[ServerUser] as ClaimsPrincipal;
//TODO Tidy on 3.8 Mono release
Assert.True(user.HasClaim(x => x.Type == "http://schemas.microsoft.com/ws/2008/06/identity/claims/role" && x.Value == "DumbUser"));
}