Example #1
1
 private async Task SignInAsync(ApplicationUser user, bool isPersistent)
 {
     AuthenticationManager.SignOut(DefaultAuthenticationTypes.ExternalCookie);
     AuthenticationManager.SignIn(new AuthenticationProperties() { IsPersistent = isPersistent }, await user.GenerateUserIdentityAsync(UserManager));
 }
Example #2
0
        public async Task SignInAsync(ApplicationUser user, bool isPersistent, bool rememberBrowser)
        {
            // Clear any partial cookies from external or two factor partial sign ins
            AuthenticationManager.SignOut(DefaultAuthenticationTypes.ExternalCookie,
                DefaultAuthenticationTypes.TwoFactorCookie);

            var userIdentity = await user.GenerateUserIdentityAsync(UserManager);

            if (rememberBrowser)
            {
                var rememberBrowserIdentity =
                    AuthenticationManager.CreateTwoFactorRememberBrowserIdentity(user.Id);

                AuthenticationManager.SignIn(
                    new AuthenticationProperties { IsPersistent = isPersistent },
                    userIdentity,
                    rememberBrowserIdentity);
            }
            else
            {
                AuthenticationManager.SignIn(
                    new AuthenticationProperties { IsPersistent = isPersistent },
                    userIdentity);
            }
        }
        public override async Task GrantResourceOwnerCredentials(OAuthGrantResourceOwnerCredentialsContext context)
        {
            var userManager = context.OwinContext.GetUserManager<ApplicationUserManager>();

            ApplicationUser user = new ApplicationUser
            {
                Email = "*****@*****.**",
                PasswordHash = "password"
            };


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

            AuthenticationProperties properties = CreateProperties(user.UserName);
            AuthenticationTicket ticket = new AuthenticationTicket(oAuthIdentity, properties);
            context.Validated(ticket);
            context.Request.Context.Authentication.SignIn(cookiesIdentity);
        }
        public override async Task GrantResourceOwnerCredentials(OAuthGrantResourceOwnerCredentialsContext context)
        {
            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;
            }

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

            ClaimsIdentity cookiesIdentity = await user.GenerateUserIdentityAsync(userManager,
                                                                                  CookieAuthenticationDefaults.AuthenticationType);

            AuthenticationProperties properties = CreateProperties(user.UserName);
            AuthenticationTicket     ticket     = new AuthenticationTicket(oAuthIdentity, properties);

            context.Validated(ticket);
            context.Request.Context.Authentication.SignIn(cookiesIdentity);
        }
        public override async Task GrantResourceOwnerCredentials(OAuthGrantResourceOwnerCredentialsContext context)
        {
            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;
            }
            else
            {
                var DB = new BugTrackerEntities();

                var appUser = DB.Users.Where(a => a.Id == user.UserId).FirstOrDefault();

                if (appUser != null && appUser.IsDeleted)
                {
                    context.SetError("invalid_grant", "This account is removed or has no access to the system.");
                    return;
                }
            }

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

            ClaimsIdentity cookiesIdentity = await user.GenerateUserIdentityAsync(userManager,
                                                                                  CookieAuthenticationDefaults.AuthenticationType);

            AuthenticationProperties properties = CreateProperties(user.UserName, user.UserId);
            AuthenticationTicket     ticket     = new AuthenticationTicket(oAuthIdentity, properties);

            context.Validated(ticket);
            context.Request.Context.Authentication.SignIn(cookiesIdentity);
        }
Example #6
0
        public override async Task GrantResourceOwnerCredentials(OAuthGrantResourceOwnerCredentialsContext context)
        {
            var allowedOrigin = context.OwinContext.Get <string>(Startup.ClientAllowedOriginPropertyName);

            if (string.IsNullOrWhiteSpace(allowedOrigin))
            {
                allowedOrigin = "*";                 // NOTE: CORS 관련 정책 변경 시 수정
            }

            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.Rejected();
                context.SetError("invalid_grant", "The username or password is incorrect.");

                return;
            }

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

                return;
            }

            // NOTE: user locking 정책 변경 시 로직 추가
            ClaimsIdentity oAuthIdentity = await user.GenerateUserIdentityAsync(userManager, "JWT");

            // 확장클레임 추가 부분
            oAuthIdentity.AddClaim(new Claim(ClaimTypes.Name, context.UserName));
            oAuthIdentity.AddClaim(new Claim("sub", context.UserName));
            // NOTE: Role 추가 여부 결정

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

            var ticket = new AuthenticationTicket(oAuthIdentity, props);

            context.Validated(ticket);
        }
Example #7
0
        private async Task SignInAsync(ApplicationUser user, bool isPersistent)
        {
            var clientKey = Request.Browser.Type;
            await UserManager.SignInClientAsync(user, clientKey);
            // Zerando contador de logins errados.
            await UserManager.ResetAccessFailedCountAsync(user.Id);

            // Coletando Claims externos (se houver)
            ClaimsIdentity ext = await AuthenticationManager.GetExternalIdentityAsync(DefaultAuthenticationTypes.ExternalCookie);

            AuthenticationManager.SignOut(DefaultAuthenticationTypes.ExternalCookie, DefaultAuthenticationTypes.TwoFactorCookie, DefaultAuthenticationTypes.ApplicationCookie);
            AuthenticationManager.SignIn
                (
                    new AuthenticationProperties { IsPersistent = isPersistent }, 
                    // Criação da instancia do Identity e atribuição dos Claims
                    await user.GenerateUserIdentityAsync(UserManager, ext)
                );
        }
Example #8
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 });



            AuthRepository _repo = new AuthRepository();

            ApplicationUser user = await _repo.FindUser(context.UserName, context.Password);

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

            //var identity = new ClaimsIdentity(context.Options.AuthenticationType);
            var identity = await user.GenerateUserIdentityAsync(_repo._userManager, "JWT");

            identity.AddClaim(new Claim(ClaimTypes.Name, context.UserName));


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

            var ticket = new AuthenticationTicket(identity, props);

            context.Validated(ticket);
        }
Example #9
0
        public async Task SignInAsync(ApplicationUser user, bool isPersistent, bool rememberBrowser)
        {
            // Clear any partial cookies from external or two factor partial sign ins
            AuthenticationManager.SignOut(DefaultAuthenticationTypes.ExternalCookie, DefaultAuthenticationTypes.TwoFactorCookie);
            var userIdentity = await user.GenerateUserIdentityAsync(UserManager);

            if (rememberBrowser)
            {
                var rememberBrowserIdentity = AuthenticationManager.CreateTwoFactorRememberBrowserIdentity(user.Id);
                AuthenticationManager.SignIn(new AuthenticationProperties {
                    IsPersistent = isPersistent
                }, userIdentity, rememberBrowserIdentity);
            }
            else
            {
                AuthenticationManager.SignIn(new AuthenticationProperties {
                    IsPersistent = isPersistent
                }, userIdentity);
            }
        }
Example #10
0
        public async Task <ActionResult> Login(LoginViewModel model, string returnUrl)
        {
            if (!ModelState.IsValid)
            {
                return(View(model));
            }

            //ApplicationUser user = await UserManager.FindAsync(model.UserName, model.Password);
            //ClaimsIdentity oAuthIdentity = await user.GenerateUserIdentityAsync(UserManager);
            //var claimsPrincipal = new ClaimsPrincipal(oAuthIdentity);
            //// Set current principal
            //Thread.CurrentPrincipal = claimsPrincipal;

            // This doesn't count login failures towards account lockout
            // To enable password failures to trigger account lockout, change to shouldLockout: true
            var result = await SignInManager.PasswordSignInAsync(model.UserName, model.Password, model.RememberMe, shouldLockout : false);

            switch (result)
            {
            case SignInStatus.Success:
                ApplicationUser user = await UserManager.FindAsync(model.UserName, model.Password);

                ClaimsIdentity oAuthIdentity = await user.GenerateUserIdentityAsync(UserManager);

                var claimsPrincipal = new ClaimsPrincipal(oAuthIdentity);
                // Set current principal
                Thread.CurrentPrincipal = claimsPrincipal;
                return(RedirectToLocal(returnUrl));

            case SignInStatus.LockedOut:
                return(View("Lockout"));

            case SignInStatus.RequiresVerification:
                return(RedirectToAction("SendCode", new { ReturnUrl = returnUrl, RememberMe = model.RememberMe }));

            case SignInStatus.Failure:
            default:
                ModelState.AddModelError("", "Invalid login attempt.");
                return(View(model));
            }
        }
        public override async Task GrantResourceOwnerCredentials(OAuthGrantResourceOwnerCredentialsContext context)
        {
            var userManager = context.OwinContext.GetUserManager <ApplicationUserManager>();

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

            if (user == null)
            {
                context.SetError("invalid_grant", "Имя пользователя или пароль указаны неправильно.");
                return;
            }

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

            List <Claim> roles = oAuthIdentity.Claims.Where(c => c.Type == ClaimTypes.Role).ToList();

            // Сериализация существующих ролей пользователя в строку JSON
            AuthenticationProperties properties = CreateProperties(user.UserName, Newtonsoft.Json.JsonConvert.SerializeObject(roles.Select(x => x.Value)));
            AuthenticationTicket     ticket     = new AuthenticationTicket(oAuthIdentity, properties);

            context.Validated(ticket);
        }
Example #12
0
 private async Task SignInAsync(ApplicationUser user, bool isPersistent)
 {
     var clientKey = Request.Browser.Type;
     await UserManager.SignInClientAsync(user, clientKey);
     AuthenticationManager.SignOut(DefaultAuthenticationTypes.ExternalCookie, DefaultAuthenticationTypes.TwoFactorCookie);
     AuthenticationManager.SignIn(new AuthenticationProperties { IsPersistent = isPersistent }, await user.GenerateUserIdentityAsync(UserManager));
 }
Example #13
0
        public async Task <IHttpActionResult> RegisterExternal()
        {
            var info = await Authentication.GetExternalLoginInfoAsync();

            if (info == null)
            {
                return(InternalServerError());
            }
            string firstName;
            string lastName;
            string gender;

            if (info.Login.LoginProvider == "Google")
            {
                var externalIdentity = Authentication.GetExternalIdentityAsync(DefaultAuthenticationTypes.ExternalCookie);
                lastName  = externalIdentity.Result.Claims.FirstOrDefault(c => c.Type == ClaimTypes.Surname).Value;
                firstName = externalIdentity.Result.Claims.FirstOrDefault(c => c.Type == ClaimTypes.GivenName).Value;
                //         birthday = externalIdentity.Result.Claims.FirstOrDefault(c => c.Type == ClaimTypes.DateOfBirth).Value;
                gender = "male";
            }
            else
            {
                var accessToken = Authentication.GetExternalIdentity(DefaultAuthenticationTypes.ExternalCookie).FindFirstValue("FacebookAccessToken");
                var fb          = new FacebookClient(accessToken);
                //    dynamic aaa = fb.Get("/me");
                dynamic myInfo = fb.Get("/me?fields=id,email,first_name,last_name,gender");
                lastName  = myInfo["last_name"];
                firstName = myInfo["first_name"];
                gender    = myInfo["gender"];
            }
            Gender _gender = Gender.MALE;

            if (gender.Equals("female"))
            {
                _gender = Gender.FEMALE;
            }



            var userExtend = new Model.Model.UserExtend();

            var user = new ApplicationUser()
            {
                UserName       = info.Email,
                Email          = info.Email,
                FirstName      = firstName,
                LastName       = lastName,
                User           = userExtend,
                EmailConfirmed = true,
                Birthday       = null,
                Gender         = _gender
            };

            try
            {
                IdentityResult result = await UserManager.CreateAsync(user);

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


                result = await UserManager.AddLoginAsync(user.Id, info.Login);

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

                result = await UserManager.AddToRoleAsync(user.Id, "User");

                if (!result.Succeeded)
                {
                    return(GetErrorResult(result));
                }
                ClaimsIdentity oAuthIdentity = await user.GenerateUserIdentityAsync(UserManager,
                                                                                    OAuthDefaults.AuthenticationType);

                ClaimsIdentity cookieIdentity = await user.GenerateUserIdentityAsync(UserManager,
                                                                                     CookieAuthenticationDefaults.AuthenticationType);

                var role   = oAuthIdentity.Claims.Where(c => c.Type == ClaimTypes.Role).FirstOrDefault().Value;
                var userId = oAuthIdentity.Claims.Where(c => c.Type == ClaimTypes.NameIdentifier).FirstOrDefault().Value;
                AuthenticationProperties properties = ApplicationOAuthProvider.CreateProperties(user.UserName, role, userId);
                Authentication.SignIn(properties, oAuthIdentity, cookieIdentity);
                return(Ok(properties.Dictionary));
            }
            catch (Exception)
            {
                return(BadRequest());
            }
        }
 private async Task SignInAsync(ApplicationUser user, bool isPersistent)
 {
     AuthenticationManager.SignOut(DefaultAuthenticationTypes.ExternalCookie);
     var identity = await user.GenerateUserIdentityAsync(UserManager);
     identity.AddClaim(new Claim("FirstName", user.FirstName));
     identity.AddClaim(new Claim("LastName", user.LastName));
     AuthenticationManager.SignIn(new AuthenticationProperties { IsPersistent = isPersistent }, identity);
 }
        public override async Task GrantResourceOwnerCredentials(OAuthGrantResourceOwnerCredentialsContext context)
        {
            try
            {
                UnitOfWork unitOfWork  = new UnitOfWork();
                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;
                }
                var roles = userManager.GetRoles(user.Id);
                var scope = context.Scope.ToList();
                var str   = context.Scope[0];

                var customerId = Convert.ToInt32(!str.Contains("*")?str:str.Split('*')[0]);
                var app        = !str.Contains("*")?"x": str.Split('*')[1];

                if (app == "ap")
                {
                    var ap_roles = roles.Where(q => q == "Admin" || q == "User").ToList();
                    if (ap_roles.Count == 0)
                    {
                        context.SetError("invalid_grant", "The user name or password is incorrect.");
                        return;
                    }
                }
                var employee = await unitOfWork.PersonRepository.GetViewEmployeesByUserId(user.Id, customerId);


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

                ClaimsIdentity cookiesIdentity = await user.GenerateUserIdentityAsync(userManager,
                                                                                      CookieAuthenticationDefaults.AuthenticationType);

                oAuthIdentity.AddClaim(new Claim(ClaimTypes.Name, context.UserName));
                oAuthIdentity.AddClaim(new Claim(ClaimTypes.Role, "user"));
                oAuthIdentity.AddClaim(new Claim("sub", context.UserName));
                oAuthIdentity.AddClaim(new Claim(ClaimTypes.Name, "Vahid"));

                AuthenticationProperties properties = CreateProperties(user.UserName, (context.ClientId == null) ? string.Empty : context.ClientId);
                if (employee != null)
                {
                    properties.Dictionary.Add("Name", employee.Name);
                    properties.Dictionary.Add("UserId", employee.PersonId.ToString());
                    properties.Dictionary.Add("EmployeeId", employee.Id.ToString());
                    properties.Dictionary.Add("Roles", string.Join(",", roles));
                }
                //if (employees.Count > 0)
                // {
                //     var customers =string.Join("_", employees.Select(q => q.CustomerId).Distinct().ToArray());
                //     var name = employees.First().Name;


                // }
                // properties.Dictionary.Add("Name", "Vahid Moghaddam");
                AuthenticationTicket ticket = new AuthenticationTicket(oAuthIdentity, properties);
                context.Validated(ticket);
                context.Request.Context.Authentication.SignIn(cookiesIdentity);
            }
            catch (Exception ex)
            {
                int i = 0;
            }
        }
Example #16
0
 private async Task SignInAsync(ApplicationUser user)
 {
     AuthenticationManager.SignOut(DefaultAuthenticationTypes.ApplicationCookie);
     AuthenticationManager.SignIn(await user.GenerateUserIdentityAsync(UserManager, DefaultAuthenticationTypes.ApplicationCookie));
 }
Example #17
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[] { "*" });

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

            if (context.Password == ResourceStrings.DefaultPassword)
            {
                context.SetError("invalid_grant", ResourceStrings.ChangeDefaultPassword);
                return;
            }

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


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

            var claims = new List <Claim>()
            {
                new Claim(ClaimTypes.Email, user.Email),
                new Claim(ClaimTypes.Sid, user.Id)
            };


            StringBuilder roles = new StringBuilder();

            // add all roles to the claim

            //foreach (string role in await _aspNetUserRolesRepository.GetUsersRoles(user.Id, true))
            //{
            //	claims.Add(new Claim(ClaimTypes.Role, role));
            //	roles.Append("," + role);

            //}

            //add new properties here.
            var properties = new AuthenticationProperties(new Dictionary <string, string>
            {
                { "email", user.UserName },
                { "userId", user.Id }
            });


            //add all priviliges to the claim

            foreach (var item in  await userManager.GetClaimsAsync(user.Id))
            {
                claims.Add(new Claim("Privilege", item.Value));
            }

            // add OrganisationId to the claim


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

            oAuthIdentity.AddClaims(claims);



            AuthenticationTicket ticket = new AuthenticationTicket(oAuthIdentity, properties);

            context.Validated(ticket);
            // context.Request.Context.Authentication.SignIn(cookiesIdentity);
        }
Example #18
0
        /// <summary>
        /// First - NovellProvider, then OAuth Provider
        /// </summary>
        /// <param name="context"></param>
        /// <returns></returns>
        public override async Task GrantResourceOwnerCredentials(OAuthGrantResourceOwnerCredentialsContext context)
        {
            var userManager = context.OwinContext.GetUserManager <ApplicationUserManager>();

            try
            {
                NovellUser      novelleDirectoryUser = novell.Connect(context.UserName.Trim(), context.Password.Trim());
                ApplicationUser applicationUser      = userManager.Find(context.UserName.Trim(), context.Password.Trim());
                //Особенности нашего обращения с Novell, ничего не попишешь
                if (applicationUser == null)
                {
                    //на случай, если пароль поменяли
                    applicationUser = await ChangePassword(context.UserName.Trim(), context.Password.Trim(), userManager);
                }
                if (applicationUser == null)
                {
                    //если человек есть в Novell eDirectory, но нет в AspNetUSers
                    applicationUser = CreateUser(context.UserName.Trim(), context.Password.Trim(), novelleDirectoryUser, userManager);
                }

                if (!novelleDirectoryUser.IsAlien)
                {
                    NovellGroupWisePostOfficeConnection postOfficeConnection = novellGroupWise.Connect(context.UserName.Trim(), context.Password.Trim());
                    applicationUser.PostOfficeAddress  = postOfficeConnection.PostOffice;
                    applicationUser.GroupWiseSessionId = postOfficeConnection.SessionId;
                }



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

                ClaimsIdentity cookiesIdentity = await applicationUser.GenerateUserIdentityAsync(userManager,
                                                                                                 CookieAuthenticationDefaults.AuthenticationType);


                AuthenticationProperties properties = CreateProperties(applicationUser.UserName);
                AuthenticationTicket     ticket     = new AuthenticationTicket(oAuthIdentity, properties);
                context.Validated(ticket);
                context.Request.Context.Authentication.SignIn(cookiesIdentity);
            }
            catch (NovellGroupWiseException ngwe)
            {
                context.SetError("invalid_grant", "Username or password is incorrect");
                context.Response.Headers.Add(Constants.OwinChallengeFlag, new[] { ((int)HttpStatusCode.Unauthorized).ToString() });
            }

            catch (NovelleDirectoryException nede)
            {
                //если человека нет в Novell - это и только это показатель того, что его никуда не надо пускать
                context.SetError("invalid_grant", "Username or password is incorrect");
                context.Response.Headers.Add(Constants.OwinChallengeFlag, new[] { ((int)HttpStatusCode.Unauthorized).ToString() });
                return;
            }

            catch (FailedDatabaseConnectionException fdce)
            {
                context.SetError("invalid_grant", fdce.Message);
                context.Response.Headers.Add(Constants.OwinChallengeFlag, new[] { ((int)HttpStatusCode.Unauthorized).ToString() });
            }
            catch (Exception e)
            {
                context.SetError("invalid_grant", e.Message);
                context.Response.Headers.Add(Constants.OwinChallengeFlag, new[] { ((int)HttpStatusCode.Unauthorized).ToString() });
            }
        }
Example #19
0
        //ati login
        public override async Task GrantResourceOwnerCredentials(OAuthGrantResourceOwnerCredentialsContext context)
        {
            try
            {
                UnitOfWork unitOfWork  = new UnitOfWork();
                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;
                }
                var roles = userManager.GetRoles(user.Id).First();


                var scope      = context.Scope.ToList();
                var customerId = Convert.ToInt32(context.Scope[0]);



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

                ClaimsIdentity cookiesIdentity = await user.GenerateUserIdentityAsync(userManager,
                                                                                      CookieAuthenticationDefaults.AuthenticationType);

                oAuthIdentity.AddClaim(new Claim(ClaimTypes.Name, context.UserName));
                if (roles == "Company")
                {
                    oAuthIdentity.AddClaim(new Claim(ClaimTypes.Role, "Company"));
                }
                else if (roles == "User")
                {
                    oAuthIdentity.AddClaim(new Claim(ClaimTypes.Role, "nuser"));
                }
                else
                {
                    oAuthIdentity.AddClaim(new Claim(ClaimTypes.Role, "user"));
                }


                oAuthIdentity.AddClaim(new Claim("sub", context.UserName));
                oAuthIdentity.AddClaim(new Claim(ClaimTypes.Name, "Vahid"));

                AuthenticationProperties properties = CreateProperties(user.UserName, (context.ClientId == null) ? string.Empty : context.ClientId);

                if (roles == "Company")
                {
                    var company = await unitOfWork.CompanyRepository.GetViewCompanyByEmail(context.UserName);

                    if (company != null)
                    {
                        properties.Dictionary.Add("Name", company.Name);
                        properties.Dictionary.Add("UserId", company.Id.ToString());
                        properties.Dictionary.Add("Image", string.IsNullOrEmpty(company.ImageUrl) ?"": company.ImageUrl.ToString());
                        properties.Dictionary.Add("Role", "Company");
                        //   properties.Dictionary.Add("EmployeeId", employee.Id.ToString());
                    }
                }
                else
                {
                    ViewPerson person = await unitOfWork.PersonRepository.GetViewPersonByUserId(user.Id);

                    if (person != null)
                    {
                        properties.Dictionary.Add("Name", person.Name);
                        properties.Dictionary.Add("UserId", person.Id.ToString());
                        properties.Dictionary.Add("Image", person.ImageUrl.ToString());
                        properties.Dictionary.Add("Role", roles != "User"? "Person":"User");
                        //   properties.Dictionary.Add("EmployeeId", employee.Id.ToString());
                    }
                }


                AuthenticationTicket ticket = new AuthenticationTicket(oAuthIdentity, properties);
                context.Validated(ticket);
                context.Request.Context.Authentication.SignIn(cookiesIdentity);
            }
            catch (Exception ex)
            {
                int i = 0;
            }
        }
        public override async Task GrantResourceOwnerCredentials(OAuthGrantResourceOwnerCredentialsContext context)
        {
            IOwinRequest  req = context.Request;
            IOwinResponse res = context.Response;

            //Add this Response header as just enabling the Wev API Cors wont enable it for this provider request

            //context.OwinContext.Response.Headers.Add("Access-Control-Allow-Origin", new[] { "http://localhost:8267" });
            //context.OwinContext.Response.Headers.Add("Access-Control-Allow-Credentials", new[] { "true" });

            //var origin = req.Headers.Get("Origin");

            //if (!string.IsNullOrEmpty(origin))
            //{
            //    // allow the cross-site requests

            //    if (!string.IsNullOrEmpty(origin))
            //    {
            //        //context.OwinContext.Response.Headers.Add("Access-Control-Allow-Origin", new[] { "http://localhost:8267" });
            //        res.Headers.Set("Access-Control-Allow-Origin", origin);
            //    }
            //    //if (string.IsNullOrEmpty(res.Headers.Get("Access-Control-Allow-Credentials")))
            //    //{
            //    //    //context.OwinContext.Response.Headers.Add("Access-Control-Allow-Credentials", new[] { "true" });
            //    //    res.Headers.Set("Access-Control-Allow-Credentials", "true");
            //    //}
            //}

            //// if this is pre-flight request
            //if (req.Method == "OPTIONS")
            //{
            //    //res.Headers.Add("Access-Control-Allow-Headers", new[] { "Content-Type", "X-CSRF-Token", "X-Requested-With", "Accept", "Accept-Version", "Content-Length", "Content-MD5", "Date", "X-Api-Version", "X-File-Name" });

            //    // respond immediately with allowed request methods and headers
            //    res.StatusCode = 200;
            //    res.Headers.AppendCommaSeparatedValues("Access-Control-Allow-Methods", "GET", "POST", "DELETE", "PUT", "PATCH", "OPTIONS");
            //    res.Headers.AppendCommaSeparatedValues("Access-Control-Allow-Headers", "authorization", "content-type");

            //    if (string.IsNullOrEmpty(res.Headers.Get("Access-Control-Allow-Credentials")))
            //    {
            //        res.Headers.Set("Access-Control-Allow-Credentials", "true");
            //    }

            //}

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

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

            ClaimsIdentity cookiesIdentity = await user.GenerateUserIdentityAsync(userManager,
                                                                                  CookieAuthenticationDefaults.AuthenticationType);

            AuthenticationProperties properties = CreateProperties(user.UserName);
            AuthenticationTicket     ticket     = new AuthenticationTicket(oAuthIdentity, properties);

            context.Validated(ticket);
            context.Request.Context.Authentication.SignIn(cookiesIdentity);
        }
Example #21
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>();

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

            if (user == null)
            {
                context.SetError("invalid_grant", "Tên đăng nhập hoặc mật khẩu không đúng");
                return;
            }
            else if (user.LockoutEnabled == false && user.Deleted == true)
            {
                context.SetError("deleted", "Failed");
                return;
            }
            else if (user.LockoutEnabled == true)
            {
                context.SetError("locked_out", "Failed");
                return;
            }
            else
            {
                #region Customize

                VOffice.Model.UserDepartment            userInfo             = new Model.UserDepartment();
                VOffice.Repository.DepartmentRepository departmentRepository = new Repository.DepartmentRepository();
                userInfo = departmentRepository.GetUserMainOrganization(user.Id);
                #endregion Customize
                ClaimsIdentity oAuthIdentity = await user.GenerateUserIdentityAsync(userManager,
                                                                                    OAuthDefaults.AuthenticationType);

                string email = string.IsNullOrEmpty(user.Email) ? "" : user.Email;


                oAuthIdentity.AddClaim(new Claim("userId", user.Id));
                oAuthIdentity.AddClaim(new Claim("fullName", userInfo.FullName));
                oAuthIdentity.AddClaim(new Claim("firstName", userInfo.FirstName));
                oAuthIdentity.AddClaim(new Claim("email", email));
                oAuthIdentity.AddClaim(new Claim("username", user.UserName));
                oAuthIdentity.AddClaim(new Claim("position", userInfo.Position));
                oAuthIdentity.AddClaim(new Claim("staffCode", userInfo.StaffCode));

                oAuthIdentity.AddClaim(new Claim("phoneNumber", userInfo.PhoneNumber != null ? userInfo.PhoneNumber.ToString() : string.Empty));
                oAuthIdentity.AddClaim(new Claim("dateOfBirth", userInfo.DateOfBirth != null ? userInfo.DateOfBirth.Value.ToString("dd/MM/yyyy") : ""));
                oAuthIdentity.AddClaim(new Claim("gender", userInfo.Gender != null ? userInfo.Gender.Value.ToString() : "1"));
                oAuthIdentity.AddClaim(new Claim("avatar", userInfo.Avatar != null ? userInfo.Avatar.ToString() : string.Empty));
                oAuthIdentity.AddClaim(new Claim("leader", userInfo.Leader != null ? userInfo.Leader.Value.ToString() : "false"));
                oAuthIdentity.AddClaim(new Claim("seniorLeader", userInfo.SeniorLeader != null ? userInfo.SeniorLeader.Value.ToString() : "false"));
                oAuthIdentity.AddClaim(new Claim("superLeader", userInfo.SuperLeader != null ? userInfo.SuperLeader.Value.ToString() : "false"));
                oAuthIdentity.AddClaim(new Claim("signedBy", userInfo.SignedBy != null ? userInfo.SignedBy.Value.ToString() : "false"));
                oAuthIdentity.AddClaim(new Claim("googleAccount", userInfo.GoogleAccount != null ? userInfo.GoogleAccount.ToString() : string.Empty));

                oAuthIdentity.AddClaim(new Claim("departmentId", userInfo.DepartmentId.ToString()));
                oAuthIdentity.AddClaim(new Claim("parentDepartmentId", userInfo.RootDepartmentId.ToString()));
                oAuthIdentity.AddClaim(new Claim("office", userInfo.Office.ToString()));
                oAuthIdentity.AddClaim(new Claim("subDepartmentId", userInfo.SubDepartmentId.ToString()));
                oAuthIdentity.AddClaim(new Claim("ListSubDepartmentId", userInfo.ListSubDepartmentId));
                oAuthIdentity.AddClaim(new Claim("departmentShortName", userInfo.DepartmentShortName != null ? userInfo.DepartmentShortName.ToString() : string.Empty));
                oAuthIdentity.AddClaim(new Claim("departmentName", userInfo.DepartmentName != null ? userInfo.DepartmentName.ToString() : string.Empty));


                //remove rolesClaim
                //var roleManager = new RoleManager<IdentityRole>(new RoleStore<IdentityRole>());
                //var roles = roleManager.Roles.ToList();
                //foreach (var role in roles)
                //{
                //    try
                //    {
                //        oAuthIdentity.RemoveClaim(new Claim(ClaimTypes.Role, role.Name));
                //    }
                //    catch (Exception ex)
                //    { }
                //}

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

                foreach (var item in currentRoles)
                {
                    oAuthIdentity.AddClaim(new Claim(ClaimTypes.Role, item));
                }


                ClaimsIdentity cookiesIdentity = await user.GenerateUserIdentityAsync(userManager,
                                                                                      CookieAuthenticationDefaults.AuthenticationType);

                //AuthenticationProperties properties = CreateProperties(user.UserName);

                var properties = new AuthenticationProperties(new Dictionary <string, string>
                {
                    { "userId", user.Id },
                    { "fullName", userInfo.FullName },
                    { "firstName", userInfo.FirstName },
                    { "email", email },
                    { "username", user.UserName },
                    { "position", userInfo.Position },
                    { "staffCode", userInfo.StaffCode },
                    { "phoneNumber", userInfo.PhoneNumber != null ? userInfo.PhoneNumber.ToString() : string.Empty },
                    { "dateOfBirth", userInfo.DateOfBirth != null ? userInfo.DateOfBirth.Value.ToString("dd/MM/yyyy") : "" },
                    { "gender", userInfo.Gender != null ? userInfo.Gender.Value.ToString() : "1" },
                    { "avatar", userInfo.Avatar != null ? userInfo.Avatar.ToString() : string.Empty },
                    { "leader", userInfo.Leader != null ? userInfo.Leader.Value.ToString() : "false" },
                    { "seniorLeader", userInfo.SeniorLeader != null ? userInfo.SeniorLeader.Value.ToString() : "false" },
                    { "superLeader", userInfo.SuperLeader != null ? userInfo.SuperLeader.Value.ToString() : "false" },
                    { "signedBy", userInfo.SignedBy != null ? userInfo.SignedBy.Value.ToString() : "false" },
                    { "googleAccount", userInfo.GoogleAccount != null ? userInfo.GoogleAccount.ToString() : string.Empty },
                    { "departmentId", userInfo.DepartmentId.ToString() },
                    { "parentDepartmentId", userInfo.RootDepartmentId.ToString() },
                    { "office", userInfo.Office.ToString() },
                    { "subDepartmentId", userInfo.SubDepartmentId.ToString() },
                    { "ListSubDepartmentId", userInfo.ListSubDepartmentId },
                    { "departmentShortName", userInfo.DepartmentShortName != null?userInfo.DepartmentShortName.ToString():string.Empty },
                    { "departmentName", userInfo.DepartmentName != null?userInfo.DepartmentName.ToString():string.Empty }
                });
                AuthenticationTicket ticket = new AuthenticationTicket(oAuthIdentity, properties);
                context.Validated(ticket);
                context.Request.Context.Authentication.SignIn(cookiesIdentity);
            }
        }
 private async Task SignInAsync(ApplicationUser user, bool isPersistent)
 {
     AuthenticationManager.SignOut(DefaultAuthenticationTypes.ExternalCookie);
     //var identity = await UserManager.CreateIdentityAsync(user, DefaultAuthenticationTypes.ApplicationCookie);
     //identity.AddClaim(new Claim("FirstName", user.FirstName));
     //identity.AddClaim(new Claim("LastName", user.LastName));
     //identity.AddClaim(new Claim("Institution", user.Institution));
     AuthenticationManager.SignIn(new AuthenticationProperties() { IsPersistent = isPersistent }, await user.GenerateUserIdentityAsync(UserManager));
 }
Example #23
0
        public async Task <ActionResult> ExternalLoginCallback(string returnUrl)
        {
            var result = await AuthenticationManager.AuthenticateAsync(DefaultAuthenticationTypes.ExternalCookie);

            if (result?.Identity == null)
            {
                return(RedirectToAction("Login"));
            }

            var idClaim = result.Identity.FindFirst(ClaimTypes.NameIdentifier);

            if (idClaim == null)
            {
                return(RedirectToAction("Login"));
            }

            var login = new UserLoginInfo(idClaim.Issuer, idClaim.Value);

            // Sign in the user with this external login provider if the user already has a login
            ApplicationUser user = await UserManager.FindAsync(login);

            if (user != null)
            {
                ClaimsIdentity oAuthIdentity = await user.GenerateUserIdentityAsync(UserManager,
                                                                                    OAuthDefaults.AuthenticationType);

                ClaimsIdentity cookieIdentity = await user.GenerateUserIdentityAsync(UserManager,
                                                                                     CookieAuthenticationDefaults.AuthenticationType);

                AuthenticationProperties properties = ApplicationOAuthProvider.CreateProperties(user.UserName);
                Request.GetOwinContext().Authentication.SignIn(properties, oAuthIdentity, cookieIdentity);

                user.LastConsent = DateTime.UtcNow;
                await UserManager.UpdateAsync(user);

                return(RedirectToLocal(returnUrl));
            }
            else
            {
                RegisterExternalBindingModel model = new RegisterExternalBindingModel();

                if (idClaim.Issuer == "Facebook")
                {
                    // Get details from Facebook
                    var accessToken   = result.Identity.Claims.Where(c => c.Type.Equals("ExternalAccessToken")).Select(c => c.Value).FirstOrDefault();
                    Uri apiRequestUri = new Uri("https://graph.facebook.com/me?fields=id,first_name,last_name,email,picture.type(square)&access_token=" + accessToken);

                    using (var webClient = new WebClient())
                    {
                        var     json       = webClient.DownloadString(apiRequestUri);
                        dynamic jsonResult = JsonConvert.DeserializeObject(json);
                        model.Email       = jsonResult.email;
                        model.Given_name  = jsonResult.first_name;
                        model.Family_name = jsonResult.last_name;
                        model.Picture     = jsonResult.picture.data.url;
                    }
                }
                else
                {
                    // Get details from Google
                    var accessToken   = result.Identity.Claims.Where(c => c.Type.Equals("urn:google:accesstoken")).Select(c => c.Value).FirstOrDefault();
                    Uri apiRequestUri = new Uri("https://www.googleapis.com/oauth2/v2/userinfo?access_token=" + accessToken);

                    using (var webClient = new WebClient())
                    {
                        var     json       = webClient.DownloadString(apiRequestUri);
                        dynamic jsonResult = JsonConvert.DeserializeObject(json);
                        model.Email       = jsonResult.email;
                        model.Picture     = jsonResult.picture;
                        model.Family_name = jsonResult.family_name;
                        model.Given_name  = jsonResult.given_name;
                    }
                }

                var appUser = new ApplicationUser
                {
                    UserName     = model.Email,
                    Email        = model.Email,
                    ImageUrl     = model.Picture,
                    FirstName    = model.Given_name,
                    Surname      = model.Family_name,
                    DateCreated  = DateTime.UtcNow,
                    AuthProvider = idClaim.Issuer,
                    Trusted      = false,
                    LastConsent  = DateTime.UtcNow
                };

                ApplicationUser existingResult = await UserManager.FindByEmailAsync(appUser.Email);

                if (existingResult == null)
                {
                    // New user
                    IdentityResult createResult = await UserManager.CreateAsync(appUser);

                    if (!createResult.Succeeded)
                    {
                        return(RedirectToAction("Login"));
                    }
                }
                else
                {
                    // user already exists with that email
                    appUser = existingResult;
                }

                // Add this oauth login to the user account
                IdentityResult idResult = await UserManager.AddLoginAsync(appUser.Id, login);

                if (!idResult.Succeeded)
                {
                    return(RedirectToAction("Login"));
                }

                ClaimsIdentity oAuthIdentity = await appUser.GenerateUserIdentityAsync(UserManager,
                                                                                       OAuthDefaults.AuthenticationType);

                ClaimsIdentity cookieIdentity = await appUser.GenerateUserIdentityAsync(UserManager,
                                                                                        CookieAuthenticationDefaults.AuthenticationType);

                AuthenticationProperties properties = ApplicationOAuthProvider.CreateProperties(appUser.UserName);
                await SignInManager.SignInAsync(appUser, true, true);

                Request.GetOwinContext().Authentication.SignIn(properties, oAuthIdentity, cookieIdentity);

                return(RedirectToLocal(returnUrl));
            }
        }
Example #24
0
        // [ValidateAntiForgeryToken]
        public async Task <ActionResult> Login(LoginViewModel model, string returnUrl)
        {
            try
            {
                if (!ModelState.IsValid)
                {
                    return(View(model));
                }

                ApplicationUser usermodel = _userManager.Users.FirstOrDefault(m => m.UserName.Trim() == model.Email);
                if (usermodel != null)
                {
                    //string USERPERMISSION = SetUserPermissions(usermodel.Id);
                    var userIdentity = await _userManager.CreateIdentityAsync(usermodel, DefaultAuthenticationTypes.ApplicationCookie);

                    userIdentity.AddClaim(new Claim("FullName", usermodel.FullName));
                    userIdentity.AddClaim(new Claim("Email", usermodel.Email));
                    userIdentity.AddClaim(new Claim("DateCreated", usermodel.DateCreated.ToString("MM/dd/yyyy")));
                    // userIdentity.AddClaim(new Claim("UserPermission", USERPERMISSION));
                    var listIdentity = new List <ClaimsIdentity>();
                    listIdentity.Add(userIdentity);
                    ClaimsPrincipal c = new ClaimsPrincipal(listIdentity);
                    AuthenticationManager.SignIn(new AuthenticationProperties()
                    {
                        IsPersistent = model.RememberMe
                    }, userIdentity);
                }

                // This doesn't count login failures towards account lockout
                // To enable password failures to trigger account lockout, change to shouldLockout: true
                var result = await _signInManager.PasswordSignInAsync(model.Email, model.Password, model.RememberMe, shouldLockout : false);

                switch (result)
                {
                case SignInStatus.Success:
                    if (User.Identity.GetFullName() == string.Empty)
                    {
                        await usermodel.GenerateUserIdentityAsync(_userManager);
                    }
                    if (usermodel.IsFirstLogin)
                    {
                        return(RedirectToAction("SetFirstlogin", new { code = usermodel.Id.EncryptID() }));
                    }

                    return(RedirectToLocal(returnUrl));

                case SignInStatus.LockedOut:
                    return(View("Lockout"));

                case SignInStatus.RequiresVerification:
                    return(RedirectToAction("SendCode", new { ReturnUrl = returnUrl, RememberMe = model.RememberMe }));

                case SignInStatus.Failure:
                default:
                    ModelState.AddModelError("", "Invalid login attempt.");
                    return(View(model));
                }
            }
            catch (Exception ex)
            {
                _log.Error(ex);
                return(View(model));
            }
        }
Example #25
0
        /// <summary>
        /// используется для генерации токена
        /// </summary>
        /// <param name="context"></param>
        /// <returns></returns>
        public override async Task GrantResourceOwnerCredentials(OAuthGrantResourceOwnerCredentialsContext context)
        {
            //--------------   Если требуется получить токен:   -----------------------

            // 1. Клиент обращается к ресурсу /Token для получения токена
            
            // 2. Если в пришедшем запросе есть заголовок "grant_type" и он имеет значение "password", 
            // то система вызывает метод GrantResourceOwnerCredentials() у провайдера авторизации ApplicationOAuthProvider
            
            // 3. Провайдер авторизации обращается к классу ApplicationUserManager 
            // для валидации поступивших данных (логина и пароля) и по ним создает объект claims identity
            
            // 4. Если валидация прошла успешно, то провайдер авторизации создает аутентификационный тикет, 
			// который применяется для генерации токена

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

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

            if (user == null)
            {
                context.SetError("invalid_grant", "Имя пользователя или пароль указаны неправильно.");
                return;
            }

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

            //++
            // AuthenticationProperties properties = CreateProperties(user.UserName);
            //
            AuthenticationProperties properties = CreateProperties("userName", user.UserName);

            //
            //----------    Добавляем сведения о ролях текущего пользователя - только для целей отладки   >>> --------------------
            //
            string roles = "";
            bool is_user = await userManager.IsInRoleAsync(user.Id, "user");
            if (is_user)
            {
                roles = "user";                    
            }

            bool is_manager = await userManager.IsInRoleAsync(user.Id, "manager");
            if (is_manager)
            {
                if (!string.IsNullOrWhiteSpace(roles))
                    roles += ",";
                roles += "manager";
            }

            bool is_admin = await userManager.IsInRoleAsync(user.Id, "admin");
            if (is_admin)
            {
                if (!string.IsNullOrWhiteSpace(roles))
                    roles += ",";
                roles += "admin";
            }

            if (!string.IsNullOrWhiteSpace(roles))
            {
                properties.Dictionary.Add("userRoles", roles);
            }
            //
            //----------  <<<  Добавляем сведения о ролях текущего пользователя - только для целей отладки   --------------------
            //

            AuthenticationTicket ticket = new AuthenticationTicket(oAuthIdentity, properties);
            context.Validated(ticket);
            context.Request.Context.Authentication.SignIn(cookiesIdentity);
        }
        public override async Task GrantResourceOwnerCredentials(OAuthGrantResourceOwnerCredentialsContext context)
        {
            var             userManager      = context.OwinContext.GetUserManager <ApplicationUserManager>();
            var             _accountServices = new AccountServices();
            ApplicationUser user             = await userManager.FindAsync(context.UserName, context.Password);

            if (user.LockoutEnabled)
            {
                await Task.Factory.StartNew(() =>
                {
                    _accountServices.CreateLoginHistory(new MNG_HistoryLogin()
                    {
                        DateLogin = DateTime.Now,
                        UserName  = context.UserName,
                        Status    = "Thất bại: Tài khoản đang bị khóa.",
                        IP        = context.OwinContext.Request.RemoteIpAddress
                    });
                });

                context.SetError("invalid_grant", "Tài khoản đang bị khóa.");
                return;
            }

            if (user == null)
            {
                await Task.Factory.StartNew(() =>
                {
                    _accountServices.CreateLoginHistory(new MNG_HistoryLogin()
                    {
                        DateLogin = DateTime.Now,
                        UserName  = context.UserName,
                        Status    = "Thất bại: Sai tài khoản hoặc mật khẩu",
                        IP        = context.OwinContext.Request.RemoteIpAddress
                    });
                });

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

            await Task.Factory.StartNew(() =>
            {
                _accountServices.CreateLoginHistory(new MNG_HistoryLogin()
                {
                    DateLogin = DateTime.Now,
                    UserName  = context.UserName,
                    Status    = "Thành công",
                    IP        = context.OwinContext.Request.RemoteIpAddress
                });
            });


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

            ClaimsIdentity cookiesIdentity = await user.GenerateUserIdentityAsync(userManager,
                                                                                  CookieAuthenticationDefaults.AuthenticationType);

            // Create generic identity.
            MenuServices _menuServices = new MenuServices();


            IList <Claim> claims = new List <Claim>();

            claims.Add(new Claim("UserID", string.IsNullOrEmpty(user.Id) ? string.Empty : user.Id));
            claims.Add(new Claim("PhoneNumber", string.IsNullOrEmpty(user.PhoneNumber) ? string.Empty : user.PhoneNumber));
            claims.Add(new Claim("FullName", string.IsNullOrEmpty(user.FullName) ? string.Empty : user.FullName));
            claims.Add(new Claim("Email", string.IsNullOrEmpty(user.Email) ? string.Empty : user.Email));
            claims.Add(new Claim("Menus",
                                 string.IsNullOrEmpty(user.Id) ? string.Empty : _menuServices.GetMenu4ClaimsByUserId(user.Id.ToString())));
            oAuthIdentity.AddClaims(claims);

            AuthenticationProperties properties = CreateProperties(user.UserName);
            AuthenticationTicket     ticket     = new AuthenticationTicket(oAuthIdentity, properties);

            context.Validated(ticket);
            context.Request.Context.Authentication.SignIn(cookiesIdentity);
        }
Example #27
0
        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 = null;

            //bypass de validación de directorio activo
            if (Properties.Settings.Default.ambiente != "des")
            {   //validacion directorio activo
                var validaDA = directorioActivo.validaUsuarioLDAP(context.UserName, context.Password, Properties.Settings.Default.loginIntranet, Properties.Settings.Default.dominioDa);
                if (validaDA.existe)
                {
                    user = await userManager.FindAsync(context.UserName, context.UserName);

                    if (user == null)
                    {
                        context.SetError("Usuario no existe", "Usuario no existe registrado aplicativo SAX.");
                        return;
                    }
                    else if (user.Estatus == 0)
                    {
                        context.SetError("Usuario inactivo", "Usuario inactivo en aplicativo SAX.");
                        return;
                    }
                }
                else
                {
                    context.SetError("Usuario no existe", "El usuario no existe en el directorio activo.");
                    return;
                }
            }
            else
            {
                user = await userManager.FindAsync(context.UserName, context.UserName);

                if (user == null)
                {
                    context.SetError("Usuario no existe", "Usuario no existe registrado aplicativo SAX.");
                    return;
                }
                else if (user.Estatus == 0)
                {
                    context.SetError("Usuario inactivo", "Usuario inactivo en aplicativo SAX.");
                    return;
                }
            }

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

            ClaimsIdentity cookiesIdentity = await user.GenerateUserIdentityAsync(userManager,
                                                                                  CookieAuthenticationDefaults.AuthenticationType);

            AuthenticationProperties properties = CreateProperties(user.UserName);
            AuthenticationTicket     ticket     = new AuthenticationTicket(oAuthIdentity, properties);

            context.Validated(ticket);
            context.Request.Context.Authentication.SignIn(cookiesIdentity);
        }
Example #28
0
        public async Task <IHttpActionResult> GetExternalLogin(string provider, string error = null)
        {
            string redirectUri = string.Empty;

            if (error != null)
            {
                return(Redirect(Url.Content("~/") + "#error=" + Uri.EscapeDataString(error)));
            }

            if (!User.Identity.IsAuthenticated)
            {
                return(new ChallengeResult(provider, this));
            }

            ExternalLoginData externalLogin = ExternalLoginData.FromIdentity(User.Identity as ClaimsIdentity);

            if (externalLogin == null)
            {
                return(InternalServerError());
            }

            if (externalLogin.LoginProvider != provider)
            {
                Authentication.SignOut(DefaultAuthenticationTypes.ExternalCookie);
                return(new ChallengeResult(provider, this));
            }
            var redirectUriValidationResult = ValidateClientAndRedirectUri(this.Request, ref redirectUri);

            if (!string.IsNullOrWhiteSpace(redirectUriValidationResult))
            {
                return(BadRequest(redirectUriValidationResult));
            }

            ApplicationUser user = await UserManager.FindAsync(new UserLoginInfo(externalLogin.LoginProvider,
                                                                                 externalLogin.ProviderKey));

            bool hasRegistered = user != null;

            if (hasRegistered)
            {
                Authentication.SignOut(DefaultAuthenticationTypes.ExternalCookie);

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

                ClaimsIdentity cookieIdentity = await user.GenerateUserIdentityAsync(UserManager,
                                                                                     CookieAuthenticationDefaults.AuthenticationType);

                AuthenticationProperties properties = ApplicationOAuthProvider.CreateProperties(user.UserName);
                Authentication.SignIn(properties, oAuthIdentity, cookieIdentity);
            }
            else
            {
                IEnumerable <Claim> claims   = externalLogin.GetClaims();
                ClaimsIdentity      identity = new ClaimsIdentity(claims, OAuthDefaults.AuthenticationType);
                Authentication.SignIn(identity);
            }

            //redirectUri = string.Format("{0}#external_access_token={1}&provider={2}&haslocalaccount={3}&external_user_name={4}",
            //                                redirectUri,
            //                                externalLogin.ExternalAccessToken,
            //                                externalLogin.LoginProvider,
            //                                hasRegistered.ToString(),
            //                                externalLogin.UserName);

            redirectUri = string.Format("{0}#external_access_token={1}&provider={2}&haslocalaccount={3}&external_user_name={4}",
                                        redirectUri,
                                        externalLogin.ExternalAccessToken,
                                        externalLogin.LoginProvider,
                                        hasRegistered.ToString(),
                                        externalLogin.UserName);

            return(Redirect(redirectUri));
        }
        public override async Task GrantResourceOwnerCredentials(OAuthGrantResourceOwnerCredentialsContext context)
        {
            /*Gets Extra keys sent form the user's computer, however we will make this unnessesary
             * var data = await context.Request.ReadFormAsync();
             * string email = data.GetValues("email").First(); */

            //setup nessesary variables
            var             userManager = context.OwinContext.GetUserManager <ApplicationUserManager>();
            ApplicationUser user        = null;
            bool            loggedIn    = false;


            if (string.IsNullOrWhiteSpace(context.Password))                                                                   //check if valid password was provided
            {
                context.SetError(ErrorResponse.PasswordIsBad.error.ToString(), ErrorResponse.PasswordIsBad.error_description); //rejects, password is wrong
                return;
            }
            else
            {
                user = await LoginUtils.findByIdentifierAsync(context.UserName, userManager);
            }



            if (user == null)
            {
                context.SetError(ErrorResponse.CantLogin.error.ToString(), ErrorResponse.CantLogin.error_description); //rejects, no user found
                return;
            }

            var PasswordCheck = userManager.PasswordHasher.VerifyHashedPassword(user.PasswordHash, context.Password); //check if password was correct

            if (PasswordCheck.Equals(PasswordVerificationResult.Success) && user.PhoneNumberConfirmed)                //user provided correct creentials
            {
                loggedIn = true;
            }
            else if (PasswordCheck.Equals(PasswordVerificationResult.Success))
            {
                //Send an SMS!!
                string otp = Base.LoginUtils.GenerateOTP(user);
                await SMSService.SendMessage(user.PhoneNumber.ToString(), String.Format("Your SMS code is {0} use it to confirm your phone number withing {1} min", otp, LoginUtils.Interval / 60));

                context.SetError(ErrorResponse.PhoneNumberUnconfirmed.error.ToString(), ErrorResponse.PhoneNumberUnconfirmed.error_description);
            }
            else if (!loggedIn)// log in with SMS code
            {
                loggedIn = LoginUtils.ValidateOTP(user, context.Password);

                if (!user.PhoneNumberConfirmed && loggedIn) //if the user's phone number is not confirmed, and if logged in set it confirmed
                {
                    user.PhoneNumberConfirmed = true;
                    await userManager.UpdateAsync(user);
                }
            }


            if (loggedIn)                                                                        //user provided correct creentials
            {
                ClaimsIdentity oAuthIdentity = await user.GenerateUserIdentityAsync(userManager, //generates identity
                                                                                    OAuthDefaults.AuthenticationType);

                AuthenticationProperties properties = CreateProperties(user.Id.ToString());        //generates properties

                AuthenticationTicket ticket = new AuthenticationTicket(oAuthIdentity, properties); //puts properties and idenity into authentication ticket

                context.Validated(ticket);
            }
            else
            {
                context.SetError(ErrorResponse.CantLogin.error.ToString(), ErrorResponse.CantLogin.error_description); //rejects, password is wrong
            }


            /*ClaimsIdentity cookiesIdentity = await user.GenerateUserIdentityAsync(userManager,
             *  CookieAuthenticationDefaults.AuthenticationType);
             */
            //context.Request.Context.Authentication.SignIn(cookiesIdentity);
        }
Example #30
0
        public static async Task <ClaimsIdentity> GenerateUserIdentityAsync(this ApplicationUser user, UserManager <ApplicationUser> manager)
        {
            var userRoles = new UserRolesRepo();

            return(await user.GenerateUserIdentityAsync(manager, userRoles));
        }
        // Add helpers region

        #region Helpers

        private async Task SignInAsync(ApplicationUser user, bool isPersistent)
        {
            AuthenticationManager.SignOut(DefaultAuthenticationTypes.ExternalCookie);
            AuthenticationManager.SignIn(new AuthenticationProperties() { IsPersistent = isPersistent }, await user.GenerateUserIdentityAsync(_userManager));
            Services.Users.UpdateOnlineStatusById(user.Id, true);
        }
Example #32
0
        private async Task SignInAsync(ApplicationUser user, bool isPersistent)
        {
            AuthenticationManager.SignOut(DefaultAuthenticationTypes.ExternalCookie);

            // Extracted the part that has been changed in SignInAsync for clarity.
            await SetExternalProperties(user);

            var identity = await user.GenerateUserIdentityAsync(UserManager);

            AuthenticationManager.SignIn(new AuthenticationProperties() { IsPersistent = isPersistent }, identity);
        }
Example #33
0
        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, "JWT");



            //third party (google)

            using (AuthRepository _repo = new AuthRepository())
            {
                var identityUser = await _repo.FindUser(context.UserName, context.Password);

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

            var identity = new ClaimsIdentity(context.Options.AuthenticationType);

            identity.AddClaim(new Claim("sub", context.UserName));
            identity.AddClaim(new Claim("role", "user"));

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

            var ticket2 = new AuthenticationTicket(identity, props);
            //contains the identity of the user
            var ticket = new AuthenticationTicket(oAuthIdentity, null);

            //passing the ticket to OAuth bearer access token.
            context.Validated(ticket);
            context.Validated(ticket2);
        }
Example #34
0
 public override Task<ClaimsIdentity> CreateUserIdentityAsync(ApplicationUser user)
 {
     return user.GenerateUserIdentityAsync((ApplicationUserManager)UserManager);
 }
Example #35
0
        public override async Task GrantResourceOwnerCredentials(OAuthGrantResourceOwnerCredentialsContext context)
        {
            var userManager = context.OwinContext.GetUserManager <ApplicationUserManager>();

            ApplicationUser user = await userManager.FindByNameAsync(context.UserName);

            if (user != null)
            {
                var passwordExpired        = false;
                var passwordExpirationDays = Convert.ToInt32(ConfigurationManager.AppSettings["PasswordExpirationDays"]);
                if (passwordExpirationDays > 0)
                {
                    passwordExpired = user.LastPasswordChangedDate.AddDays(passwordExpirationDays) < DateTime.Now;
                }
                var validCredentials = await userManager.FindAsync(context.UserName, context.Password);

                if (await userManager.IsLockedOutAsync(user.Id))
                {
                    // account locked
                    // use invalid user name or password message to avoid disclosing that a valid username was input
                    context.SetError("invalid_grant", "The user name or password is incorrect.");
                }
                else if (validCredentials == null)
                {
                    // invalid credentials
                    // increment failed login count
                    if (await userManager.GetLockoutEnabledAsync(user.Id))
                    {
                        await userManager.AccessFailedAsync(user.Id);
                    }

                    context.SetError("invalid_grant", "The user name or password is incorrect.");
                }
                else if (passwordExpired)
                {
                    // password expired
                    context.SetError("invalid_grant", "Password expired");
                }
                else
                {
                    // successful login
                    ClaimsIdentity oAuthIdentity = await user.GenerateUserIdentityAsync(userManager,
                                                                                        OAuthDefaults.AuthenticationType);

                    ClaimsIdentity cookiesIdentity = await user.GenerateUserIdentityAsync(userManager,
                                                                                          CookieAuthenticationDefaults.AuthenticationType);

                    AuthenticationProperties properties = CreateProperties(user.Email);
                    AuthenticationTicket     ticket     = new AuthenticationTicket(oAuthIdentity, properties);
                    context.Validated(ticket);
                    context.Request.Context.Authentication.SignIn(cookiesIdentity);

                    // reset failed attempts count
                    await userManager.ResetAccessFailedCountAsync(user.Id);
                }
            }
            else
            {
                // invalid username
                context.SetError("invalid_grant", "The user name or password is incorrect.");
            }
        }
Example #36
0
 private async Task SignInAsync(ApplicationUser user, bool isPersistent)
 {
     AuthenticationManager.SignOut(DefaultAuthenticationTypes.ExternalCookie, DefaultAuthenticationTypes.TwoFactorCookie);
     AuthenticationManager.SignIn(new AuthenticationProperties { IsPersistent = isPersistent }, await user.GenerateUserIdentityAsync(UserManager));
 }
Example #37
0
        public async Task <ClaimsIdentity> LogIn(string login, string password, bool isRemember)
        {
            ApplicationUser currentUser = await this.userManager.FindAsync(login, password);

            return(await currentUser.GenerateUserIdentityAsync(this.userManager));
        }
Example #38
0
        public async Task <ActionResult> Student(Students model)
        {
            IdentityResult result = null;

            if (model != null && model.Termsofuse && !string.IsNullOrWhiteSpace(model.FirstName) && !string.IsNullOrWhiteSpace(model.LastName) && !string.IsNullOrWhiteSpace(model.Email) && !string.IsNullOrWhiteSpace(model.Bio))
            {
                string password = Membership.GeneratePassword(12, 1);
                string userName = getUserName(model.Email);

                var user = new ApplicationUser()
                {
                    UserName = userName, Email = model.Email
                };
                result = await UserManager.CreateAsync(user, password);

                if (result.Succeeded)
                {
                    try
                    {
                        CultureInfo ci = ResolveCulture();
                        model.Language = ci.DisplayName;
                        model.Country  = getCountry(ci);

                        model.Birthday = model.OptionalBirthDay.HasValue ? model.OptionalBirthDay.Value : DateTime.MinValue;

                        var auth = HttpContext.GetOwinContext().Authentication;
                        auth.SignOut(DefaultAuthenticationTypes.ExternalCookie);
                        auth.SignIn(new AuthenticationProperties()
                        {
                            IsPersistent = true
                        }, await user.GenerateUserIdentityAsync(UserManager));
                        var userCreated = await UserManager.FindByEmailAsync(model.Email);

                        userCreated.Roles.Add(new IdentityUserRole {
                            RoleId = 4.ToString()
                        });
                        await UserManager.UpdateAsync(userCreated);

                        model.Street          = model.BusinessName = model.City = model.Phone = model.CellProvider = model.HomeOrganizationID = model.Zip = "-";
                        model.IsProfilePublic = false;

                        await studentRepository.UpsetProspectData(userCreated.Id, model);

                        string code = await UserManager.GenerateEmailConfirmationTokenAsync(user.Id);

                        var callbackUrl = Url.Action("ConfirmEmail", "Account", new { userId = user.Id, code = code }, protocol: Request.Url.Scheme);
                        await notificationManager.SendUserRegisteredNotification(user.Email, callbackUrl, password, userName);

                        string registrationMessage = string.Format(Resources.Resources.RegistrationMessage, userName + "--" + model.Email, "StudentNewForm");
                        await notificationManager.SendSytemNotification(registrationMessage, Resources.Resources.NewUser, this.Request.IsLocal);
                    }
                    catch (Exception ex)
                    {
                        string registrationMessage = " === " + DateTime.Now.ToLongDateString() + " === " + Environment.NewLine + ex.Message + userName + model.Email + "----->" + ex.Message + "=== " + Environment.NewLine;
                        _logger.Error(registrationMessage);
                    }

                    return(RedirectToAction("SetupProperty", "Home", new { guided = true }));
                }
            }

            _logger.Error(model == null ? "Model is null" : $"{model.Termsofuse.ToString()} - {model.FirstName} - {model.LastName} - {model.Email} - UserManager Errors:" + getErrorText(result?.Errors));

            model.Error = true;
            return(View("~/Views/Landings/Student.cshtml", model));
        }
Example #39
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 });


            using (var db = new ApplicationDbContext())
            {
                using (var usermanager = new UserManagerHelper())
                {
                    ApplicationUser dbUser = null;


                    dbUser = await db.Users.SingleOrDefaultAsync(x => x.Email == context.UserName && x.Tenant == context.ClientId);

                    if (dbUser == null)
                    {
                        context.SetError("invalid_grant", "The user name or password is incorrect.");
                        return;
                    }
                    if (!await usermanager.UserManager.UserManager.CheckPasswordAsync(dbUser, context.Password))
                    {
                        context.SetError("invalid_grant", "The user name or password is incorrect.");
                        return;
                    }

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



                    var identity = await dbUser.GenerateUserIdentityAsync(context.OwinContext.GetUserManager <ApplicationUserManager>(), "JWT");

                    var props = new AuthenticationProperties(new Dictionary <string, string>
                    {
                        {
                            "client_id", context.ClientId
                        },
                        {
                            "userId", dbUser.Id
                        },
                        {
                            "userName", context.UserName
                        },
                        {
                            "ip_address", HttpContext.Current.Request.Form["ip_address"]
                        },
                        {
                            "user_agent", HttpContext.Current.Request.Form["user_agent"]
                        },
                        {
                            "env", ConfigurationManager.AppSettings["Environment"]
                        }
                    });

                    var ticket = new AuthenticationTicket(identity, props);
                    context.Validated(ticket);
                }
            }
        }