public async Task<CreateUserOutput> CreateUser(CreateUserInput input) { CreateUserOutput result = new CreateUserOutput(); result.Status = 1; ApplicationUser user = new ApplicationUser(); user.Email = input.Email; user.UserName = input.UserName; user.PhoneNumber = input.PhoneNumber; IdentityResult validateUserResult = await this.UserManager.UserValidator.ValidateAsync(user); IdentityResult validatePassResult = await this.UserManager.PasswordValidator.ValidateAsync(input.Password); if (validateUserResult.Succeeded && validatePassResult.Succeeded) { IdentityResult res = await this.UserManager.CreateAsync(user); if (res.Succeeded) { input.Id = user.Id; if (!string.IsNullOrEmpty(input.Password)) { res = await this.UserManager.AddPasswordAsync(user.Id, input.Password); if (res.Succeeded) { if (!string.IsNullOrEmpty(input.DisplayName)) res = await this.UserManager.AddClaimAsync(user.Id, new Claim("displayName", input.DisplayName)); if (input.UserGroups != null) { foreach (Quang.Auth.Entities.Group group in input.UserGroups) this._userTable.addUserToGroup(group.Id, user.Id); } result.Status = 0; } else { IdentityResult identityResult = await this.UserManager.DeleteAsync(user); } } else result.Status = 0; } } return result; }
public static async Task<AuthenticationProperties> CreateProperties(string clientId, ApplicationUser user, string userClientId, string clientApiSecret, long? countSuccessLoggedIn, IList<Claim> userClaims) { var userManager = HttpContext.Current.Request.GetOwinContext().GetUserManager<ApplicationUserManager>(); Claim claim = userClaims.FirstOrDefault(m => m.Type == "displayName"); IDictionary<string, string> dictionary1 = new Dictionary<string, string>(); dictionary1.Add("as:client_id", clientId); dictionary1.Add("userName", user.UserName); dictionary1.Add("displayName", claim != null ? claim.Value : user.UserName); dictionary1.Add("userClientId", userClientId); dictionary1.Add("email", string.IsNullOrEmpty(user.Email) ? string.Empty : user.Email); if (!string.IsNullOrEmpty(clientApiSecret)) dictionary1.Add("client_api_secret", clientApiSecret); if (countSuccessLoggedIn.HasValue) { IDictionary<string, string> dictionary2 = dictionary1; const string key = "isFirstLogin"; long? nullable = countSuccessLoggedIn; string str = (nullable.GetValueOrDefault() != 1L ? 0 : (1)) != 0 ? bool.TrueString : bool.FalseString; dictionary2.Add(key, str); } IList<string> result = userManager.GetRolesAsync(user.Id).Result; dictionary1.Add("roles", string.Join(",", result)); return new AuthenticationProperties(dictionary1); }
private async Task<JObject> GenerateLocalAccessTokenResponse(ApplicationUser user) { TimeSpan tokenExpiration = TimeSpan.FromDays(1.0); var userManager = HttpContext.Current.GetOwinContext().GetUserManager<ApplicationUserManager>(); var identity = await user.GenerateUserIdentityAsync(userManager, "Bearer"); var clientInfo = AppAuthorizeAttribute.GenerateClientInfo(user.UserName, tokenExpiration); string userClientId = clientInfo.Key; var userClientClaims = clientInfo.Value; identity.AddClaims(userClientClaims); IList<string> roles = await userManager.GetRolesAsync(user.Id); var data = (IDictionary<string, string>)new Dictionary<string, string>(); data.Add("userName", user.UserName); data.Add("userClientId", userClientId); data.Add("roles", string.Join(",", roles)); var props = new AuthenticationProperties(data) { IssuedUtc = DateTime.UtcNow, ExpiresUtc = DateTime.UtcNow.Add(tokenExpiration) }; IList<Claim> claims = await userManager.GetClaimsAsync(user.Id); var displayName = claims.FirstOrDefault(m => m.Type == "displayName"); var ticket = new AuthenticationTicket(identity, props); string accessToken = Startup.OAuthOptions.AccessTokenFormat.Protect(ticket); var tokenResponse = new JObject(new[] { new JProperty("userName", user.UserName), new JProperty("displayName",displayName != null ? displayName.Value : user.UserName), new JProperty("roles", string.Join(",", roles)), new JProperty("access_token", accessToken), new JProperty("token_type", "bearer"), new JProperty("expires_in", tokenExpiration.TotalSeconds.ToString(CultureInfo.InvariantCulture)), new JProperty("userClientId", userClientId), new JProperty(".issued", ticket.Properties.IssuedUtc.ToString()), (object)new JProperty(".expires", ticket.Properties.ExpiresUtc.ToString()) }); return tokenResponse; }
private JObject GenerateLocalAccessTokenResponseBackup(ApplicationUser user) { TimeSpan timeSpan = TimeSpan.FromDays(1.0); var identity = new ClaimsIdentity("Bearer"); identity.AddClaim(new Claim("http://schemas.xmlsoap.org/ws/2005/05/identity/claims/name", user.UserName)); var properties = new AuthenticationProperties() { IssuedUtc = DateTime.UtcNow, ExpiresUtc = DateTime.UtcNow.Add(timeSpan) }; var data = new AuthenticationTicket(identity, properties); string str = Startup.OAuthOptions.AccessTokenFormat.Protect(data); return new JObject(new object[] { new JProperty("userName", user.UserName), new JProperty("roles", string.Empty), new JProperty("access_token", str), new JProperty("token_type", "bearer"), new JProperty("expires_in", timeSpan.TotalSeconds.ToString()), new JProperty(".issued", data.Properties.IssuedUtc.ToString()), new JProperty(".expires", data.Properties.ExpiresUtc.ToString()) }); }
public async Task<IHttpActionResult> RegisterExternal(RegisterExternalBindingModel model) { IHttpActionResult httpActionResult; if (!ModelState.IsValid) { httpActionResult = BadRequest(ModelState); } else { var verifiedAccessToken = await VerifyExternalAccessToken(model.Provider, model.ExternalAccessToken); if (verifiedAccessToken == null) { httpActionResult = BadRequest("Invalid Provider or External Access Token"); } else { ExternalLoginData.FromIdentity(User.Identity as ClaimsIdentity); var user = await UserManager.FindAsync(new UserLoginInfo(model.Provider, verifiedAccessToken.ProviderKey)); var hasRegistered = user != null; if (hasRegistered) { httpActionResult = BadRequest("External user is already registered"); } else { var applicationUser = new ApplicationUser { UserName =model.Provider.ToLower() +verifiedAccessToken.ProviderKey.ToLower(), Email = model.Email }; user = applicationUser; var result = await UserManager.CreateAsync(user); if (!result.Succeeded) { httpActionResult = GetErrorResult(result); } else { var info = new ExternalLoginInfo { DefaultUserName = user.UserName, Login = new UserLoginInfo(model.Provider, verifiedAccessToken.ProviderKey) }; result = await UserManager.AddLoginAsync(user.Id, info.Login); if (!result.Succeeded) { httpActionResult = GetErrorResult(result); } else { var accessTokenResponse = await GenerateLocalAccessTokenResponse(user); httpActionResult = Ok(accessTokenResponse); } } } } } return httpActionResult; }
public async Task<IHttpActionResult> Register(RegisterBindingModel model) { IHttpActionResult httpActionResult; if (!ModelState.IsValid) { httpActionResult = BadRequest(ModelState); } else { var applicationUser = new ApplicationUser {UserName = model.Email, Email = model.Email}; ApplicationUser user = applicationUser; IdentityResult result = await UserManager.CreateAsync(user, model.Password); httpActionResult = result.Succeeded ? Ok() : GetErrorResult(result); } return httpActionResult; }