本文整理汇总了C#中System.Security.Claims.ClaimsPrincipal类的典型用法代码示例。如果您正苦于以下问题:C# ClaimsPrincipal类的具体用法?C# ClaimsPrincipal怎么用?C# ClaimsPrincipal使用的例子?那么恭喜您, 这里精选的类代码示例或许可以为您提供帮助。
ClaimsPrincipal类属于System.Security.Claims命名空间,在下文中一共展示了ClaimsPrincipal类的15个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的C#代码示例。
示例1: PostLogin
public string PostLogin(FormDataCollection body)
{
string username = body.Get("username");
string password = body.Get("password");
using(var session = store.OpenSession())
{
var profile = session.Load<Profile>("profiles/" + username);
if(profile.Password == password)
{
var defaultPrincipal = new ClaimsPrincipal(
new ClaimsIdentity(new[] {new Claim(MyClaimTypes.ProfileKey, profile.Id)},
"Application" // this is important. if it's null or empty, IsAuthenticated will be false
));
var principal = FederatedAuthentication.FederationConfiguration.IdentityConfiguration.
ClaimsAuthenticationManager.Authenticate(
Request.RequestUri.AbsoluteUri, // this, or any other string can be available
// to your ClaimsAuthenticationManager
defaultPrincipal);
AuthenticationManager.EstablishSession(principal);
return "login ok";
}
return "login failed";
}
}
示例2: CreateCodeFlowResponseAsync
public async Task<AuthorizeResponse> CreateCodeFlowResponseAsync(ValidatedAuthorizeRequest request, ClaimsPrincipal subject)
{
var code = new AuthorizationCode
{
Client = request.Client,
Subject = subject,
IsOpenId = request.IsOpenIdRequest,
RequestedScopes = request.ValidatedScopes.GrantedScopes,
RedirectUri = request.RedirectUri,
WasConsentShown = request.WasConsentShown,
RefreshTokenLifetime = request.Client.RefreshTokenLifetime
};
// store id token and access token and return authorization code
var id = Guid.NewGuid().ToString("N");
await _authorizationCodes.StoreAsync(id, code);
return new AuthorizeResponse
{
RedirectUri = request.RedirectUri,
Code = id,
State = request.State
};
}
示例3: UpdateConsentAsync
public async Task UpdateConsentAsync(Client client, ClaimsPrincipal user, IEnumerable<string> scopes)
{
if (client == null) throw new ArgumentNullException("client");
if (user == null) throw new ArgumentNullException("user");
if (client.AllowRememberConsent)
{
var subject = user.GetSubjectId();
var clientId = client.ClientId;
if (scopes != null && scopes.Any())
{
var consent = new Consent
{
Subject = subject,
ClientId = clientId,
Scopes = scopes
};
await _store.UpdateAsync(consent);
}
else
{
await _store.RevokeAsync(subject, clientId);
}
}
}
示例4: Authenticate
public override ClaimsPrincipal Authenticate(string resourceName, ClaimsPrincipal incomingPrincipal)
{
if (incomingPrincipal != null && incomingPrincipal.Identity.IsAuthenticated)
{
// Get the claims required to make further Graph API enquiries about the user
//Claim nameIdClaim = incomingPrincipal.FindFirst(NameIdClaim);
//if (nameIdClaim == null)
//{
// throw new NotSupportedException("Name claim not available, role authentication is not supported");
//}
Claim nameClaim = incomingPrincipal.FindFirst(NameClaim);
if (nameClaim == null)
{
throw new NotSupportedException("Name claim not available, role authentication is not supported");
}
string userName = nameClaim.Value;
//string currentUserObjectId = objectIdentifierClaim.Value;
//load up the roles as RoleClaims
TableUser user = new TableUser(userName);
Task<IList<string>> t = _userStore.GetRolesAsync(user);
t.RunSynchronously();
IList<string> currentRoles = t.Result;
foreach (string role in currentRoles)
{
((ClaimsIdentity)incomingPrincipal.Identity).AddClaim(new Claim(ClaimTypes.Role, role, ClaimValueTypes.String, _issuer));
}
}
return base.Authenticate(resourceName, incomingPrincipal);
}
开发者ID:4deeptech,项目名称:AccidentalFish.AspNet.Identity.Azure,代码行数:31,代码来源:AzureTableRoleClaimsAuthenticationManager.cs
示例5: Authorize
public bool Authorize(ClaimsPrincipal user, object resource, string policyName)
{
var policy = _options.GetPolicy(policyName);
return (policy == null)
? false
: this.Authorize(user, resource, policy);
}
示例6: Check_PoliciesCanMutateUsersClaims
public void Check_PoliciesCanMutateUsersClaims()
{
// Arrange
var user = new ClaimsPrincipal(
new ClaimsIdentity(new Claim[0], "Basic")
);
var policies = new IAuthorizationPolicy[] {
new FakePolicy() {
ApplyAsyncAction = (context) => {
if (!context.Authorized)
{
context.UserClaims.Add(new Claim("Permission", "CanDeleteComments"));
context.Retry = true;
}
}
}
};
var authorizationService = new DefaultAuthorizationService(policies);
// Act
var allowed = authorizationService.Authorize(new Claim("Permission", "CanDeleteComments"), user);
// Assert
Assert.True(allowed);
}
示例7: 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;
}
示例8: Validate
public ClaimsPrincipal Validate(string userName, string password)
{
var binding = new UserNameWSTrustBinding(SecurityMode.TransportWithMessageCredential);
var credentials = new ClientCredentials();
credentials.UserName.UserName = userName;
credentials.UserName.Password = password;
GenericXmlSecurityToken genericToken;
genericToken = WSTrustClient.Issue(
new EndpointAddress(_address),
new EndpointAddress(_realm),
binding,
credentials) as GenericXmlSecurityToken;
var config = new SecurityTokenHandlerConfiguration();
config.AudienceRestriction.AllowedAudienceUris.Add(new Uri(_realm));
config.CertificateValidationMode = X509CertificateValidationMode.None;
config.CertificateValidator = X509CertificateValidator.None;
var registry = new ConfigurationBasedIssuerNameRegistry();
registry.AddTrustedIssuer(_issuerThumbprint, _address);
config.IssuerNameRegistry = registry;
var handler = SecurityTokenHandlerCollection.CreateDefaultSecurityTokenHandlerCollection(config);
ClaimsPrincipal principal;
var token = genericToken.ToSecurityToken();
principal = new ClaimsPrincipal(handler.ValidateToken(token));
Tracing.Information("Successfully requested token for user via WS-Trust");
return FederatedAuthentication.FederationConfiguration.IdentityConfiguration.ClaimsAuthenticationManager.Authenticate("ResourceOwnerPasswordValidation", principal);
}
开发者ID:Excelsior-Charles,项目名称:Thinktecture.AuthorizationServer,代码行数:33,代码来源:WSTrustResourceOwnerCredentialValidation.cs
示例9: GetClaimsPrincipalWithNoSub
internal static void GetClaimsPrincipalWithNoSub()
{
List<Claim> claims = new List<Claim>();
ClaimsPrincipal principal = new ClaimsPrincipal(new ClaimsIdentity(claims, "Bearer", "name", "role"));
ClaimsPrincipal.Current.AddIdentity(principal.Identity as ClaimsIdentity);
ClaimsPrincipal.ClaimsPrincipalSelector = () => principal;
}
示例10: GetCurrentUserRegistrationReferenceAsync
/// <summary>
/// Extracts the User details accessing the service as a unique id in the form
/// of "{authprovider}:{uniqueId}" using ProviderCrednetials for the logged
/// in user.
/// </summary>
/// <param name="principal">The principal accessing the service.</param>
/// <param name="request">The HttpRequest used to access the service.</param>
/// <returns>The unique user id.</returns>
public async Task<string> GetCurrentUserRegistrationReferenceAsync(ClaimsPrincipal principal, HttpRequestMessage request)
{
string provider = principal?.FindFirst("http://schemas.microsoft.com/identity/claims/identityprovider").Value;
ProviderCredentials creds = null;
if (string.Equals(provider, "facebook", StringComparison.OrdinalIgnoreCase))
{
creds = await principal.GetAppServiceIdentityAsync<FacebookCredentials>(request);
}
else if (string.Equals(provider, "google", StringComparison.OrdinalIgnoreCase))
{
creds = await principal.GetAppServiceIdentityAsync<GoogleCredentials>(request);
}
else if (string.Equals(provider, "twitter", StringComparison.OrdinalIgnoreCase))
{
creds = await principal.GetAppServiceIdentityAsync<TwitterCredentials>(request);
}
else if (string.Equals(provider, "microsoftaccount", StringComparison.OrdinalIgnoreCase))
{
creds = await principal.GetAppServiceIdentityAsync<MicrosoftAccountCredentials>(request);
}
if (creds == null)
{
throw ServiceExceptions.UserNullException();
}
// Format user details in the desired form of {authprovider}:{uniqueId}
string authProvider = creds.Provider;
string uniqueId = creds.UserClaims.FirstOrDefault(c => c.Type.Equals(ClaimTypes.NameIdentifier))?.Value;
var uniqueUserName = $"{authProvider}:{uniqueId}";
return uniqueUserName;
}
开发者ID:Microsoft,项目名称:Appsample-Photosharing,代码行数:42,代码来源:DefaultUserRegistrationReferenceProvider.cs
示例11: GetIdentityTokenClaimsAsync
public virtual async Task<IEnumerable<Claim>> GetIdentityTokenClaimsAsync(ClaimsPrincipal subject, Client client, IEnumerable<Scope> scopes, bool includeAllIdentityClaims, NameValueCollection request)
{
Logger.Debug("Getting claims for identity token");
List<Claim> outputClaims = new List<Claim>(GetStandardSubjectClaims(subject));
var additionalClaims = new List<string>();
// fetch all identity claims that need to go into the id token
foreach (var scope in scopes)
{
if (scope.IsOpenIdScope)
{
foreach (var scopeClaim in scope.Claims)
{
if (includeAllIdentityClaims || scopeClaim.AlwaysIncludeInIdToken)
{
additionalClaims.Add(scopeClaim.Name);
}
}
}
}
if (additionalClaims.Count > 0)
{
var claims = await _users.GetProfileDataAsync(subject.GetSubjectId(), additionalClaims);
if (claims != null)
{
outputClaims.AddRange(claims);
}
}
return outputClaims;
}
示例12: CheckAccessCore
/// <summary>
/// Checks authorization for the given operation context based on default policy evaluation.
/// </summary>
/// <param name="operationContext">The <see cref="T:System.ServiceModel.OperationContext" /> for the current authorization request.</param>
/// <returns>
/// true if access is granted; otherwise, false. The default is true.
/// </returns>
protected override bool CheckAccessCore(OperationContext operationContext)
{
var retVal = base.CheckAccessCore(operationContext);
SimpleWebToken token = null;
if (retVal)
{
// Extract authorization data.
var requestMessage = operationContext.RequestContext.RequestMessage;
var httpDetails = requestMessage.Properties[HttpRequestMessageProperty.Name] as HttpRequestMessageProperty;
var requestUri = WebOperationContext.Current != null && WebOperationContext.Current.IncomingRequest.UriTemplateMatch != null ? WebOperationContext.Current.IncomingRequest.UriTemplateMatch.BaseUri : requestMessage.Headers.To;
token = ReadAuthToken(httpDetails);
retVal = token != null && IsValidToken(token, requestUri);
}
var securityContext = ServiceSecurityContext.Anonymous;
ClaimsPrincipal principal = new GenericPrincipal(new GenericIdentity(String.Empty), new string[0]);
var identity = principal.Identity;
if (retVal)
{
var claims = token.Claims.Select(keyValuePair => new Claim(keyValuePair.Key, keyValuePair.Value));
identity = new ClaimsIdentity(claims, "OAUTH-SWT");
principal = new ClaimsPrincipal(identity);
Thread.CurrentPrincipal = principal;
}
securityContext.AuthorizationContext.Properties["Principal"] = principal;
securityContext.AuthorizationContext.Properties["Identities"] = new List<IIdentity> { identity };
operationContext.IncomingMessageProperties.Security.ServiceSecurityContext = securityContext;
return retVal;
//return true;
}
示例13: Login
public async Task<IActionResult> Login(LoginViewModel model, string returnUrl = null)
{
if (User.Identity.IsAuthenticated)
{
return RedirectToAction(nameof(HomeController.Index), "Home");
}
ViewData["ReturnUrl"] = returnUrl;
if (!ModelState.IsValid || model.UserName != model.Password) {
ModelState.AddModelError("", "Invalid login attempt.");
return View(model);
}
var claims = new List<Claim>() {
new Claim(ClaimTypes.Name, model.UserName),
new Claim(ClaimTypes.Role, "User"),
new Claim(ClaimTypes.Country, "USA" ),
new Claim("Event", "South Florida Code Camp 2016")
};
if (model.UserName.Equals("admin", StringComparison.OrdinalIgnoreCase)) {
claims.Add(new Claim(ClaimTypes.Role, "Administrator"));
}
var identity = new ClaimsIdentity(claims, "local", ClaimTypes.Name, ClaimTypes.Role);
var principal = new ClaimsPrincipal(identity);
await HttpContext.Authentication.SignInAsync("Cookies", principal);
return RedirectToLocal(returnUrl);
}
示例14: Configuration
public void Configuration(IAppBuilder app)
{
// token validation
app.UseIdentityServerBearerTokenAuthentication(new IdentityServerBearerTokenAuthenticationOptions
{
Authority = Constants.IdentityServerUri,
RequiredScopes = new[] { "apiAccess" }
});
// add app local claims per request
app.UseClaimsTransformation(incoming =>
{
// either add claims to incoming, or create new principal
var appPrincipal = new ClaimsPrincipal(incoming);
incoming.Identities.First().AddClaim(new Claim("appSpecific", "some_value"));
return Task.FromResult(appPrincipal);
});
app.UseCors(CorsOptions.AllowAll);
var config = new HttpConfiguration();
config.MapHttpAttributeRoutes();
// web api configuration
app.UseWebApi(config);
}
示例15: TryIssueToken
public bool TryIssueToken(EndpointReference appliesTo, ClaimsPrincipal principal, string tokenType, out TokenResponse response)
{
SecurityToken token = null;
response = new TokenResponse { TokenType = tokenType };
var result = TryIssueToken(appliesTo, principal, tokenType, out token);
if (result == false)
{
return false;
}
var ts = token.ValidTo.Subtract(DateTime.UtcNow);
response.ExpiresIn = (int)ts.TotalSeconds;
if (tokenType == TokenTypes.JsonWebToken || tokenType == TokenTypes.SimpleWebToken)
{
var handler = FederatedAuthentication.FederationConfiguration.IdentityConfiguration.SecurityTokenHandlers[tokenType];
response.AccessToken = handler.WriteToken(token);
}
else
{
var handler = FederatedAuthentication.FederationConfiguration.IdentityConfiguration.SecurityTokenHandlers;
var sb = new StringBuilder(128);
handler.WriteToken(new XmlTextWriter(new StringWriter(sb)), token);
response.AccessToken = sb.ToString();
}
return result;
}