/// <summary> /// 资源归属人请求时的验证,授权类型password /// </summary> /// <param name="context"></param> /// <returns></returns> public override async Task GrantResourceOwnerCredentials(OAuthGrantResourceOwnerCredentialsContext context) { var userService = context.HttpContext.ApplicationServices.GetService <UserService>(); var roleService = context.HttpContext.ApplicationServices.GetService <RoleService>(); var optionsMgr = context.HttpContext.ApplicationServices.GetService <IOptions <IdentityOptions> >(); User user = await userService.FindByNameAsync(context.UserName); if (user == null) { context.SetError("invalid_grant", Resources.Error_NotFounUserName); return; } if (!await userService.CheckPasswordAsync(user, context.Password)) { context.SetError("invalid_grant", Resources.Error_NotFounPassword); return; } UserClaimsPrincipalFactory <User, Role> claimsFactory = new UserClaimsPrincipalFactory <User, Role>(userService, roleService, optionsMgr); var principal = await claimsFactory.CreateAsync(user); AuthenticationProperties properties = CreateProperties(user.UserName); AuthenticationTicket ticket = new AuthenticationTicket(principal, properties, OAuthDefaults.AuthenticationType); context.Validated(ticket); }
private async Task <PlannerController> SetupPlannerController(PlannerService service) { ctxDb.Roles.Add(new IdentityRole { Name = "Student", NormalizedName = "STUDENT" }); ctxDb.SaveChanges(); AccountService accService = new AccountService(userManager, signInManager); var user = await accService.RegisterUser(new RegisterViewModel { RNum = "r0000001", Email = "*****@*****.**", Name = "Thomas", SurName = "Claes", Password = "******", ConfirmPassword = "******", GeboorteDatum = new DateTime(1998, 9, 21) }); IOptions <IdentityOptions> options = Options.Create <IdentityOptions>(new IdentityOptions { }); UserClaimsPrincipalFactory <ApplicationUser> userClaimFactory = new UserClaimsPrincipalFactory <ApplicationUser>(userManager, options); var claim = userClaimFactory.CreateAsync(user).Result; var httpContext = new Mock <HttpContext>(); httpContext.Setup(x => x.User).Returns(claim); var context = new ControllerContext(new ActionContext(httpContext.Object, new RouteData(), new ControllerActionDescriptor())); return(new PlannerController(service, userManager, signInManager) { ControllerContext = context, TempData = new TempDataDictionary(httpContext.Object, Mock.Of <ITempDataProvider>()) }); }
public async Task <UserAndIdentity> GetImpersonatedUserAndIdentity(string impersonationToken) { var cacheItem = await _cacheManager.GetImpersonationCache().GetOrDefaultAsync(impersonationToken); if (cacheItem == null) { throw new UserFriendlyException(L("ImpersonationTokenErrorMessage")); } CheckCurrentTenant(cacheItem.TargetTenantId); //Get the user from tenant var user = await _userManager.FindByIdAsync(cacheItem.TargetUserId.ToString()); //Create identity var identity = (ClaimsIdentity)(await _principalFactory.CreateAsync(user)).Identity; if (!cacheItem.IsBackToImpersonator) { //Add claims for audit logging if (cacheItem.ImpersonatorTenantId.HasValue) { identity.AddClaim(new Claim(AbpClaimTypes.ImpersonatorTenantId, cacheItem.ImpersonatorTenantId.Value.ToString(CultureInfo.InvariantCulture))); } identity.AddClaim(new Claim(AbpClaimTypes.ImpersonatorUserId, cacheItem.ImpersonatorUserId.ToString(CultureInfo.InvariantCulture))); } //Remove the cache item to prevent re-use await _cacheManager.GetImpersonationCache().RemoveAsync(impersonationToken); return(new UserAndIdentity(user, identity)); }
public async Task SetUser(ApplicationUser user) { var factory = new UserClaimsPrincipalFactory <ApplicationUser, ApplicationRole>(UserManager, RoleManager, IdentityOptions); HttpContext.User = await factory.CreateAsync(user); }
private async Task LoginAdminAsync() { var user = await _userManager.GetAdminAsync(); var principal = await _userClaimsPrincipalFactory.CreateAsync(user); await _signInManager.SignOutAsync(); await _signInManager.SignInAsync(principal.Identity as ClaimsIdentity, false); }
public async Task CreateIdentityNullChecks() { var userManager = MockHelpers.MockUserManager<TestUser>().Object; var roleManager = MockHelpers.MockRoleManager<TestRole>().Object; var options = new Mock<IOptions<IdentityOptions>>(); Assert.Throws<ArgumentNullException>("optionsAccessor", () => new UserClaimsPrincipalFactory<TestUser, TestRole>(userManager, roleManager, options.Object)); var identityOptions = new IdentityOptions(); options.Setup(a => a.Options).Returns(identityOptions); var factory = new UserClaimsPrincipalFactory<TestUser, TestRole>(userManager, roleManager, options.Object); await Assert.ThrowsAsync<ArgumentNullException>("user", async () => await factory.CreateAsync(null)); }
public async Task SaveAsync(IdentitySecurityLogContext context) { Action <SecurityLogInfo> securityLogAction = securityLog => { securityLog.Identity = context.Identity; securityLog.Action = context.Action; if (!context.UserName.IsNullOrWhiteSpace()) { securityLog.UserName = context.UserName; } if (!context.ClientId.IsNullOrWhiteSpace()) { securityLog.ClientId = context.ClientId; } foreach (var property in context.ExtraProperties) { securityLog.ExtraProperties[property.Key] = property.Value; } }; if (CurrentUser.IsAuthenticated) { await SecurityLogManager.SaveAsync(securityLogAction); } else { if (context.UserName.IsNullOrWhiteSpace()) { await SecurityLogManager.SaveAsync(securityLogAction); } else { var user = await UserManager.FindByNameAsync(context.UserName); if (user != null) { using (CurrentPrincipalAccessor.Change(await UserClaimsPrincipalFactory.CreateAsync(user))) { await SecurityLogManager.SaveAsync(securityLogAction); } } else { await SecurityLogManager.SaveAsync(securityLogAction); } } } }
public async Task CreateIdentityNullChecks() { var userManager = MockHelpers.MockUserManager <PocoUser>().Object; var roleManager = MockHelpers.MockRoleManager <PocoRole>().Object; var options = new Mock <IOptions <IdentityOptions> >(); Assert.Throws <ArgumentNullException>("optionsAccessor", () => new UserClaimsPrincipalFactory <PocoUser, PocoRole>(userManager, roleManager, options.Object)); var identityOptions = new IdentityOptions(); options.Setup(a => a.Value).Returns(identityOptions); var factory = new UserClaimsPrincipalFactory <PocoUser, PocoRole>(userManager, roleManager, options.Object); await Assert.ThrowsAsync <ArgumentNullException>("user", async() => await factory.CreateAsync(null)); }
/// <summary> /// 登录 /// </summary> /// <param name="input">The parameters.</param> /// <returns>Task<ClaimsPrincipal>.</returns> public async Task <ClaimsPrincipal> SignInAsync(SignInDto input) { await IdentityOptions.SetAsync(); var user = await UserManager.FindByNameAsync(input.UserName); if (user != null) { var check = await UserManager.CheckPasswordAsync(user, input.Passowrd); if (check) { return(await UserClaimsPrincipalFactory.CreateAsync(user)); } } throw new UserFriendlyException("用户名或密码错误"); }
private async Task <ClaimsIdentity> GetClaimsIdentityFromCache(User user, ImpersonationCacheItem cacheItem) { var identity = (ClaimsIdentity)(await _principalFactory.CreateAsync(user)).Identity; if (!cacheItem.IsBackToImpersonator) { //Add claims for audit logging if (cacheItem.ImpersonatorTenantId.HasValue) { identity.AddClaim(new Claim(AbpClaimTypes.ImpersonatorTenantId, cacheItem.ImpersonatorTenantId.Value.ToString(CultureInfo.InvariantCulture))); } identity.AddClaim(new Claim(AbpClaimTypes.ImpersonatorUserId, cacheItem.ImpersonatorUserId.ToString(CultureInfo.InvariantCulture))); } return(identity); }
public async Task <ClaimsPrincipal> CreateAsync(User user) { var defaultPrincipal = await defaultFactory.CreateAsync(user); var identity = defaultPrincipal.Identities.Single(); var role = dbContext.Roles .SingleOrDefault(rl => rl.Users.Any(usr => usr.Id == user.Id)); if (role != null) { var roleClaim = new Claim(ClaimTypes.Role, role.Id); identity.AddClaim(roleClaim); } return(defaultPrincipal); }
public async Task <IActionResult> LoginCallback() { var op = "oD4-6t6tF6OBi05z3XfssyWlWB28"; var ci = "vuejsclient"; var code = Request.Query["code"]; var returnUrl = Request.QueryString.Value.Replace("?returnUrl=", "").UrlDecode(); var state = Request.Query["state"]; // var result = OAuthApi.GetAccessToken(WxOpenAppId, WxOpenAppSecret, code); var user = _userService.GetUserByOpenId(op); var f = new UserClaimsPrincipalFactory <User>(_userManager, _options); var claims = await f.CreateAsync(user); await _signInManager.SignInAsync(user, true); return(Redirect(returnUrl)); }
public async Task <SignInResult> LoginAsync(HubCallerContext context, string login, string password) { var user = await _userManager.FindByNameAsync(login); if (user == null) { user = await _userManager.FindByEmailAsync(login); } if (user == null) { return(SignInResult.Failed); } var result = await _signInManager.CheckPasswordSignInAsync(user, password, lockoutOnFailure : false); if (result == SignInResult.Success) { var principal = await _claimsPrincipalFactory.CreateAsync(user); _users[context.ConnectionId] = principal; SetUser(context, principal); } return(result); }
private async Task <UserAndIdentity> GetUserAndIdentity(ImpersonationCacheItem cacheItem, string impersonationToken) { var user = await _userManager.FindByIdAsync(cacheItem.TargetUserId.ToString()); //Create identity var identity = (ClaimsIdentity)(await _principalFactory.CreateAsync(user)).Identity; if (!cacheItem.IsBackToImpersonator) { //Add claims for audit logging if (cacheItem.ImpersonatorTenantId.HasValue) { identity.AddClaim(new Claim(AbpClaimTypes.ImpersonatorTenantId, cacheItem.ImpersonatorTenantId.Value.ToString(CultureInfo.InvariantCulture))); } identity.AddClaim(new Claim(AbpClaimTypes.ImpersonatorUserId, cacheItem.ImpersonatorUserId.ToString(CultureInfo.InvariantCulture))); } //Remove the cache item to prevent re-use await _cacheManager.GetImpersonationCache().RemoveAsync(impersonationToken); return(new UserAndIdentity(user, identity)); }
public override async Task <AuthenticationState> GetAuthenticationStateAsync() { using var scope = _scopeFactory.CreateScope(); var userManager = scope.ServiceProvider.GetService <UserManager <TUser> >(); var state = base.GetAuthenticationStateAsync().Result; var user = await userManager !.GetUserAsync(state.User); AuthenticationState result = new AuthenticationState(new ClaimsPrincipal(new ClaimsIdentity())); if (user != null) { var roles = await userManager !.GetRolesAsync(user); var principalFactory = new UserClaimsPrincipalFactory <TUser>(userManager, new OptionsWrapper <IdentityOptions>(_options)); var principal = await principalFactory.CreateAsync(user); var claimsPrincipal = new ClaimsPrincipal(new ClaimsIdentity(principal.Identity, roles.Select(role => new Claim(ClaimTypes.Role, role)))); result = new AuthenticationState(claimsPrincipal); } NotifyAuthenticationStateChanged(Task.FromResult(result)); return(result); }
protected virtual async Task <JKLoginResult <TUser, TUserLogin, TUserClaim, TUserToken> > CreateLoginResultAsync(TUser user) { if (!user.IsActive) { return(new JKLoginResult <TUser, TUserLogin, TUserClaim, TUserToken>(AbpLoginResultType.UserIsNotActive)); } if (await IsEmailConfirmationRequiredForLoginAsync(user.TenantId) && !user.IsEmailConfirmed) { return(new JKLoginResult <TUser, TUserLogin, TUserClaim, TUserToken>(AbpLoginResultType.UserEmailIsNotConfirmed)); } if (await IsPhoneConfirmationRequiredForLoginAsync(user.TenantId) && !user.IsPhoneNumberConfirmed) { return(new JKLoginResult <TUser, TUserLogin, TUserClaim, TUserToken>(AbpLoginResultType.UserPhoneNumberIsNotConfirmed)); } var principal = await _claimsPrincipalFactory.CreateAsync(user); return(new JKLoginResult <TUser, TUserLogin, TUserClaim, TUserToken>( user, principal.Identity as ClaimsIdentity )); }
public async Task EnsureClaimsIdentityHasExpectedClaims(bool supportRoles, bool supportClaims, bool supportRoleClaims, bool supportsUserEmail) { // Setup var userManager = MockHelpers.MockUserManager <PocoUser>(); var roleManager = MockHelpers.MockRoleManager <PocoRole>(); var user = new PocoUser { UserName = "******", Email = "*****@*****.**" }; userManager.Setup(m => m.SupportsUserClaim).Returns(supportClaims); userManager.Setup(m => m.SupportsUserRole).Returns(supportRoles); userManager.Setup(m => m.SupportsUserEmail).Returns(supportsUserEmail); userManager.Setup(m => m.GetUserIdAsync(user)).ReturnsAsync(user.Id); userManager.Setup(m => m.GetUserNameAsync(user)).ReturnsAsync(user.UserName); if (supportsUserEmail) { userManager.Setup(m => m.GetEmailAsync(user)).ReturnsAsync(user.Email); } var roleClaims = new[] { "Admin", "Local" }; if (supportRoles) { userManager.Setup(m => m.GetRolesAsync(user)).ReturnsAsync(roleClaims); roleManager.Setup(m => m.SupportsRoleClaims).Returns(supportRoleClaims); } var userClaims = new[] { new Claim("Whatever", "Value"), new Claim("Whatever2", "Value2") }; if (supportClaims) { userManager.Setup(m => m.GetClaimsAsync(user)).ReturnsAsync(userClaims); } userManager.Object.Options = new IdentityOptions(); var admin = new PocoRole() { Name = "Admin" }; var local = new PocoRole() { Name = "Local" }; var adminClaims = new[] { new Claim("AdminClaim1", "Value1"), new Claim("AdminClaim2", "Value2") }; var localClaims = new[] { new Claim("LocalClaim1", "Value1"), new Claim("LocalClaim2", "Value2") }; if (supportRoleClaims) { roleManager.Setup(m => m.FindByNameAsync("Admin")).ReturnsAsync(admin); roleManager.Setup(m => m.FindByNameAsync("Local")).ReturnsAsync(local); roleManager.Setup(m => m.GetClaimsAsync(admin)).ReturnsAsync(adminClaims); roleManager.Setup(m => m.GetClaimsAsync(local)).ReturnsAsync(localClaims); } var options = new Mock <IOptions <IdentityOptions> >(); var identityOptions = new IdentityOptions(); options.Setup(a => a.Value).Returns(identityOptions); var factory = new UserClaimsPrincipalFactory <PocoUser, PocoRole>(userManager.Object, roleManager.Object, options.Object); // Act var principal = await factory.CreateAsync(user); var identity = principal.Identities.First(); // Assert var manager = userManager.Object; Assert.NotNull(identity); Assert.Single(principal.Identities); Assert.Equal(IdentityConstants.ApplicationScheme, identity.AuthenticationType); var claims = identity.Claims.ToList(); Assert.NotNull(claims); Assert.Contains( claims, c => c.Type == manager.Options.ClaimsIdentity.UserNameClaimType && c.Value == user.UserName); Assert.Contains(claims, c => c.Type == manager.Options.ClaimsIdentity.UserIdClaimType && c.Value == user.Id); Assert.Equal(supportsUserEmail, claims.Any(c => c.Type == manager.Options.ClaimsIdentity.EmailClaimType && c.Value == user.Email)); Assert.Equal(supportRoles, claims.Any(c => c.Type == manager.Options.ClaimsIdentity.RoleClaimType && c.Value == "Admin")); Assert.Equal(supportRoles, claims.Any(c => c.Type == manager.Options.ClaimsIdentity.RoleClaimType && c.Value == "Local")); foreach (var cl in userClaims) { Assert.Equal(supportClaims, claims.Any(c => c.Type == cl.Type && c.Value == cl.Value)); } foreach (var cl in adminClaims) { Assert.Equal(supportRoleClaims, claims.Any(c => c.Type == cl.Type && c.Value == cl.Value)); } foreach (var cl in localClaims) { Assert.Equal(supportRoleClaims, claims.Any(c => c.Type == cl.Type && c.Value == cl.Value)); } userManager.VerifyAll(); roleManager.VerifyAll(); }
/// <summary> /// 直接根据用户信息登陆 /// </summary> /// <param name="user">用户信息</param> /// <returns>用户身份信息</returns> public async Task <ClaimsIdentity> LoginAsync(User user) { ClaimsIdentity identity = (ClaimsIdentity)(await _claimsPrincipalFactory.CreateAsync(user)).Identity; return(identity); }
/// <summary> /// Create and init the context. /// </summary> /// <param name="dbctx"></param> /// <param name="host"></param> /// <param name="path"></param> /// <param name="regionName"></param> /// <param name="user"></param> /// <param name="checkInitResults"></param> /// <returns></returns> protected async Task <WcmsAppContext> CreateAndInitAppContext(AppDbContext dbctx, string host, string path, string regionName, ApplicationUser user = null, bool checkInitResults = true) { // Check the service provider... Assert.NotEqual(null, _serviceProvider); // Create and init the http context... var httpContext = new DefaultHttpContext(); Assert.NotEqual(null, httpContext); // Configure the http context... httpContext.RequestServices = _services.BuildServiceProvider(); Assert.NotEqual(null, httpContext.RequestServices); httpContext.Request.Host = new HostString(host); httpContext.Request.Path = new PathString(path); // Add user to the http context... if (user != null) { UserClaimsPrincipalFactory <ApplicationUser, IdentityRole> clmFact = _GetRequiredServicee <UserClaimsPrincipalFactory <ApplicationUser, IdentityRole> >(httpContext.RequestServices); Assert.NotEqual(null, clmFact); httpContext.User = /*ClaimsPrincipal upp =*/ await clmFact.CreateAsync(user); Assert.NotEqual(null, httpContext.User /*upp*/); //httpContext.User = new ClaimsPrincipal(upp); } // Create and init the route context... var routeContext = new RouteContext(httpContext); Assert.NotEqual(null, routeContext); // Configure the route context... routeContext.RouteData = new RouteData(); Assert.NotEqual(null, routeContext.RouteData); routeContext.RouteData.Values.Add(CRoute.RegionTagName, regionName); // Build loger factory... var logFactory = _GetRequiredServicee <ILoggerFactory>(httpContext.RequestServices); Assert.NotEqual(null, logFactory); #if DEBUG //logFactory.AddConsole(_LogFilter); logFactory.AddDebug(_LogFilter); #endif // Create and init the context... WcmsAppContext ctx = _GetRequiredServicee <WcmsAppContext>(httpContext.RequestServices); Assert.NotEqual(null, ctx); Assert.Equal(null, ctx.User); Assert.Equal(null, ctx.Site); //ctx.UnitTestInit(dbctx); int initSiteAsyncRes = await ctx.InitSiteAsync(httpContext, _GetRequiredServicee <IAuthorizationService>(httpContext.RequestServices)); bool initRouteAsyncRes = await ctx.InitRouteAsync(routeContext); if (checkInitResults == true) { Assert.Equal(3, initSiteAsyncRes); // No module registered. Assert.Equal(true, initRouteAsyncRes); } return(ctx); }
public async Task EnsureClaimsIdentityHasExpectedClaims(bool supportRoles, bool supportClaims, bool supportRoleClaims) { // Setup var userManager = MockHelpers.MockUserManager<TestUser>(); var roleManager = MockHelpers.MockRoleManager<TestRole>(); var user = new TestUser { UserName = "******" }; userManager.Setup(m => m.SupportsUserClaim).Returns(supportClaims); userManager.Setup(m => m.SupportsUserRole).Returns(supportRoles); userManager.Setup(m => m.GetUserIdAsync(user)).ReturnsAsync(user.Id); userManager.Setup(m => m.GetUserNameAsync(user)).ReturnsAsync(user.UserName); var roleClaims = new[] { "Admin", "Local" }; if (supportRoles) { userManager.Setup(m => m.GetRolesAsync(user)).ReturnsAsync(roleClaims); roleManager.Setup(m => m.SupportsRoleClaims).Returns(supportRoleClaims); } var userClaims = new[] { new Claim("Whatever", "Value"), new Claim("Whatever2", "Value2") }; if (supportClaims) { userManager.Setup(m => m.GetClaimsAsync(user)).ReturnsAsync(userClaims); } userManager.Object.Options = new IdentityOptions(); var admin = new TestRole() { Name = "Admin" }; var local = new TestRole() { Name = "Local" }; var adminClaims = new[] { new Claim("AdminClaim1", "Value1"), new Claim("AdminClaim2", "Value2") }; var localClaims = new[] { new Claim("LocalClaim1", "Value1"), new Claim("LocalClaim2", "Value2") }; if (supportRoleClaims) { roleManager.Setup(m => m.FindByNameAsync("Admin")).ReturnsAsync(admin); roleManager.Setup(m => m.FindByNameAsync("Local")).ReturnsAsync(local); roleManager.Setup(m => m.GetClaimsAsync(admin)).ReturnsAsync(adminClaims); roleManager.Setup(m => m.GetClaimsAsync(local)).ReturnsAsync(localClaims); } var options = new Mock<IOptions<IdentityOptions>>(); var identityOptions = new IdentityOptions(); options.Setup(a => a.Options).Returns(identityOptions); var factory = new UserClaimsPrincipalFactory<TestUser, TestRole>(userManager.Object, roleManager.Object, options.Object); // Act var principal = await factory.CreateAsync(user); var identity = principal.Identities.First(); // Assert var manager = userManager.Object; Assert.NotNull(identity); Assert.Equal(1, principal.Identities.Count()); Assert.Equal(IdentityOptions.ApplicationCookieAuthenticationType, identity.AuthenticationType); var claims = identity.Claims.ToList(); Assert.NotNull(claims); Assert.True( claims.Any(c => c.Type == manager.Options.ClaimsIdentity.UserNameClaimType && c.Value == user.UserName)); Assert.True(claims.Any(c => c.Type == manager.Options.ClaimsIdentity.UserIdClaimType && c.Value == user.Id)); Assert.Equal(supportRoles, claims.Any(c => c.Type == manager.Options.ClaimsIdentity.RoleClaimType && c.Value == "Admin")); Assert.Equal(supportRoles, claims.Any(c => c.Type == manager.Options.ClaimsIdentity.RoleClaimType && c.Value == "Local")); foreach (var cl in userClaims) { Assert.Equal(supportClaims, claims.Any(c => c.Type == cl.Type && c.Value == cl.Value)); } foreach (var cl in adminClaims) { Assert.Equal(supportRoleClaims, claims.Any(c => c.Type == cl.Type && c.Value == cl.Value)); } foreach (var cl in localClaims) { Assert.Equal(supportRoleClaims, claims.Any(c => c.Type == cl.Type && c.Value == cl.Value)); } userManager.VerifyAll(); roleManager.VerifyAll(); }