コード例 #1
0
        public async Task <IHttpActionResult> Register(RegisterBindingModel model)
        {
            if (!ModelState.IsValid)
            {
                return(BadRequest(ModelState));
            }

            // New user account registration, additional tasks
            // Before attempting to add the user, let's validate the claims

            // Reference to the manager
            Manager m = new Manager();

            // Status field to indicate whether the requested claims are allowed
            // The first "not found" or malformed claim will change it to "false"
            bool canRegister = true;

            // Look at the role claims
            foreach (var roleClaimValue in model.Roles)
            {
                if (m.AppClaimGetByMatch("role", roleClaimValue.Trim().ToLower()) == null)
                {
                    canRegister = false;
                }
            }

            // Look at the custom claims, add code here...



            if (canRegister)
            {
                var user = new ApplicationUser()
                {
                    UserName = model.Email, Email = model.Email
                };

                IdentityResult result = await UserManager.CreateAsync(user, model.Password);

                if (result.Succeeded)
                {
                    // Add the new claims that were submitted by the user/requestor

                    await UserManager.AddClaimAsync(user.Id, new Claim(ClaimTypes.Email, model.Email));

                    await UserManager.AddClaimAsync(user.Id, new Claim(ClaimTypes.Role, "User"));

                    await UserManager.AddClaimAsync(user.Id, new Claim(ClaimTypes.GivenName, model.GivenName));

                    await UserManager.AddClaimAsync(user.Id, new Claim(ClaimTypes.Surname, model.Surname));

                    foreach (var role in model.Roles)
                    {
                        await UserManager.AddClaimAsync(user.Id, new Claim(ClaimTypes.Role, role));
                    }

                    // Add custom claims that were submitted by the user/requestor; add code here...
                }
                else
                {
                    return(GetErrorResult(result));
                }
                return(Ok());
            }
            else
            {
                return(StatusCode(HttpStatusCode.BadRequest));
                // We should give the user more useful info
            }
        }