// validate username and password from the request and validate them against our ASP.NET 2.1 Identity system
        public override async Task GrantResourceOwnerCredentials(OAuthGrantResourceOwnerCredentialsContext context)
        {
            // cors allowed
            var allowedOrigin = "*";

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

            var signManager = context.OwinContext.Get <ApplicationSignInManager>();

            if (await signManager.TrySignIn(context) != SignInStatus.Success)
            {
                context.Rejected();
                return;
            }

            AppUser user = await signManager.UserManager.FindAsync(context.UserName, context.Password);

            ClaimsIdentity oAuthIdentity = await signManager.CreateUserIdentityAsync(user);

            oAuthIdentity.AddClaims(ExtendedClaimsProvider.GetClaims(user));
            oAuthIdentity.AddClaims(ExtendedClaimsProvider.CreateRolesBasedOnClaims(oAuthIdentity));

            var ticket = new AuthenticationTicket(oAuthIdentity, new AuthenticationProperties
            {
                AllowRefresh = true
            });

            context.Validated(ticket);
        }
        public async Task<IActionResult> Login(LoginViewModel model)
        {
            if (ModelState.IsValid)
            {
                // This doesn't count login failures towards account lockout
                // To enable password failures to trigger account lockout, set lockoutOnFailure: true
                var result = await _signInManager.PasswordSignInAsync(model.UserName, model.Password, model.RememberMe, lockoutOnFailure: false).ConfigureAwait(false);
                if (result.Succeeded)
                {
                    var claims = new List<Claim>()
                    {
                        new Claim(ClaimTypes.Name, model.UserName)
                    };
                    var user = await _userManager.FindByNameAsync(model.UserName).ConfigureAwait(false);
                    claims.AddRange(ExtendedClaimsProvider.GetClaims(user));
                    var claimsIdentity = new ClaimsIdentity(claims, "login");

                    await HttpContext.SignInAsync(
                    CookieAuthenticationDefaults.AuthenticationScheme,
                    new ClaimsPrincipal(claimsIdentity),
                    new AuthenticationProperties
                    {
                        IsPersistent = true,
                        ExpiresUtc = DateTime.UtcNow.AddDays(30)
                    }).ConfigureAwait(false);
                    _logger.LogInformation(1, "User logged in.");
                    return RedirectToLocal(model.ReturnUrl);
                }
            }

            // If we got this far, something failed, redisplay form
            return View(model);
        }
        public async Task <IHttpActionResult> AssignClaimsToUser([FromUri] string id, [FromBody] List <ClaimBindingModel> claimsToAssign)
        {
            if (!ModelState.IsValid)
            {
                return(BadRequest(ModelState));
            }

            var appUser = await this.AppUserManager.FindByIdAsync(id);

            if (appUser == null)
            {
                return(NotFound());
            }

            foreach (ClaimBindingModel claimModel in claimsToAssign)
            {
                if (appUser.Claims.Any(c => c.ClaimType == claimModel.Type))
                {
                    await this.AppUserManager.RemoveClaimAsync(id, ExtendedClaimsProvider.CreateClaim(claimModel.Type, claimModel.Value));
                }

                await this.AppUserManager.AddClaimAsync(id, ExtendedClaimsProvider.CreateClaim(claimModel.Type, claimModel.Value));
            }

            return(Ok());
        }
        public async Task <IHttpActionResult> RemoveClaimsFromUser([FromUri] string id, [FromBody] List <ClaimBindingModel> claimsToRemove)
        {
            if (!ModelState.IsValid)
            {
                return(BadRequest(ModelState));
            }

            var appUser = await this.AppUserManager.FindByIdAsync(id);

            if (appUser == null)
            {
                return(NotFound());
            }
            IdentityUserClaim iuc;

            foreach (ClaimBindingModel claimModel in claimsToRemove)
            {
                iuc = new IdentityUserClaim()
                {
                    ClaimType  = claimModel.Type,
                    ClaimValue = claimModel.Value,
                    UserId     = id,
                };
                //if (appUser.Claims.Any(c => c.ClaimType == claimModel.Type))

                if (appUser.Claims.Contains(iuc))
                {
                    await this.AppUserManager.RemoveClaimAsync(id, ExtendedClaimsProvider.CreateClaim(claimModel.Type, claimModel.Value));
                }
            }

            return(Ok());
        }
        public override async Task GrantResourceOwnerCredentials(OAuthGrantResourceOwnerCredentialsContext context)
        {
            var 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)
            {
                context.SetError("invalid_grant", "The user name or password is incorrect.");
                return;
            }

            if (!user.EmailConfirmed)
            {
                context.SetError("invalid_grant", "User did not confirm email.");
                return;
            }

            ClaimsIdentity oAuthIdentity = await user.GenerateUserIdentityAsync(userManager);

            oAuthIdentity.AddClaims(ExtendedClaimsProvider.GetClaims(user));
            oAuthIdentity.AddClaims(RolesFromClaims.CreateRolesBasedOnClaims(oAuthIdentity));

            var ticket = new AuthenticationTicket(oAuthIdentity, null);

            context.Validated(ticket);
        }
        /// <summary>
        /// Responsible to validate the username and password sent to the authorization server’s token endpoint
        /// </summary>
        /// <param name="context"></param>
        /// <returns></returns>
        public override async Task GrantResourceOwnerCredentials(OAuthGrantResourceOwnerCredentialsContext context)
        {
            var allowedOrigin = context.OwinContext.Get <string>("as:clientAllowedOrigin");

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

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

            var             userManager = context.OwinContext.GetUserManager <ApplicationUserManager>();
            var             roleManager = context.OwinContext.GetUserManager <ApplicationRoleManager>();
            ApplicationUser user        = await userManager.FindAsync(context.UserName, context.Password);

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

            if (!user.EmailConfirmed)
            {
                context.SetError("invalid_grant", "User did not confirm email.");
                return;
            }
            //generate the identity to pass to the tikcet
            ClaimsIdentity oAuthIdentity = await user.GenerateUserIdentityAsync(userManager, context.Options.AuthenticationType);

            oAuthIdentity.AddClaim(new Claim(ClaimTypes.Name, context.UserName));
            oAuthIdentity.AddClaim(new Claim("sub", context.UserName));
            //Add all roles of current user
            List <Claim> rolesClaims = new List <Claim>();

            foreach (var identityUserRole in user.Roles)
            {
                var identityRole = await roleManager.FindByIdAsync(identityUserRole.RoleId);

                rolesClaims.Add(new Claim(ClaimTypes.Role, identityRole.Name));
            }
            oAuthIdentity.AddClaims(rolesClaims);
            //add specific claims to the identity of the user withc suite some cases
            //like add FTE (Full time employee) when the JoinDate of the user is greater then 90 days
            oAuthIdentity.AddClaims(ExtendedClaimsProvider.GetClaims(user));
            //add some roles based on some claims
            oAuthIdentity.AddClaims(RolesFromClaims.CreateRolesBasedOnClaims(oAuthIdentity));
            var props = new AuthenticationProperties(new Dictionary <string, string>
            {
                {
                    "as:client_id", (context.ClientId == null) ? string.Empty : context.ClientId
                },
                {
                    "userName", context.UserName
                }
            });

            var ticket = new AuthenticationTicket(oAuthIdentity, props);

            context.Validated(ticket);
        }
Example #7
0
        public async Task <IHttpActionResult> RemoveClaimsFromUser([FromUri] Guid id, [FromBody] List <ClaimRequestModel> claimsToRemove)
        {
            if (!ModelState.IsValid)
            {
                return(BadRequest(ModelState));
            }

            try
            {
                var appUser = await _applicationUserManager.FindByIdAsync(id);

                if (appUser == null)
                {
                    return(NotFound());
                }

                foreach (ClaimRequestModel claimModel in claimsToRemove)
                {
                    if (appUser.Claims.Any(c => c.ClaimType == claimModel.Type))
                    {
                        await _applicationUserManager.RemoveClaimAsync(id, ExtendedClaimsProvider.CreateClaim(claimModel.Type, claimModel.Value));
                    }
                }
                return(Ok());
            }
            catch (Exception ex)
            {
                _logger.Error(ex, "Failed to RemoveClaimsFromUser");
                return(InternalServerError(ex, "Failed to RemoveClaimsFromUser"));
            }
        }
        public async Task <ClaimsIdentity> GetClaimIdentityAsync(ApplicationUser appUser, ApplicationUserManager appUserManager)
        {
            ClaimsIdentity oAuthIdentity = await appUser.GenerateUserIdentityAsync(appUserManager, "JWT");

            oAuthIdentity.AddClaims(ExtendedClaimsProvider.GetClaims(appUser));
            oAuthIdentity.AddClaims(RolesFromClaims.CreateRolesBasedOnClaims(oAuthIdentity));
            return(oAuthIdentity);
        }
Example #9
0
        public override async Task GrantResourceOwnerCredentials(OAuthGrantResourceOwnerCredentialsContext context)
        {
            var allowedOrigin = context.OwinContext.Get <string>("as:clientAllowedOrigin");

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

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

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

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

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

            //if (!user.EmailConfirmed)
            //{
            //    context.SetError("invalid_grant", "User did not confirm email.");
            //    return;
            //}

            ClaimsIdentity oAuthIdentity = await user.GenerateUserIdentityAsync(userManager, "JWT");

            oAuthIdentity.AddClaims(ExtendedClaimsProvider.GetClaims(user));
            oAuthIdentity.AddClaims(RolesFromClaims.CreateRolesBasedOnClaims(oAuthIdentity));

            //var ticket = new AuthenticationTicket(oAuthIdentity, null);

            var props = new AuthenticationProperties(new Dictionary <string, string>
            {
                {
                    "as:client_id", (context.ClientId == null) ? string.Empty : context.ClientId
                },
                {
                    "UserName", context.UserName
                },
                {
                    "level", user.Level.ToString()
                },
                {
                    "firstname", user.FirstName
                },
                {
                    "lastname", user.LastName
                }
            });

            var ticket = new AuthenticationTicket(oAuthIdentity, props);

            context.Validated(ticket);
        }
        public override async Task GrantResourceOwnerCredentials(OAuthGrantResourceOwnerCredentialsContext context)
        {
            var 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);

            var systemUser = await userManager.FindByNameAsync("System");

            if (user == null)
            {
                context.SetError("invalid_grant", "The user name or password is incorrect.");
                logger.Error($"Login failed The user name or password is incorrect: {context.UserName}, Id: {user.Id}", systemUser.Id);
                return;
            }

            if ((!user.IsActive.HasValue) || (!user.IsActive.Value))
            {
                context.SetError("invalid_grant", "The user is inactive");
                logger.Error($"Login failed The user is inactive: {context.UserName}, Id: {user.Id}", systemUser.Id);
                return;
            }

            //if (!user.EmailConfirmed)
            //{
            //    context.SetError("invalid_grant", "User did not confirm email.");
            //    logger.Error($"Login failed User did not confirm email: {context.UserName},  Id: {user.Id}", systemUser.Id);
            //    return;
            //}

            ClaimsIdentity oAuthIdentity = await user.GenerateUserIdentityAsync(userManager, "JWT");

            oAuthIdentity.AddClaims(ExtendedClaimsProvider.GetClaims(user));

            oAuthIdentity.AddClaims(RolesFromClaims.CreateRolesBasedOnClaims(oAuthIdentity));

            var ticket = new AuthenticationTicket(oAuthIdentity, null);

            context.Validated(ticket);

            if (ticket == null)
            {
                logger.Error($"Login failed The user name or password is incorrect: {context.UserName}", systemUser.Id);
            }
            else
            {
                List <Claim> claimsList = oAuthIdentity.Claims.Where(c => c.Type == ClaimTypes.Role).ToList();
                string       rolesList  = string.Join(",", claimsList.Select(r => r.Value).ToList());
                logger.Info($"Login Successful for {context.UserName} Roles: {rolesList}", systemUser.Id);
            }
        }
        public async Task <IHttpActionResult> CreateUser(CreateUserBindingModel createUserModel)
        {
            if (!ModelState.IsValid)
            {
                return(BadRequest(ModelState));
            }
            var user = new ApplicationUser()
            {
                UserName = createUserModel.Username,
                Email    = createUserModel.Email,
                JoinDate = DateTime.Now.Date,
            };


            IdentityResult addUserResult = await this.AppUserManager.CreateAsync(user, createUserModel.Password);

            if (!addUserResult.Succeeded)
            {
                return(GetErrorResult(addUserResult));
            }

            var userEntity    = this.AppUserManager.Users.FirstOrDefault(x => x.Email == createUserModel.Email);
            var newEmployeeId = _employeeService.Post(new EmployeeDto()
            {
                CompanyId = 1,
                Id        = createUserModel.DeveloperId,
                Email     = createUserModel.Email,
                FirstName = createUserModel.FirstName,
                Surname   = createUserModel.LastName,
            }, userEntity);

            var readClaim         = ExtendedClaimsProvider.CreateClaim("canReadUsers", "true");
            var readProjectsClaim = ExtendedClaimsProvider.CreateClaim("canReadProjects", "true");

            AppUserManager.AddClaim(userEntity.Id, readClaim);
            AppUserManager.AddClaim(userEntity.Id, readProjectsClaim);

            string code = await this.AppUserManager.GenerateEmailConfirmationTokenAsync(user.Id);

            var callbackUrl = new Uri(Url.Link("ConfirmEmailRoute", new { userId = user.Id, code = HttpUtility.UrlEncode(code) }));

            try
            {
                await this.AppUserManager.SendEmailAsync(user.Id, "Confirm your account", "Please confirm your account by clicking: " + callbackUrl);
            }
            catch (Exception ex)
            {
                return(BadRequest(ex.Message));
            }

            Uri locationHeader = new Uri(Url.Link("GetUserById", new { id = user.Id }));

            return(Created(locationHeader, TheModelFactory.Create(user)));
        }
        public override async Task GrantResourceOwnerCredentials(OAuthGrantResourceOwnerCredentialsContext context)
        {
            var allowedOrigin = context.OwinContext.Get <string>("as: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.FindByEmailAsync(context.UserName);

            if (user == null)
            {
                context.SetError("invalid_grant", "The email or passcode is incorrect.");
                return;
            }
            if (user.PasscodeHash != context.Password)
            {
                context.SetError("invalid_grant", "The passcode is incorrect.");
                return;
            }
            if (user.LockoutEndDateUtc < DateTime.UtcNow)
            {
                context.SetError("invalid_grant", "The passcode has expired.");
                return;
            }
            if (!user.EmailConfirmed)
            {
                context.SetError("invalid_grant", "User did not confirm email.");
                return;
            }

            ClaimsIdentity oAuthIdentity = await user.GenerateUserIdentityAsync(userManager, "JWT");

            oAuthIdentity.AddClaims(ExtendedClaimsProvider.GetClaims(user));
            oAuthIdentity.AddClaims(RolesFromClaims.CreateRolesBasedOnClaims(oAuthIdentity));

            var props = new AuthenticationProperties(new Dictionary <string, string>
            {
                {
                    "as:client_id", (context.ClientId == null) ? string.Empty : context.ClientId
                },
                {
                    "userName", context.UserName
                }
            });
            var ticket = new AuthenticationTicket(oAuthIdentity, props);

            context.Validated(ticket);
        }
Example #13
0
        public override async Task GrantResourceOwnerCredentials(OAuthGrantResourceOwnerCredentialsContext context)
        {
            try
            {
                var allowedOrigin = "*";

                context.OwinContext.Response.Headers.Add("Access-Control-Allow-Origin", new[] { allowedOrigin });
                var             userManager = context.OwinContext.GetUserManager <ApplicationUserManager>();
                ApplicationUser user        = null;;
                try
                {
                    user = await userManager.FindAsync(context.UserName, context.Password);
                }
                catch (Exception ex)
                {
                    Utilities.LogException(ex);
                }

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

                if (!user.EmailConfirmed)
                {
                    context.SetError("invalid_grant", "User did not confirm email.");
                    return;
                }
                _userType = user.UserType;
                //ClaimsIdentity oAuthIdentity = await user.GenerateUserIdentityAsync(userManager, "JWT");
                ClaimsIdentity oAuthIdentity = userManager.CreateIdentityAsync(user, "JWT").Result;
                oAuthIdentity.AddClaims(ExtendedClaimsProvider.GetClaims(user));
                oAuthIdentity.AddClaims(RolesFromClaims.CreateRolesBasedOnClaims(oAuthIdentity));

                List <Claim>             roles      = oAuthIdentity.Claims.Where(c => c.Type == ClaimTypes.Role).ToList();
                AuthenticationProperties properties = CreateProperties(user.UserName, Newtonsoft.Json.JsonConvert.SerializeObject(roles.Select(x => x.Value)));
                var ticket = new AuthenticationTicket(oAuthIdentity, properties);

                context.Validated(ticket);
            }
            catch (Exception ex)
            {
                Utilities.LogException(ex);
            }
        }
        private string GenerateToken(ApplicationUser user, DateTime expires, string refreshToken)
        {
            List <Claim> claims = ExtendedClaimsProvider.GetClaims(user).ToList();

            claims.AddRange(new[]
            {
                new Claim("Id", user.Id.ToString()),
                new Claim("RefreshToken", refreshToken)
            });
            var token = new JwtTokenBuilder()
                        .AddSecurityKey(JwtSecurityKey.Create(SWCmsConstants.JWTSettings.SECRET_KEY))
                        .AddSubject(user.UserName)
                        .AddIssuer(SWCmsConstants.JWTSettings.ISSUER)
                        .AddAudience(SWCmsConstants.JWTSettings.AUDIENCE)
                        .AddClaims(claims.ToDictionary(c => c.Type, c => c.Value))
                        .AddExpiry(SWCmsConstants.JWTSettings.EXPIRED_IN)
                        .Build();

            return(token.Value);

            //var handler = new JwtSecurityTokenHandler();
            //List<Claim> claims = ExtendedClaimsProvider.GetClaims(user).ToList();
            //claims.AddRange(new[]
            //    {
            //        new Claim("Id", user.Id.ToString()),
            //        new Claim("RefreshToken", refreshToken)
            //    });
            //ClaimsIdentity identity = new ClaimsIdentity(
            //    new GenericIdentity(user.UserName, "TokenAuth"),
            //    claims
            //);

            //var securityToken = handler.CreateToken(new SecurityTokenDescriptor
            //{
            //    Issuer = SWCmsConstants.AuthConfiguration.AuthTokenIssuer,
            //    Audience = SWCmsConstants.AuthConfiguration.Audience,
            //    SigningCredentials = SWCmsConstants.AuthConfiguration.SigningCredentials,
            //    Subject = identity,
            //    IssuedAt = expires.AddSeconds(-SWCmsConstants.AuthConfiguration.AuthCookieExpiration),
            //    Expires = expires
            //});
            //return handler.WriteToken(securityToken);
        }
Example #15
0
        public override async Task GrantResourceOwnerCredentials(OAuthGrantResourceOwnerCredentialsContext context)
        {
            //
            // Setup CORS
            //
            var allowedOrigin = "*";

            context.OwinContext.Response.Headers.Add("Access-Control-Allow-Origin", new [] { allowedOrigin });
            //
            // Check whether user exists and if the user has confirmed email. If so grant the access token
            //
            var userManager = context.OwinContext.GetUserManager <ApplicationUserManager>();
            var user        = await userManager.FindAsync(context.UserName, context.Password);

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

            if (user.EmailConfirmed == false)
            {
                context.SetError("The user has not verified the email yet");
                return;
            }

            var oAuthIdentity = await user.GenerateUserIdentityAsync(userManager, "JWT");

            //
            // Get claims for the user
            //
            oAuthIdentity.AddClaims(ExtendedClaimsProvider.GetClaims(user));
            //
            // Get role based claims
            //
            oAuthIdentity.AddClaims(RolesFromClaims.CreateRolesBasedOnClaims(oAuthIdentity));

            var ticket = new AuthenticationTicket(oAuthIdentity, null);

            context.Validated(ticket);
        }
        public override async Task GrantResourceOwnerCredentials(OAuthGrantResourceOwnerCredentialsContext context)
        {
            var allowedOrigin = "*";

            context.OwinContext.Response.Headers.Add("Access-Control-Allow-Origin", new[] { allowedOrigin });
            var userManager = context.OwinContext.GetUserManager <ApplicationUserManager>();
            var user        = await userManager.FindAsync(context.UserName, context.Password);

            if (user == null)
            {
                context.SetError("invalid_grant", "The user name or password is incorrect.");
                return;
            }
            var oAuthIdentity = await user.GenerateUserIdentityAsync(userManager, "JWT");

            // Add any extra claims to the JWT that the applications would need
            oAuthIdentity.AddClaims(ExtendedClaimsProvider.GetClaims(user));
            var ticket = new AuthenticationTicket(oAuthIdentity, null);

            context.Validated(ticket);
        }
Example #17
0
        public async Task <IHttpActionResult> RemoveClaimsFromUser([FromUri] string id, [FromBody] List <ClaimDTO> claimsToRemove)
        {
            if (!ModelState.IsValid)
            {
                return(BadRequest(ModelState));
            }

            var appUser = await this.UserManager.FindByIdAsync(id);

            if (appUser == null)
            {
                return(NotFound());
            }

            foreach (ClaimDTO dto in claimsToRemove)
            {
                if (appUser.Claims.Any(c => c.ClaimType == dto.Type))
                {
                    await this.UserManager.RemoveClaimAsync(id, ExtendedClaimsProvider.CreateClaim(dto.Type, dto.Value));
                }
            }

            return(Ok());
        }
Example #18
0
        public override async Task GrantResourceOwnerCredentials(OAuthGrantResourceOwnerCredentialsContext context)
        {
            //var allowedOrigin = context.OwinContext.Get<string>("as:clientAllowedOrigin");

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

            //context.OwinContext.Response.Headers.Add("Access-Control-Allow-Origin", new[] { allowedOrigin });
            //context.OwinContext.Response.Headers.Add("Access-Control-Allow-Origin", new[] { "*" });
            //using (AuthRepository _repo = new AuthRepository())
            //{
            //    IdentityUser user = await _repo.FindUser(context.UserName, context.Password);

            //    ClaimsIdentity oAuthIdentity = await user.GenerateUserIdentityAsync(userManager, "JWT");

            //    oAuthIdentity.AddClaims(ExtendedClaimsProvider.GetClaims(user));

            //    var ticket = new AuthenticationTicket(oAuthIdentity, null);

            //    context.Validated(ticket);

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

            var 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)
            {
                context.SetError("invalid_grant", "The user name or password is incorrect.");
                return;
            }

            if (!user.EmailConfirmed)
            {
                context.SetError("invalid_grant", "User did not confirm email.");
                return;
            }

            ClaimsIdentity oAuthIdentity = await user.GenerateUserIdentityAsync(userManager, "JWT");

            oAuthIdentity.AddClaims(ExtendedClaimsProvider.GetClaims(user));
            oAuthIdentity.AddClaims(RolesFromClaims.CreateRolesBasedOnClaims(oAuthIdentity));

            var props = new AuthenticationProperties(new Dictionary <string, string>
            {
                {
                    "as:client_id", (context.ClientId == null) ? string.Empty : context.ClientId
                },
                {
                    "userName", context.UserName
                }
            });

            var ticket = new AuthenticationTicket(oAuthIdentity, props);

            context.Validated(ticket);

            //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;
            //}

            //if (!user.EmailConfirmed)
            //{
            //    context.SetError("invalid_grant", "User did not confirm email.");
            //    return;
            //}

            //ClaimsIdentity oAuthIdentity = await user.GenerateUserIdentityAsync(userManager, "JWT");
            //oAuthIdentity.AddClaims(ExtendedClaimsProvider.GetClaims(user));
            //oAuthIdentity.AddClaims(RolesFromClaims.CreateRolesBasedOnClaims(oAuthIdentity));



            //var oAuthIdentity = new ClaimsIdentity(context.Options.AuthenticationType);
            //oAuthIdentity.AddClaim(new Claim(ClaimTypes.Name, context.UserName));
            //oAuthIdentity.AddClaim(new Claim("sub", context.UserName));
            //oAuthIdentity.AddClaim(new Claim(ClaimTypes.Role, "SuperAdmin"));


            //var props = new AuthenticationProperties(new Dictionary<string, string>
            //    {
            //        {
            //            "as:client_id", (context.ClientId == null) ? string.Empty : context.ClientId
            //        },
            //        {
            //            "userName", context.UserName
            //        }
            //    });

            //var ticket = new AuthenticationTicket(oAuthIdentity, props);

            //var ticket = new AuthenticationTicket(oAuthIdentity, null);

            //context.Validated(ticket);
            //context.Validated(oAuthIdentity);
        }
Example #19
0
        public override async Task GrantResourceOwnerCredentials(OAuthGrantResourceOwnerCredentialsContext context)
        {
            int state    = 0; // {0. Basic User; 1. Portal Admin; 2. WSSAdmin }
            var client   = _repo.FindClient(context.ClientId);
            var customer = "";
            var cusId    = 0;

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

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

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

            var userManager = context.OwinContext.GetUserManager <ApplicationUserManager>();
            var roleManager = new RoleManager <IdentityRole>(new RoleStore <IdentityRole>(new ApplicationDbContext()));

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

            var rolesForUser = await userManager.GetRolesAsync(user.Id);

            var serialRoles = Newtonsoft.Json.JsonConvert.SerializeObject(rolesForUser);

            // get the client company
            var clientUser = _repo.FindClientUserByUserId(user.Id);

            if (clientUser != null)
            {
                var sidClient = await _repo2.FindSidClientId(clientUser.SidClientId);

                customer = sidClient.Name;
                cusId    = sidClient.Id;
            }

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

            if (!user.EmailConfirmed)
            {
                context.SetError("invalid_grant", "User did not confirm email.");
                return;
            }

            var props = new AuthenticationProperties(new Dictionary <string, string>
            {
                {
                    "as:client_id", (context.ClientId == null) ? string.Empty : context.ClientId
                },
                {
                    "userName", context.UserName
                },
                {
                    "fullName", user.FirstName + " " + user.LastName
                },
                {
                    "access", (client.IsPublic == false) ? "Public" : "Private"
                },
                {
                    "roles", serialRoles
                },
                {
                    "customer", customer
                },
                {
                    "customerId", cusId.ToString()
                }
            });


            ClaimsIdentity oAuthIdentity = await user.GenerateUserIdentityAsync(userManager, "JWT");

            oAuthIdentity.AddClaims(ExtendedClaimsProvider.GetClaims(user));
            oAuthIdentity.AddClaims(RolesFromClaims.CreateRolesBasedOnClaims(oAuthIdentity));

            var ticket = new AuthenticationTicket(oAuthIdentity, props);

            context.Validated(ticket);
        }
Example #20
0
        public override async Task GrantResourceOwnerCredentials(OAuthGrantResourceOwnerCredentialsContext context)
        {
            var allowedOrigin = "*";

            try
            {
                //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)
                {
                    context.SetError("invalid_grant", "The user name or password is incorrect.");
                    return;
                }

                if (!user.EmailConfirmed)
                {
                    context.SetError("invalid_grant", "User did not confirm email.");
                    return;
                }

                iAuthContext con = new AuthContext();

                if (string.IsNullOrEmpty(user.ApkName))
                {
                    People p      = con.getPersonIdfromEmail(user.Email);
                    int    UserId = p.PeopleID;
                    if (!p.Active)
                    {
                        context.SetError("invalid_grant", "Please check your registered email address to validate email address.");
                        return;
                    }
                    if (UserId == 0)
                    {
                        context.SetError("invalid_grant", "The user name or password is incorrect.");
                        return;
                    }

                    ClaimsIdentity identity = await user.GenerateUserIdentityAsync(userManager, "JWT");

                    identity.AddClaims(ExtendedClaimsProvider.GetClaims(user));
                    identity.AddClaims(RolesFromClaims.CreateRolesBasedOnClaims(identity));

                    //UserAccessPermission uap = con.getRoleDetail(p.Permissions); // Get Role Access Detail
                    var rolesIds = user.Roles.Select(x => x.RoleId).ToList();


                    //var identity = new ClaimsIdentity(context.Options.AuthenticationType);
                    //identity.AddClaims(ExtendedClaimsProvider.GetClaims(user));
                    identity.AddClaims(RolesFromClaims.CreateRolesBasedOnClaims(identity));
                    identity.AddClaim(new Claim(ClaimTypes.Name, context.UserName));
                    identity.AddClaim(new Claim(ClaimTypes.Role, p.Permissions));
                    identity.AddClaim(new Claim("firsttime", "true"));
                    identity.AddClaim(new Claim("compid", p.CompanyId.ToString()));
                    identity.AddClaim(new Claim("email", user.Email));
                    identity.AddClaim(new Claim("Email", user.Email.ToString()));
                    identity.AddClaim(new Claim("Level", user.Level.ToString()));
                    identity.AddClaim(new Claim("userid", UserId.ToString()));
                    identity.AddClaim(new Claim("DisplayName", p.DisplayName));
                    identity.AddClaim(new Claim("username", (p.PeopleFirstName + " " + p.PeopleLastName).ToString()));
                    identity.AddClaim(new Claim("userid", UserId.ToString()));
                    identity.AddClaim(new Claim("Roleids", string.Join(",", rolesIds)));
                    //identity.AddClaim(new Claim("pagePermissions", JsonConvert.SerializeObject(pagePermissions)));
                    User_Id = UserId;
                    ac_Type = p.Permissions;
                    var props = new AuthenticationProperties(new Dictionary <string, string> {
                    });
                    if (p.Permissions == "HQ Master login")
                    {
                        props = new AuthenticationProperties(new Dictionary <string, string>
                        {
                            { "as:client_id", (context.ClientId == null) ? string.Empty : context.ClientId },
                            { "userName", context.UserName },
                            { "compid", p.CompanyId.ToString() },
                            { "Level", user.Level.ToString() },
                            { "role", p.Permissions },
                            { "email", user.Email },
                            { "userid", UserId.ToString() },
                            { "LScode", p.LScode },


                            // { "pagePermissions", JsonConvert.SerializeObject(pagePermissions)}
                        });
                    }
                    else
                    {
                        props = new AuthenticationProperties(new Dictionary <string, string>
                        {
                            { "as:client_id", (context.ClientId == null) ? string.Empty : context.ClientId },
                            { "userName", context.UserName },
                            { "compid", user.PhoneNumber },
                            { "role", p.Permissions },
                            { "Level", user.Level.ToString() },
                            { "email", user.Email },
                            { "userid", UserId.ToString() },


                            //{ "pagePermissions", JsonConvert.SerializeObject(pagePermissions)}
                        });
                    }
                    var ticket = new AuthenticationTicket(identity, props);
                    context.Validated(ticket);
                }
                else  // Authorize APK
                {
                    ClaimsIdentity identity = await user.GenerateUserIdentityAsync(userManager, "JWT");

                    identity.AddClaims(ExtendedClaimsProvider.GetClaims(user));
                    identity.AddClaims(RolesFromClaims.CreateRolesBasedOnClaims(identity));
                    identity.AddClaim(new Claim("AppName", user.ApkName));

                    var props = new AuthenticationProperties(new Dictionary <string, string> {
                    });

                    props = new AuthenticationProperties(new Dictionary <string, string>
                    {
                        { "as:client_id", (context.ClientId == null) ? string.Empty : context.ClientId },
                        { "userName", context.UserName },
                        { "AppName", user.ApkName }
                    });


                    var ticket = new AuthenticationTicket(identity, props);
                    context.Validated(ticket);
                }
            }
            catch (Exception ex)
            {
                logger.Error("Unable to validate user {0}", context.UserName);
                logger.Error(ex.InnerException != null ? ex.InnerException.ToString() : ex.ToString());
            }
        }