Exemplo n.º 1
0
        private async Task<JObject> GenerateLocalAccessTokenResponse(string userName)
        {

            var tokenExpiration = TimeSpan.FromDays(1);


            ApplicationUser user = await UserManager.FindByNameAsync(userName);

            if (user == null || user.IsActive == false)
            {
                return null;
            }

            var _roles = await UserManager.GetRolesAsync(user.Id);

            ClaimsIdentity oAuthIdentity = await user.GenerateUserIdentityAsync(UserManager, OAuthDefaults.AuthenticationType);
            oAuthIdentity.AddClaim(new Claim(ClaimTypes.Name, userName));
            oAuthIdentity.AddClaim(new Claim("sub", userName));
            if (_roles.Contains(IdentityConstants.Roles.Administrator))
            {
                oAuthIdentity.AddClaim(new Claim("role", IdentityConstants.Roles.Administrator));
            }

            var props = new AuthenticationProperties()
            {
                IssuedUtc = DateTime.UtcNow,
                ExpiresUtc = DateTime.UtcNow.Add(tokenExpiration),
            };

            var ticket = new AuthenticationTicket(oAuthIdentity, props);

            var accessToken = Startup.OAuthBearerOptions.AccessTokenFormat.Protect(ticket);

            /* If not external user for e.g. social logins (Google, Facebook etc)
            Then display is the combination of First & Last Name
            **/
            if (user.Logins.Count == 0)
            {
                var person = new RegistrationController().GetPerson(user.UserName);
                user.DisplayName = person != null ? person.FirstName + " " + person.LastName : user.DisplayName;
            }

            JObject tokenResponse = new JObject(
                                        new JProperty("userName", userName),
                                        new JProperty("displayName", user.DisplayName ?? 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()),
                                        new JProperty(".issued", ticket.Properties.IssuedUtc.ToString()),
                                        new JProperty(".expires", ticket.Properties.ExpiresUtc.ToString())
        );

            return tokenResponse;
        }
Exemplo n.º 2
0
        public override async Task GrantResourceOwnerCredentials(OAuthGrantResourceOwnerCredentialsContext context)
        {

            var allowedOrigin = context.OwinContext.Get<string>("clientAllowedOrigin");

            if (allowedOrigin == null) allowedOrigin = "*";

            context.OwinContext.Response.Headers.Add("Access-Control-Allow-Origin", new[] { allowedOrigin });

            var userManager = context.OwinContext.GetUserManager<ApplicationUserManager>();

            ApplicationUser user = await userManager.FindAsync(context.UserName, context.Password);

            if (user == null || user.IsActive == false)
            {
                context.SetError("invalid_grant", "The user name or password is incorrect.");
                return;
            }

            /* Currently two-factor authentication is enabled for internal users
            * if EmailConfirmed and PhoneNumberConfirmed both are false then
            * verification code sent to user is not verified
            **/
            if (!user.EmailConfirmed && !user.PhoneNumberConfirmed)
            {
                context.SetError("user_requiresverification", "User is not verified. Use verification code send to email or phone no entered during registration process.");
                return;
            }
            if (await userManager.IsLockedOutAsync(user.Id))
            {
                context.SetError("user_lockedout", "User is locked out");
                return;// SignInStatus.LockedOut;
            }
            var _roles = await userManager.GetRolesAsync(user.Id);

            ClaimsIdentity oAuthIdentity = await user.GenerateUserIdentityAsync(userManager, OAuthDefaults.AuthenticationType);

            //var oAuthIdentity = new ClaimsIdentity("JWT");

            oAuthIdentity.AddClaim(new Claim(ClaimTypes.Name, context.UserName));
            oAuthIdentity.AddClaim(new Claim("sub", context.UserName));
            if (_roles.Contains(IdentityConstants.Roles.Administrator))
            {
                oAuthIdentity.AddClaim(new Claim("role", IdentityConstants.Roles.Administrator));
            }

            var person = new RegistrationController().GetPerson(user.UserName);
            user.DisplayName = person != null ? person.FirstName + " " + person.LastName : user.DisplayName;

            AuthenticationProperties properties = CreateProperties(user, string.Join(",", _roles));
            //properties.Dictionary.Add("audience", IdentityConstants.AudienceId);
            properties.Dictionary.Add("audience", (context.ClientId == null) ? string.Empty : context.ClientId);

            var ticket = new AuthenticationTicket(oAuthIdentity, properties);
            context.Validated(ticket);
            //return Task.FromResult<object>(null);
            //context.Request.Context.Authentication.SignIn(cookiesIdentity);

        }
Exemplo n.º 3
0
        public async Task<IHttpActionResult> Register(RegisterBindingModel model)
        {
            if (!ModelState.IsValid)
            {
                return BadRequest(ModelState);
            }

            var regContext = new RegistrationController();
            if (regContext.IsDuplicateEmail(model.Email))
            {
                return BadRequest("Email ID already exists");
            }


            var user = new ApplicationUser()
            {
                UserName = model.Email,
                Email = model.Email,
                PhoneNumber = model.Person.Contact.Phone,
                DisplayName = model.DisplayName
            };

            IdentityResult result;


            try
            {
                result = await UserManager.CreateAsync(user, model.Password).ConfigureAwait(false);
                // Note that because of the ConfigureAwait(false), we are not on the original context here.
                // Instead, we're running on the thread pool.

                if (!result.Succeeded)
                {
                    return GetErrorResult(result);
                }
                else
                {

                    //Enable two factor authentication
                    result = await UserManager.SetTwoFactorEnabledAsync(user.Id, true).ConfigureAwait(false);
                    if (!result.Succeeded)
                    {
                        return GetErrorResult(result);
                    }

                    /* Insert a new record into the People table
                    */

                    var personResult = new RegistrationController().CreatePerson(model.Person);

                    // Sending verification code
                    var provider = "EmailCode";
                    var token = await UserManager.GenerateTwoFactorTokenAsync(user.Id, provider).ConfigureAwait(false);
                    // See IdentityConfig.cs to plug in Email/SMS services to actually send the code
                    result = await UserManager.NotifyTwoFactorTokenAsync(user.Id, provider, token);
                    if (!result.Succeeded)
                    {
                        return GetErrorResult(result);
                    }
                    return Ok(result);
                }
            }
            catch (Exception ex)
            {

                throw ex;
            }


        }