本文整理汇总了C#中System.Security.Claims.ClaimsIdentity类的典型用法代码示例。如果您正苦于以下问题:C# ClaimsIdentity类的具体用法?C# ClaimsIdentity怎么用?C# ClaimsIdentity使用的例子?那么恭喜您, 这里精选的类代码示例或许可以为您提供帮助。
ClaimsIdentity类属于System.Security.Claims命名空间,在下文中一共展示了ClaimsIdentity类的15个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的C#代码示例。
示例1: GrantResourceOwnerCredentials
/// <summary>
/// 验证用户名与密码 [Resource Owner Password Credentials Grant[username与password]|grant_type=password&username=irving&password=654321]
/// </summary>
/// <param name="context"></param>
/// <returns></returns>
public override async Task GrantResourceOwnerCredentials(OAuthGrantResourceOwnerCredentialsContext context)
{
context.OwinContext.Response.Headers.Add("Access-Control-Allow-Origin", new[] { "*" });
//validate user credentials (验证用户名与密码) should be stored securely (salted, hashed, iterated)
var userValid = await _accountService.ValidateUserNameAuthorizationPwdAsync(context.UserName, context.Password);
if (!userValid)
{
//context.Rejected();
context.SetError(AbpConstants.AccessDenied, AbpConstants.AccessDeniedErrorDescription);
return;
}
var claimsIdentity = new ClaimsIdentity(context.Options.AuthenticationType);
claimsIdentity.AddClaim(new Claim(ClaimTypes.Name, context.UserName));
var ticket = new AuthenticationTicket(claimsIdentity, new AuthenticationProperties());
context.Validated(ticket);
/*
//create identity
var claimsIdentity = new ClaimsIdentity(context.Options.AuthenticationType);
claimsIdentity.AddClaim(new Claim(ClaimTypes.Name, context.UserName));
claimsIdentity.AddClaim(new Claim("sub", context.UserName));
claimsIdentity.AddClaim(new Claim("role", "user"));
// create metadata to pass on to refresh token provider
var props = new AuthenticationProperties(new Dictionary<string, string>
{
{"as:client_id", context.ClientId }
});
var ticket = new AuthenticationTicket(claimsIdentity, props);
context.Validated(ticket);
*/
}
示例2: GrantResourceOwnerCredentials
public override async Task GrantResourceOwnerCredentials(OAuthGrantResourceOwnerCredentialsContext context)
{
// Try get the useraccount by provided username
var userAccount = _uow.UserAccountRepository.Get(context.UserName);
// If the useraccount was not found, reject the token request
if (userAccount == null)
{
context.Rejected();
return;
}
// If password is invalid, reject the token request
if (!PasswordHelper.Verify(userAccount.Password, userAccount.Salt, context.Password))
{
context.Rejected();
return;
}
// Create identity which will be included in the token
var identity = new ClaimsIdentity(context.Options.AuthenticationType);
// All claims added here will be written to the token. Thus claims should
// be added with moderation
identity.AddClaim(new Claim(ClaimTypes.Name, context.UserName));
identity.AddClaim(new Claim(ClaimTypes.Role, "administrator"));
// Validate the reqeust and return a token
context.Validated(identity);
}
示例3: GetUniqueIdentifierParameters
internal static IEnumerable<string> GetUniqueIdentifierParameters(ClaimsIdentity claimsIdentity)
{
var nameIdentifierClaim = claimsIdentity.FindFirst(claim =>
String.Equals(ClaimTypes.NameIdentifier,
claim.Type, StringComparison.Ordinal));
if (nameIdentifierClaim != null && !string.IsNullOrEmpty(nameIdentifierClaim.Value))
{
return new string[]
{
ClaimTypes.NameIdentifier,
nameIdentifierClaim.Value
};
}
// We Do not understand this claimsIdentity, fallback on serializing the entire claims Identity.
var claims = claimsIdentity.Claims.ToList();
claims.Sort((a, b) => string.Compare(a.Type, b.Type, StringComparison.Ordinal));
var identifierParameters = new List<string>();
foreach (var claim in claims)
{
identifierParameters.Add(claim.Type);
identifierParameters.Add(claim.Value);
}
return identifierParameters;
}
示例4: GrantResourceOwnerCredentials
public override async Task GrantResourceOwnerCredentials(OAuthGrantResourceOwnerCredentialsContext context)
{
// Allow CORS on the token middleware provider
context.OwinContext.Response.Headers.Add("Access-Control-Allow-Origin", new[] { "*" });
//TODO
// Usually this would be done via dependency injection
// But I haven't got it to work with the OWIN startup class yet
AppDBContext _ctx = new AppDBContext();
UserRepository _repo = new UserRepository(_ctx);
IdentityUser user = await _repo.FindUser(context.UserName, context.Password);
if (user == null)
{
context.SetError("invalid_grant", "The user name or password is incorrect.");
return;
}
var identity = new ClaimsIdentity(context.Options.AuthenticationType);
identity.AddClaim(new Claim("sub", context.UserName));
identity.AddClaim(new Claim("role", "user"));
context.Validated(identity);
}
示例5: ConfigureOAuth
public void ConfigureOAuth(IAppBuilder app)
{
app.UseOAuthBearerAuthentication(new OAuthBearerAuthenticationOptions());
app.UseOAuthAuthorizationServer(new OAuthAuthorizationServerOptions()
{
AllowInsecureHttp = true,
TokenEndpointPath = new PathString("/token"),
AccessTokenExpireTimeSpan = TimeSpan.FromMinutes(30),
Provider = new OAuthAuthorizationServerProvider
{
OnValidateClientAuthentication = async c=>c.Validated(),
OnGrantResourceOwnerCredentials = async c =>
{
using (var repo = new AuthRepository())
{
var user = await repo.FindUser(c.UserName, c.Password);
if (user == null)
{
c.Rejected();
throw new ApiException("User not existed or wrong password.");
}
}
var identity = new ClaimsIdentity(c.Options.AuthenticationType);
identity.AddClaims(new[] {new Claim(ClaimTypes.Name, c.UserName), new Claim(ClaimTypes.Role, "user")});
if (string.Equals(c.UserName, AppConfig.Manager, StringComparison.InvariantCultureIgnoreCase))
identity.AddClaims(new[] {new Claim(ClaimTypes.Name, c.UserName), new Claim(ClaimTypes.Role, "manager")});
c.Validated(identity);
}
},
});
}
示例6: GrantResourceOwnerCredentials
public override async Task GrantResourceOwnerCredentials(OAuthGrantResourceOwnerCredentialsContext context)
{
var user = userRepository.Get(w => w.UserName == context.UserName && w.Password == context.Password);
//var userManager = context.OwinContext.GetUserManager<ApplicationUserManager>();
//ApplicationUser user = await userManager.FindAsync(context.UserName, context.Password);
if (user == null)
{
context.SetError("invalid_grant", "The user name or password is incorrect.");
return;
}
ClaimsIdentity oAuthIdentity = new ClaimsIdentity(context.Options.AuthenticationType);
ClaimsIdentity cookiesIdentity = new ClaimsIdentity(context.Options.AuthenticationType);
oAuthIdentity.AddClaim(new Claim(ClaimTypes.Name, user.UserName));
if (user.Roles.Count() > 0)
{
oAuthIdentity.AddClaim(new Claim(ClaimTypes.Role, user.Roles.FirstOrDefault().Name));
}
//ClaimsIdentity oAuthIdentity = await user.GenerateUserIdentityAsync(userManager,
// OAuthDefaults.AuthenticationType);
//ClaimsIdentity cookiesIdentity = await user.GenerateUserIdentityAsync(userManager,
// CookieAuthenticationDefaults.AuthenticationType);
AuthenticationProperties properties = CreateProperties(user.UserName);
AuthenticationTicket ticket = new AuthenticationTicket(oAuthIdentity, properties);
context.Validated(ticket);
context.Request.Context.Authentication.SignIn(cookiesIdentity);
}
示例7: Login
public ActionResult Login(LoginViewModel model, string returnUrl)
{
if (!ModelState.IsValid)
{
return View(model);
}
var data = new Data();
var users = data.users();
if (users.Any(p => p.user == model.UserName && p.password == model.Password))
{
var identity = new ClaimsIdentity(new[] { new Claim(ClaimTypes.Name, model.UserName),}, DefaultAuthenticationTypes.ApplicationCookie);
Authentication.SignIn(new AuthenticationProperties
{
IsPersistent = model.RememberMe
}, identity);
return RedirectToAction("Index", "Home");
}
else
{
ModelState.AddModelError("", "Invalid login attempt.");
return View(model);
}
}
开发者ID:amshekar,项目名称:sb-admin-bootstrap-template-asp-mvc-authentication,代码行数:26,代码来源:AccountController.cs
示例8: Unauthorized
public async Task<IActionResult> Unauthorized(string returnUrl = null)
{
const string Issuer = "https://contoso.com";
List<Claim> claims = new List<Claim>();
claims.Add(new Claim(ClaimTypes.Name, "barry", ClaimValueTypes.String, Issuer));
claims.Add(new Claim(ClaimTypes.Role, "Administrator", ClaimValueTypes.String, Issuer));
claims.Add(new Claim("EmployeeId", "123", ClaimValueTypes.String, Issuer));
claims.Add(new Claim(ClaimTypes.DateOfBirth, "1970-06-08", ClaimValueTypes.Date));
claims.Add(new Claim("BadgeNumber", "123456", ClaimValueTypes.String, Issuer));
//claims.Add(new Claim("TemporaryBadgeExpiry", DateTime.Now.AddDays(1).ToString(), ClaimValueTypes.String, Issuer));
//claims.Add(new Claim("TemporaryBadgeExpiry", DateTime.Now.AddDays(-1).ToString(), ClaimValueTypes.String, Issuer));
var userIdentity = new ClaimsIdentity("SuperSecureLogin");
userIdentity.AddClaims(claims);
var userPrincipal = new ClaimsPrincipal(userIdentity);
await HttpContext.Authentication.SignInAsync("Cookie", userPrincipal,
new AuthenticationProperties
{
ExpiresUtc = DateTime.UtcNow.AddMinutes(20),
IsPersistent = false,
AllowRefresh = false
});
return RedirectToLocal(returnUrl);
}
示例9: Login
public ActionResult Login(LoginModel model, string returnUrl)
{
if (model.UserName != model.Password) return View();
var claims = new List<Claim>
{
new Claim(ClaimTypes.Name, model.UserName),
new Claim(ClaimTypes.Email, "[email protected]"),
new Claim(ClaimTypes.Role, "Administrator"),
new Claim("Data", "Read"),
};
var id = new ClaimsIdentity(claims, CookieAuthenticationDefaults.AuthenticationType);
var authenticationManager = Request.GetOwinContext().Authentication;
var authProperties = new AuthenticationProperties { IsPersistent = true };
authenticationManager.SignIn(authProperties, id);
if (Url.IsLocalUrl(returnUrl))
{
return Redirect(returnUrl);
}
return RedirectToAction("Index", "Home");
}
示例10: AuthenticateAsync
/// <summary>
/// Returns a ClaimsPrincipal object with the NameIdentifier and Name claims, if the request can be
/// successfully authenticated based on query string parameter bewit or HTTP Authorization header (hawk scheme).
/// </summary>
public async Task<ClaimsPrincipal> AuthenticateAsync()
{
string bewit;
bool isBewit = Bewit.TryGetBewit(this.request, out bewit);
var authentication = isBewit ?
Bewit.AuthenticateAsync(bewit, now, request, credentialsFunc) :
HawkSchemeHeader.AuthenticateAsync(now, request, credentialsFunc);
this.result = await authentication;
if (result.IsAuthentic)
{
// At this point, authentication is successful but make sure the request parts match what is in the
// application specific data 'ext' parameter by invoking the callback passing in the request object and 'ext'.
// The application specific data is considered verified, if the callback is not set or it returns true.
bool isAppSpecificDataVerified = this.verificationCallback == null ||
this.verificationCallback(request, result.ApplicationSpecificData);
if (isAppSpecificDataVerified)
{
// Set the flag so that Server-Authorization header is not sent for bewit requests.
this.isBewitRequest = isBewit;
var idClaim = new Claim(ClaimTypes.NameIdentifier, result.Credential.Id);
var nameClaim = new Claim(ClaimTypes.Name, result.Credential.User);
var identity = new ClaimsIdentity(new[] { idClaim, nameClaim }, HawkConstants.Scheme);
return new ClaimsPrincipal(identity);
}
}
return null;
}
示例11: GrantResourceOwnerCredentials
public override async Task GrantResourceOwnerCredentials(OAuthGrantResourceOwnerCredentialsContext context)
{
context.OwinContext.Response.Headers.Add("Access-Control-Allow-Origin", new[] {"*"});
var identity = new ClaimsIdentity(DefaultAuthenticationTypes.ApplicationCookie);
var userManager = Startup.UserManagerFactory();
var user = await userManager.FindAsync(context.UserName, context.Password);
if (user == null)
{
context.SetError("invalid_grant", "The user name or password is incorrect.");
return;
}
identity.AddClaim(new Claim("id", user.StaffId.ToString()));
identity.AddClaim(new Claim(ClaimTypes.Name, user.UserName));
var listOfRoles = await userManager.GetRolesAsync(user.Id);
if (listOfRoles.Contains("admin"))
{
identity.AddClaim(new Claim("role", "admin"));
}
else
{
identity.AddClaim(new Claim("role", "user"));
}
context.Validated(identity);
var ctx = HttpContext.Current.GetOwinContext();
var authManager = ctx.Authentication;
authManager.SignIn(identity);
}
示例12: GrantResourceOwnerCredentials
public override async Task GrantResourceOwnerCredentials(OAuthGrantResourceOwnerCredentialsContext context)
{
context.OwinContext.Response.Headers.Add("Access-Control-Allow-Origin", new[] { "*" });
using (var projectContext = new ProjectContext())
{
using (var unitOfWork = new UnitOfWork(projectContext))
{
IdentityUser user = await unitOfWork.Users.FindUser(context.UserName, context.Password);
if (user == null)
{
context.SetError("invalid_grant", "The user name or password is incorrect.");
return;
}
}
}
var identity = new ClaimsIdentity(context.Options.AuthenticationType);
identity.AddClaim(new Claim("sub", context.UserName));
identity.AddClaim(new Claim("role", "user"));
context.Validated(identity);
}
示例13: GrantResourceOwnerCredentials
public override async Task GrantResourceOwnerCredentials(OAuthGrantResourceOwnerCredentialsContext context)
{
context.OwinContext.Response.Headers.Add("Access-Control-Allow-Origin", new[] { "*" });
List<string> roles = new List<string>();
IdentityUser user = new IdentityUser();
using (AuthRepository _repo = new AuthRepository())
{
user = await _repo.FindUser(context.UserName, context.Password);
if (user == null)
{
context.SetError("invalid_grant", "Потребителското име или паролата не са верни.");
return;
}
else
{
roles = await _repo.GetRolesForUser(user.Id);
}
}
var identity = new ClaimsIdentity(context.Options.AuthenticationType);
identity.AddClaim(new Claim("sub", context.UserName));
foreach (var item in roles)
{
identity.AddClaim(new Claim(ClaimTypes.Role, item));
}
context.Validated(identity);
context.Response.Headers.Add("UserRoles", roles.ToArray());
}
示例14: ValidateResponseAndSignIn
private void ValidateResponseAndSignIn(TokenResponse response)
{
if (!string.IsNullOrWhiteSpace(response.IdentityToken))
{
var tokenClaims = ValidateToken(response.IdentityToken);
var claims = new List<Claim>(from c in tokenClaims
where c.Type != "iss" &&
c.Type != "aud" &&
c.Type != "nbf" &&
c.Type != "exp" &&
c.Type != "iat" &&
c.Type != "amr" &&
c.Type != "idp"
select c);
if (!string.IsNullOrWhiteSpace(response.AccessToken))
{
claims.Add(new Claim("access_token", response.AccessToken));
claims.Add(new Claim("expires_at", (DateTime.UtcNow.ToEpochTime() + response.ExpiresIn).ToDateTimeFromEpoch().ToString()));
}
if (!string.IsNullOrWhiteSpace(response.RefreshToken))
{
claims.Add(new Claim("refresh_token", response.RefreshToken));
}
var id = new ClaimsIdentity(claims, "Cookies");
Request.GetOwinContext().Authentication.SignIn(id);
}
}
示例15: Authenticate
public string Authenticate(string Email, string Password)
{
AuthenticateService service = new AuthenticateService(_container);
if (!string.IsNullOrEmpty(Email) && !string.IsNullOrEmpty(Password))
{
var user = service.Authenticate(Email, Password);
if (user != null)
{
var authentication = Request.GetOwinContext().Authentication;
var identity = new ClaimsIdentity("Bearer");
identity.AddClaim(new Claim("name", user.Name));
identity.AddClaim(new Claim("email", user.Email));
identity.AddClaim(new Claim("userid", user.Id.ToString()));
identity.AddClaim(new Claim("usertype", user.UserType.ToString()));
identity.AddClaim(new Claim("companyid", user.Company.Id.ToString()));
identity.AddClaim(new Claim("companyname", user.Company.Name));
AuthenticationTicket ticket = new AuthenticationTicket(identity, new AuthenticationProperties());
var currentUtc = new Microsoft.Owin.Infrastructure.SystemClock().UtcNow;
ticket.Properties.IssuedUtc = currentUtc;
ticket.Properties.ExpiresUtc = currentUtc.Add(TimeSpan.FromMinutes(30));
var token = Startup.OAuthServerOptions.AccessTokenFormat.Protect(ticket);
authentication.SignIn(identity);
return token;
}
}
return "false";
}