public override async Task GrantResourceOwnerCredentials(OAuthGrantResourceOwnerCredentialsContext context)
        {
            var userManager = context.OwinContext.GetUserManager<ApplicationUserManager>();
            

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

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

            //next line added from:
            //http://stackoverflow.com/questions/26046441/current-user-in-owin-authentication
            oAuthIdentity.AddClaim(new Claim(ClaimTypes.Name, context.UserName));

            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)
        {
            using (var repo = new AuthRepository())
            {
                var 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);

                identity.AddClaim(new Claim(ClaimTypes.Name, context.UserName));
                identity.AddClaim(new Claim("id", user.Id));
                
                var isAdmin = repo.HasRole(user, "Administrator");
                identity.AddClaim(new Claim("is_admin", isAdmin.ToString()));

                identity.AddClaim(isAdmin
                    ? new Claim(ClaimTypes.Role, "Administrator")
                    : new Claim(ClaimTypes.Role, "DashboardUser"));


                context.Validated(identity);
            }
        }
        public override async Task GrantResourceOwnerCredentials(OAuthGrantResourceOwnerCredentialsContext context)
        {
            try
            {
                context.OwinContext.Response.Headers.Add("Access-Control-Allow-Origin", new[] { "*" });

                //認証処理
                //LDAPに対して uid + password で認証を行う
                var userManager = new LdapUserManager(new LdapUserStore());
                var ldapUser = await userManager.FindAsync(context.UserName, context.Password);
                if (ldapUser == null)
                {
                    //認証失敗
                    context.SetError("invalid_grant", "The username or password is incorrect.");
                    return;
                }

                //ユーザーを表す ClaimsIdentity を作成する
                var identity = await userManager.CreateIdentityAsync(ldapUser, context.Options.AuthenticationType);
                identity.AddClaim(new Claim("dn", ldapUser.DistinguishedName));
                identity.AddClaim(new Claim("uid", ldapUser.Id));
                context.Validated(identity);

                //認証登録
                context.Request.Context.Authentication.SignIn(identity);
            }
            catch (Exception e)
            {
                context.SetError("Application Error", e.Message);
            }
        }
        public override async Task GrantResourceOwnerCredentials(OAuthGrantResourceOwnerCredentialsContext context)
        {
            context.OwinContext.Response.Headers.Add("Access-Control-Allow-Origin", new[] { "*" });
            try
            {
                //using (IUserRepository _repository = new UserRepository(DataContextHelper.CurrentDataContext))
                //{
                //    var user = _repository.Get(context.UserName);
                //    if (user == null)
                //        throw new Exception("Usuário ou senha inválidos");

                //    user.Authenticate(context.UserName, context.Password);

                //    GenericIdentity genericIdentity = new GenericIdentity(user.Email);
                //    var identity = new ClaimsIdentity(genericIdentity, null, context.Options.AuthenticationType, null, null);
                //    identity.AddClaim(new Claim("sub", context.UserName));
                //    identity.AddClaim(new Claim("role", "user"));

                //    context.Validated(identity);
                //}
            }
            catch (Exception ex)
            {
                //context.SetError("invalid_grant", ex.Message);
                //LogErrorHelper.Register(ex);
                return;
            } 
    }
        public override async Task GrantResourceOwnerCredentials(OAuthGrantResourceOwnerCredentialsContext context)
        {
            // Try get the useraccount by provided username
            var userAccount = _uow.UserAccountRepository.Get(context.UserName);

            // If the useraccount was not found, reject the token request
            if (userAccount == null)
            {
                context.Rejected();
                return;
            }

            // If password is invalid, reject the token request
            if (!PasswordHelper.Verify(userAccount.Password, userAccount.Salt, context.Password))
            {
                context.Rejected();
                return;
            }

            // Create identity which will be included in the token
            var identity = new ClaimsIdentity(context.Options.AuthenticationType);

            // All claims added here will be written to the token. Thus claims should
            // be added with moderation
            identity.AddClaim(new Claim(ClaimTypes.Name, context.UserName));
            identity.AddClaim(new Claim(ClaimTypes.Role, "administrator"));
            
            // Validate the reqeust and return a token 
            context.Validated(identity);
        }
        // Called when a request to the Token endpoint arrives with a "grant_type" of "password".
        // This occurs when the user has provided name and password credentials directly
        // into the client application's user interface, and the client application is using
        // those to acquire an "access_token" and optional "refresh_token". 
        public override async Task GrantResourceOwnerCredentials(OAuthGrantResourceOwnerCredentialsContext context)
        {
            context.OwinContext.Response.Headers.Add("Access-Control-Allow-Origin", new[] { "*" });
            var userManager = context.OwinContext.GetUserManager<GbmonoUserManager>();

            // lookup user by user name and password
            GbmonoUser user = await userManager.FindAsync(context.UserName, context.Password);

            if (user == null)
            {
                context.SetError("invalid_grant", "用户名或密码不正确。");
                return;
            }

            // create user identity for Bearer token
            ClaimsIdentity oAuthIdentity = await user.GenerateUserIdentityAsync(userManager, OAuthDefaults.AuthenticationType);

            // create user identity for cookie
            ClaimsIdentity cookiesIdentity = await user.GenerateUserIdentityAsync(userManager, CookieAuthenticationDefaults.AuthenticationType);

            // create properties, user name or other extra information
            AuthenticationProperties properties = CreateProperties(user);

            // initialize a new instance of the Microsoft.Owin.Security.AuthenticationTicket
            AuthenticationTicket ticket = new AuthenticationTicket(oAuthIdentity, properties);

            // call the context.Validated(ticket) to tell the OAuth server to protect the ticket as an access token and send it out in JSON payload.
            // to issue an access token the context.Validated must be called with a new ticket containing the claims about the resource owner
            // which should be associated with the access token.
            context.Validated(ticket);

            // Signs the cookie identity so it can send the authentication cookie.
            context.Request.Context.Authentication.SignIn(cookiesIdentity);
        }
        //Taking UserName and Password as inputs and validated them against our ASP.NET Identity System
        //if credential is valid, then generate an identity for this logged in user.
        //
        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<TRAPUserManager>();

            User 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 authIdentity = await user.GenerateUserIdentityAsync(userManager, "JWT");

            //AuthenticationTicket contains user identity information and authentication state
            var authTicket = new AuthenticationTicket(authIdentity, null);

            context.Validated(authTicket);

        }
        public override async Task GrantResourceOwnerCredentials(OAuthGrantResourceOwnerCredentialsContext context)
        {
            // Allow CORS on the token middleware provider
            context.OwinContext.Response.Headers.Add("Access-Control-Allow-Origin", new[] { "*" });

            //TODO
            // Usually this would be done via dependency injection
            // But I haven't got it to work with the OWIN startup class yet
            AppDBContext _ctx = new AppDBContext();
            UserRepository _repo = new UserRepository(_ctx);

                IdentityUser 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);
            identity.AddClaim(new Claim("sub", context.UserName));
            identity.AddClaim(new Claim("role", "user"));

            context.Validated(identity);

        }
        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 user = await _identityRepository.FindUserAsync(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);
                identity.AddClaim(new Claim(ClaimTypes.Name, context.UserName));
                identity.AddClaim(new Claim(ClaimTypes.Role, "user"));
                identity.AddClaim(new Claim("sub", context.UserName));

                var props = new AuthenticationProperties(new Dictionary<string, string>
                {
                    { 
                        "as:client_id", context.ClientId ?? string.Empty
                    },
                    { 
                        "userName", context.UserName
                    }
                });
                var ticket = new AuthenticationTicket(identity, props);
                context.Validated(ticket);    
            
        }
        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;
            }

            if (context.Request.Headers["devicetoken"] != null)
            {
                if (user.DeviceToken != context.Request.Headers["devicetoken"])
                {
                    user.DeviceToken = context.Request.Headers["devicetoken"];
                    userManager.Update(user);
                }
            }

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

            context.OwinContext.Response.Headers.Add("Access-Control-Allow-Origin",
                new[] { ConfigurationManager.AppSettings["internal:origins"] });

            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)
        {
            using (UserManager<IdentityUser> userManager = _userManagerFactory())
            {
                try
                {
                    IdentityUser 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 userManager.CreateIdentityAsync(user,
                        context.Options.AuthenticationType);
                    ClaimsIdentity cookiesIdentity = await userManager.CreateIdentityAsync(user,
                        CookieAuthenticationDefaults.AuthenticationType);
                    AuthenticationProperties properties = CreateProperties(user.UserName, user.Roles.First().Role.Name);
                    AuthenticationTicket ticket = new AuthenticationTicket(oAuthIdentity, properties);
                    context.Validated(ticket);
                    context.Request.Context.Authentication.SignIn(cookiesIdentity);
                }
                catch (Exception)
                {
                    
                    throw;
                }
                
            }
        }
        public override async Task GrantResourceOwnerCredentials(OAuthGrantResourceOwnerCredentialsContext context)
        {
            var user = userRepository.Get(w => w.UserName == context.UserName && w.Password == context.Password);
            
            //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 = new ClaimsIdentity(context.Options.AuthenticationType);
            ClaimsIdentity cookiesIdentity = new ClaimsIdentity(context.Options.AuthenticationType);
            oAuthIdentity.AddClaim(new Claim(ClaimTypes.Name, user.UserName));
            if (user.Roles.Count() > 0)
            {
                oAuthIdentity.AddClaim(new Claim(ClaimTypes.Role, user.Roles.FirstOrDefault().Name));
            }

            //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  allowedOrigin = "*";
            ApplicationUser appUser = null;

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

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

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

            var identity = new ClaimsIdentity(context.Options.AuthenticationType);
            identity.AddClaim(new Claim(ClaimTypes.Name, context.UserName));
            identity.AddClaim(new Claim(ClaimTypes.Role, "User"));
            identity.AddClaim(new Claim("PSK", appUser.PSK));

            var props = new AuthenticationProperties(new Dictionary<string, string>
                {
                    { 
                        "userName", context.UserName
                    }
                });

            var ticket = new AuthenticationTicket(identity, props);
            context.Validated(ticket);
        }
 public override async Task GrantResourceOwnerCredentials(OAuthGrantResourceOwnerCredentialsContext context)
 {
     context.OwinContext.Response.Headers.Add("Access-Control-Allow-Origin", new[] {"*"});
     try
     {
         using (var userManager = new UserManager<User>(new UserStore<User>(new ElearningDbContext())))
         {
             var user = await userManager.FindAsync(context.UserName, context.Password);
             if (user == null)
             {
                 context.SetError("invaild_grant", "The user name or password is incorrect");
                 return;
             }
         }
     }
     catch (Exception ex)
     {
         var a = ex;
         throw;
     }
     var identity = new ClaimsIdentity("JWT");
     identity.AddClaim(new Claim(ClaimTypes.Name, context.UserName));
     identity.AddClaim(new Claim("sub", context.UserName));
     identity.AddClaim(new Claim(ClaimTypes.Role, "user"));
     var properties = new AuthenticationProperties(new Dictionary<string, string>
     {
         {
             "audience", context.ClientId ?? string.Empty
         }
     });
     var ticket = new AuthenticationTicket(identity, properties);
     context.Validated(ticket);
 }
        public override async Task GrantResourceOwnerCredentials(OAuthGrantResourceOwnerCredentialsContext context)
        {
            context.OwinContext.Response.Headers.Add("Access-Control-Allow-Origin", new[] { "*" });
            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);

            //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)));
            string role = "";
            if (oAuthIdentity.Claims.Where(c => c.Type == ClaimTypes.Role).Any())
            {
                role = oAuthIdentity.Claims.Where(c => c.Type == ClaimTypes.Role).First().Value;
            }
            AuthenticationProperties properties = CreateProperties(user.UserName, role);
            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", "El nombre de usuario o la contraseña no son correctos.");
                return;
            }

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

            new LogsController().AddLogLogin(LogsController.LOGIN, "ApplicationUser", user);


            String role = "";
            IList<String> roles = userManager.GetRoles(user.Id);
            foreach (String obj in roles)
            {
                role += obj;
            }
            
            AuthenticationProperties properties = CreateProperties(user.UserName, role);
            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>();

            UserAccount 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);

            string fullName = user.FirstName;

            if (!string.IsNullOrEmpty(user.LastName))
            {
                fullName = fullName + " " + user.LastName;
            }
            AuthenticationProperties properties = CreateProperties(user.UserName, fullName);
            AuthenticationTicket ticket = new AuthenticationTicket(oAuthIdentity, properties);
            context.Validated(ticket);

            oAuthIdentity.AddClaims(new List<Claim> {
             new Claim(ClaimTypes.NameIdentifier, fullName),
              new Claim (ClaimTypes.Name, fullName)
            });

            context.Request.Context.Authentication.SignIn(properties, new ClaimsIdentity[] { cookiesIdentity, oAuthIdentity });
        }
        public override Task GrantResourceOwnerCredentials(OAuthGrantResourceOwnerCredentialsContext context)
        {
            context.OwinContext.Response.Headers.Add("Access-Control-Allow-Origin", new[] { "*" });

            // Dummy check here, you need to do your DB checks against membership system http://bit.ly/SPAAuthCode
            if (context.UserName != context.Password)
            {
                context.SetError("invalid_grant", "The user name or password is incorrect");
                //return;
                return Task.FromResult<object>(null);
            }

            var identity = new ClaimsIdentity("JWT");

            identity.AddClaim(new Claim(ClaimTypes.Name, context.UserName));
            identity.AddClaim(new Claim("sub", context.UserName));
            identity.AddClaim(new Claim(ClaimTypes.Role, "Manager"));
            identity.AddClaim(new Claim(ClaimTypes.Role, "Supervisor"));

            var props =
                new AuthenticationProperties(
                    new Dictionary<string, string>
                        {
                            {
                                "audience",
                                context.ClientId ?? string.Empty
                            }
                        });

            var ticket = new AuthenticationTicket(identity, props);
            context.Validated(ticket);
            return Task.FromResult<object>(null);
        }
        public override async Task GrantResourceOwnerCredentials(OAuthGrantResourceOwnerCredentialsContext context)
        {
            context.OwinContext.Response.Headers.Add("Access-Control-Allow-Origin", new[] {"*"});
            var identity = new ClaimsIdentity(DefaultAuthenticationTypes.ApplicationCookie);
            var userManager = Startup.UserManagerFactory();
            var user = await userManager.FindAsync(context.UserName, context.Password);
            if (user == null)
            {
                context.SetError("invalid_grant", "The user name or password is incorrect.");
                return;
            }
            identity.AddClaim(new Claim("id", user.StaffId.ToString()));
            identity.AddClaim(new Claim(ClaimTypes.Name, user.UserName));
            var listOfRoles = await userManager.GetRolesAsync(user.Id);
            if (listOfRoles.Contains("admin"))
            {
                identity.AddClaim(new Claim("role", "admin"));
            }
            else
            {
                identity.AddClaim(new Claim("role", "user"));
            }
            context.Validated(identity);


            var ctx = HttpContext.Current.GetOwinContext();
            var authManager = ctx.Authentication;
            authManager.SignIn(identity);
        }
        public override async Task GrantResourceOwnerCredentials(OAuthGrantResourceOwnerCredentialsContext context)
        {
            context.OwinContext.Response.Headers.Add("Access-Control-Allow-Origin", new[] { "http://hawkwareapps.com" });
            context.OwinContext.Response.Headers.Add("Access-Control-Allow-Credentials", new[] { "true" });
            //context.OwinContext.Response.Headers.Add("Access-Control-Allow-Methods", new[] { "*" });
            //context.OwinContext.Response.Headers.Add("Access-Control-Allow-Headers", new[] { "Content-Type, X-Requested-With" });

            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)
        {

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

            List<string> roles = new List<string>();
            IdentityUser user = new IdentityUser();

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

                if (user == null)
                {
                    context.SetError("invalid_grant", "Потребителското име или паролата не са верни.");
                    return;
                }
                else
                {
                    roles = await _repo.GetRolesForUser(user.Id);
                }
            }

            var identity = new ClaimsIdentity(context.Options.AuthenticationType);
            identity.AddClaim(new Claim("sub", context.UserName));
            foreach (var item in roles)
            {
                identity.AddClaim(new Claim(ClaimTypes.Role, item));
            }

            context.Validated(identity);
            context.Response.Headers.Add("UserRoles", roles.ToArray());
        }
        public override async Task GrantResourceOwnerCredentials(OAuthGrantResourceOwnerCredentialsContext context)
        {
            context.OwinContext.Response.Headers.Add("Access-Control-Allow-Origin", new[] { "*" });

            using (AuthRepository _repo = new AuthRepository())
            {
                IdentityUser 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);

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

                var roles = await _repo.FindUserRoles(user.Id);

                foreach (var r in roles)
                {
                    identity.AddClaim(new Claim(ClaimTypes.Role, r));
                }
                //identity.AddClaim(new Claim("sub", context.UserName));
                
                context.Validated(identity);
            }
        }
        /// <summary>
        /// oAuth Resource Password Login Flow
		/// 1. Checks the password with the Identity API
		/// 2. Create a user identity for the bearer token
		/// 3. Create a user identity for the cookie
		/// 4. Calls the context.Validated(ticket) to tell the oAuth2 server to protect the ticket as an access token and send it out in JSON payload
		/// 5. Signs the cookie identity so it can send the authentication cookie
        /// </summary>
        /// <param name="context">The authorization context</param>
		/// <returns>Task</returns>		
        public override async Task GrantResourceOwnerCredentials(OAuthGrantResourceOwnerCredentialsContext context)
        {
            using (ApplicationUserManager userManager = _userManagerFactory())
            {
                UserProfile user = await userManager.FindAsync(context.UserName, context.Password);
                
                if (user == null)
                {
                    context.SetError("invalid_grant", "Invalid user or password");
                    return;
                }

                ClaimsIdentity oAuthIdentity = await userManager.CreateIdentityAsync(user,
                    context.Options.AuthenticationType);
                ClaimsIdentity cookiesIdentity = await userManager.CreateIdentityAsync(user,
                    CookieAuthenticationDefaults.AuthenticationType);

                var justCreatedIdentity = await userManager.FindByNameAsync(user.UserName);
                var roles = await userManager.GetRolesAsync(justCreatedIdentity.Id);

                AuthenticationProperties properties = CreateProperties(user.UserName, roles.ToArray(), user.EmailConfirmed);
                AuthenticationTicket ticket = new AuthenticationTicket(oAuthIdentity, properties);
                                
                context.Validated(ticket);
                context.Request.Context.Authentication.SignIn(cookiesIdentity);
            }
        }
        public override async Task GrantResourceOwnerCredentials(OAuthGrantResourceOwnerCredentialsContext context)
        {
            var allowedOrigin = "*";
            context.OwinContext.Response.Headers.Add("Access-Control-Allow-Origin", new[] { allowedOrigin });

            if (context.UserName != "*****@*****.**" || context.Password != "%baG7cadence")
            {
                context.SetError("invalid_grant", "The user name or password is incorrect.");
                return;
            }

            var claims = new List<Claim>();
            //claims.Add(new Claim(ClaimTypes., context.UserName));

            var data = await context.Request.ReadFormAsync();

            var identity = new ClaimsIdentity("JWT");

            //identity.AddClaims(claims);

            int daysSignedIn = 14;
            context.Options.AccessTokenExpireTimeSpan = TimeSpan.FromDays(daysSignedIn);

            var ticket = new AuthenticationTicket(identity, null);
            context.Validated(ticket);
        }
Example #26
0
        //Taking UserName and Password as inputs and validated them against our ASP.NET Identity System
        //if credential is valid, then generate an identity for this logged in user.
        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<TRAPUserManager>();

            User 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 authIdentity = await user.GenerateUserIdentityAsync(userManager, "JWT");
            List<Claim> roles = authIdentity.Claims.Where(c => c.Type == ClaimTypes.Role).ToList();
            AuthenticationProperties properties = CreateProperties(user.UserName, Newtonsoft.Json.JsonConvert.SerializeObject(roles.Select(x => x.Value)));

            //AuthenticationTicket contains user identity information and authentication state
            var authTicket = new AuthenticationTicket(authIdentity, properties);

            context.Validated(authTicket);

        }
        public override async Task GrantResourceOwnerCredentials(OAuthGrantResourceOwnerCredentialsContext context)
        {

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

            using (var projectContext = new ProjectContext())
            {
                using (var unitOfWork = new UnitOfWork(projectContext))
                {
                    IdentityUser user = await unitOfWork.Users.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);
            identity.AddClaim(new Claim("sub", context.UserName));
            identity.AddClaim(new Claim("role", "user"));

            context.Validated(identity);

        }
        public override async Task GrantResourceOwnerCredentials(OAuthGrantResourceOwnerCredentialsContext context)
        {

            //context.OwinContext.Response.Headers.Add("Access-Control-Allow-Origin", new[] { "*" });
            IdentityUser user;
            using (var _repo = new AuthRepository())
            {
                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);
            identity.AddClaim(new Claim("sub", context.UserName));
            identity.AddClaim(new Claim("userId", user.Id));

            if (user.Id == "c417fc8e-5bae-410f-b2ee-463afe2fdeaa")
                identity.AddClaim(new Claim(ClaimTypes.Role, "Admin"));

            var props = new AuthenticationProperties(new Dictionary<string, string>
            {
                {
                    "userId", user.Id
                }
            });

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

        }
 /// <summary>
 ///  验证用户名与密码 [Resource Owner Password Credentials Grant[username与password]|grant_type=password&username=irving&password=654321]
 /// </summary>
 /// <param name="context"></param>
 /// <returns></returns>
 public override async Task GrantResourceOwnerCredentials(OAuthGrantResourceOwnerCredentialsContext context)
 {
     context.OwinContext.Response.Headers.Add("Access-Control-Allow-Origin", new[] { "*" });
     //validate user credentials (验证用户名与密码)  should be stored securely (salted, hashed, iterated) 
     var userValid = await _accountService.ValidateUserNameAuthorizationPwdAsync(context.UserName, context.Password);
     if (!userValid)
     {
         //context.Rejected();
         context.SetError(AbpConstants.AccessDenied, AbpConstants.AccessDeniedErrorDescription);
         return;
     }
     var claimsIdentity = new ClaimsIdentity(context.Options.AuthenticationType);
     claimsIdentity.AddClaim(new Claim(ClaimTypes.Name, context.UserName));
     var ticket = new AuthenticationTicket(claimsIdentity, new AuthenticationProperties());
     context.Validated(ticket);
     /*
     //create identity
     var claimsIdentity = new ClaimsIdentity(context.Options.AuthenticationType);
     claimsIdentity.AddClaim(new Claim(ClaimTypes.Name, context.UserName));
     claimsIdentity.AddClaim(new Claim("sub", context.UserName));
     claimsIdentity.AddClaim(new Claim("role", "user"));
     // create metadata to pass on to refresh token provider
     var props = new AuthenticationProperties(new Dictionary<string, string>
                     {
                         {"as:client_id", context.ClientId }
                     });
     var ticket = new AuthenticationTicket(claimsIdentity, props);
     context.Validated(ticket);
     */
 }
Example #30
0
        public override async Task GrantResourceOwnerCredentials(OAuthGrantResourceOwnerCredentialsContext oauthCtx)
        {
            oauthCtx.OwinContext.Response.Headers.Add("Access-Control-Allow-Origin", new[] { "*" });

            if (oauthCtx.UserName == null || oauthCtx.Password == null)
            {
                oauthCtx.SetError("invalid_grant", "No Credentials");
                return;
            }

            Person person;

            using (var dbCtx = new UserMetadataCtx())//UserCtx())
            {
                person = await dbCtx.People.Include(user => user.Security)
                         .Include(user => user.Student)
                         .Include(user => user.Faculty)
                         .SingleOrDefaultAsync(user => user.Email == oauthCtx.UserName);
            }

            if (person == null)
            {
                oauthCtx.SetError("invalid_grant", "Invalid username or password");
                return;
            }

            var hasValidPassword = PasswordHash.ValidatePassword(oauthCtx.Password, person.Security.PasswordHash);

            if (!hasValidPassword)
            {
                oauthCtx.SetError("invalid_grant", "Invalid username or password");
                return;
            }

            var identity = UserAuthToken.GetClaimId;

            identity.AddClaim(new Claim(ClaimTypes.PrimarySid, person.PersonId.ToString()));

            switch (person.MpInstituteRole)
            {
            case MpInstituteRoleId.Student:
                identity.AddClaim(new Claim(ClaimTypes.Role, MpInstituteRole.Student));
                break;

            case MpInstituteRoleId.Faculty:
                identity.AddClaim(new Claim(ClaimTypes.Role, MpInstituteRole.Faculty));
                if (person.Faculty.IsCourseAdmin)
                {
                    identity.AddClaim(new Claim(ClaimTypes.Role, MpInstituteRole.ISA));
                }
                else
                {
                    identity.AddClaim(new Claim(ClaimTypes.Role, MpInstituteRole.notISA));
                }
                break;

            default:
                identity.AddClaim(new Claim(ClaimTypes.Role, MpInstituteRoleId.Student));
                break;
            }


            _idToken = new IdToken
            {
                TokenExpire        = DateTime.Now.Add(TimeSpan.FromHours(24)),
                TokenExpireWarning = DateTime.Now.Add(TimeSpan.FromHours(23)),
                LastName           = person.LastName,
                FirstName          = person.FirstName,
                Email                = person.Email,
                MpAffiliation        = person.MpAffiliation,
                MpComponent          = person.MpComponent,
                MpPaygrade           = person.MpPaygrade,
                MpGender             = person.MpGender,
                MpInstituteRole      = person.MpInstituteRole,
                RegistrationComplete = person.RegistrationComplete,
                PersonId             = person.PersonId
            };

            var ticket = new AuthenticationTicket(identity, null);

            oauthCtx.Validated(ticket);

            await Task.FromResult(oauthCtx.Validated());
        }
 public override async Task GrantResourceOwnerCredentials(OAuthGrantResourceOwnerCredentialsContext context)
 {
 }
Example #32
0
        /// <summary>
        /// Grant resource owner credentials overload method.
        /// </summary>
        /// <param name="context">Context parameter</param>
        /// <returns>Returns when task is completed</returns>
        public override async Task GrantResourceOwnerCredentials(OAuthGrantResourceOwnerCredentialsContext context)
        {
            // Initialization.
            string usernameVal = (String.IsNullOrEmpty(context.UserName)) ? "" : context.UserName;
            string passwordVal = (String.IsNullOrEmpty(context.Password)) ? "" : context.Password;
            //var user = this.databaseManager.LoginByUsernamePassword(usernameVal, passwordVal).ToList();

            IFormCollection parameters = await context.Request.ReadFormAsync();

            string deviceDetails = parameters.Get("DeviceDetails");

            deviceDetails = (String.IsNullOrEmpty(deviceDetails)) ? "" : deviceDetails;
            string deviceUDID = parameters.Get("DeviceUDID");

            deviceUDID = (String.IsNullOrEmpty(deviceUDID)) ? "" : deviceUDID;
            string deviceTYPE = parameters.Get("DeviceTYPE");

            deviceTYPE = (String.IsNullOrEmpty(deviceTYPE)) ? "" : deviceTYPE;
            string mobileDatetime = parameters.Get("MobileDateTime");

            mobileDatetime = (String.IsNullOrEmpty(mobileDatetime)) ? "" : mobileDatetime;
            string fcmToken = parameters.Get("FcmToken");

            fcmToken = (String.IsNullOrEmpty(fcmToken)) ? "" : fcmToken;

            string serviceTYPE = parameters.Get("ServiceTYPE");

            serviceTYPE = (String.IsNullOrEmpty(serviceTYPE)) ? "" : serviceTYPE;

            Users userobject = new Users();

            userobject.userName       = usernameVal;
            userobject.passWord       = passwordVal;
            userobject.deviceDetails  = deviceDetails;
            userobject.deviceUDID     = deviceUDID;
            userobject.deviceTYPE     = deviceTYPE;
            userobject.mobileDatetime = mobileDatetime;
            userobject.fcmToken       = fcmToken;
            userobject.serviceTYPE    = serviceTYPE;

            string userID  = "";
            string isLead  = "";
            string teamIDs = "";

            JsonStandardResponse sendOtpResponse = null;

            if (userobject.serviceTYPE.ToLower() == "login")
            {
                /*if (userobject.userName != "admin" || userobject.passWord != "admin")
                 * {
                 *  context.SetError("invalid_grant", "The user name or password is incorrect.");
                 *  return;
                 * }*/
                if (userobject.passWord.Length < 8)
                {
                    context.SetError("invalid_grant", "Password length must be must be equal or greater than 8 characters.");
                    return;
                }

                DateTime dateTime;
                try
                {
                    dateTime = DateTime.ParseExact(userobject.mobileDatetime, "MM-dd-yyyy HH:mm:ss", CultureInfo.InvariantCulture);
                }
                catch (FormatException)
                {
                    context.SetError("invalid_grant", "invalid datetime format required is MM-dd-yyyy HH:mm:ss");
                    return;
                }

                //Login from credentials
                //Verification.
                //string Status = new UserProfile().VerifyUserCredentials(userobject, Constants.GetConnectionString());
                string Status = new UserProfile().VerifyUserCredentialsFromAD(userobject, Constants.GetConnectionString());
                if (Status != "Success")
                {
                    context.SetError("invalid_grant", Status);
                    return;
                }

                new UserProfile().InsertUserFcmToken(userobject, Constants.GetConnectionString());

                userobject.passWord = "";
            }
            else if (userobject.serviceTYPE.ToLower() == "adminlogin")
            {
                /*if (userobject.userName != "admin" || userobject.passWord != "admin")
                 * {
                 *  context.SetError("invalid_grant", "The user name or password is incorrect.");
                 *  return;
                 * }*/
                if (userobject.passWord.Length < 8)
                {
                    context.SetError("invalid_grant", "Password length must be must be equal or greater than 8 characters.");
                    return;
                }

                DateTime dateTime;
                try
                {
                    dateTime = DateTime.ParseExact(userobject.mobileDatetime, "MM-dd-yyyy HH:mm:ss", CultureInfo.InvariantCulture);
                }
                catch (FormatException)
                {
                    context.SetError("invalid_grant", "invalid datetime format required is MM-dd-yyyy HH:mm:ss");
                    return;
                }

                //Login from credentials
                //Verification.
                string Status = new UserProfile().VerifyUserCredentials(userobject, Constants.GetConnectionString());
                //string Status = new UserProfile().VerifyUserCredentialsFromAD(userobject, Constants.GetConnectionString());
                if (Status != "Success")
                {
                    context.SetError("invalid_grant", Status);
                    return;
                }

                new UserProfile().InsertUserFcmToken(userobject, Constants.GetConnectionString());

                userobject.passWord = "";
            }
            else if (userobject.serviceTYPE.ToLower() == "refreshtoken")
            {
                //Checks DeviceUDID whether it is logged in or not
                if (userobject.deviceUDID == "" || userobject.userName == "")
                {
                    context.SetError("invalid_grant", "device udid or user name cannot be empty!");
                    return;
                }

                //Login Status Verification.
                Users obj = new UserProfile().checkUserLoginStatus(userobject, Constants.GetConnectionString());
                if (obj == null)
                {
                    context.SetError("invalid_grant", "no session found against device udid and user name!");
                    return;
                }
            }
            else
            {
                context.SetError("invalid_grant", "Invalid Request!");
                return;
            }

            Users userobj = new UserProfile().checkUserLoginStatus(userobject, Constants.GetConnectionString());

            if (userobj != null)
            {
                userobject.ID = userobj.ID;
                Users obj = new UserProfile().getUserByUserNameAndUserID(userobject, Constants.GetConnectionString());
                userID = obj.ID;
                isLead = obj.isLead;
                //teamDetailsJson = new JavaScriptSerializer().Serialize(obj.teams);
                teamIDs = string.Join(",", obj.teams.Select(x => x.ID).ToArray());
            }

            var claims = new List <Claim>();
            //claims.Add(new Claim("serviceTYPE", userobject.serviceTYPE.ToLower()));
            //claims.Add(new Claim("userName", usernameVal));
            IDictionary <string, string> data = new Dictionary <string, string>
            {
                { "serviceTYPE", userobject.serviceTYPE.ToLower() },
                { "userName", usernameVal },
                { "userID", userID },
                { "isLead", isLead },
                { "teamIDs", teamIDs }
                //{ "UserDetails", JsonConvert.SerializeObject(new UserProfile().checkUserLoginStatus(userobject, Constants.GetConnectionString()))}
            };

            // Setting Claim Identities for OAUTH 2 protocol.
            ClaimsIdentity       oAuthClaimIdentity   = new ClaimsIdentity(claims, OAuthDefaults.AuthenticationType);
            ClaimsIdentity       cookiesClaimIdentity = new ClaimsIdentity(claims, CookieAuthenticationDefaults.AuthenticationType);
            AuthenticationTicket ticket = new AuthenticationTicket(oAuthClaimIdentity, new AuthenticationProperties(data));

            // Grant access to authorize user.
            context.Validated(ticket);
            context.Request.Context.Authentication.SignIn(cookiesClaimIdentity);
        }
        public override async Task GrantResourceOwnerCredentials(OAuthGrantResourceOwnerCredentialsContext context)
        {
            using (var unitOfWork = new UnitOfWorkFactory().Create())
            {
                string requestIPAddress = GetIpAddress();

                var auditLog = new AuditActivityLog()
                {
                    SenderUserID     = context.UserName,
                    SenderRequestURL = HttpContext.Current.Request.Url.OriginalString,
                    SenderIP         = requestIPAddress,
                    AuditDateTime    = DateTime.Now
                };
                var auditId = unitOfWork.AuditRepository.CreateAuditActivityLog(auditLog);
                unitOfWork.Commit();

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

                    var clientUser = unitOfWork.UserRepository.GetUserByName(x => x, context.UserName,
                                                                             new List <Expression <Func <ClientUser, object> > > {
                        x => x.Client,
                        x => x.UserIPAddresses
                    });
                    if (clientUser == null || !(await unitOfWork.UserRepository.IsPasswordValidAsync(clientUser, context.Password)))
                    {
                        throw new AuthenticationException("The user name or password is incorrect.");
                    }

                    auditLog.LoginUser    = clientUser;
                    auditLog.InsightEmail = clientUser.Email;

                    if (!clientUser.Active)
                    {
                        throw new AuthenticationException("The user account is disabled.");
                    }
                    if (clientUser.Client == null)
                    {
                        throw new AuthenticationException("The user account doesn't have a client associated with it.");
                    }

                    DateTime nowDateTime = DateTime.UtcNow;

                    //Check whitelisting of IP addresses
                    if (clientUser.Client.WhitelistIPs)
                    {
                        List <ClientIPAddresses> userIPWhiteList = clientUser.UserIPAddresses == null ? null : clientUser.UserIPAddresses.Where(x => (x.IPAddress4 == requestIPAddress)).ToList();
                        if (userIPWhiteList == null || userIPWhiteList.Count() == 0)
                        {
                            throw new AuthenticationException("Connection denied.");
                        }
                    }

                    //Check number of open tokens limit
                    int openTokensLimit = clientUser.Client.OpenTokensLimit;
                    if (openTokensLimit == 0 && !Int32.TryParse(ConfigurationManager.AppSettings["opentokenslimit"], out openTokensLimit))
                    {
                        openTokensLimit = 0;
                    }

                    if (openTokensLimit > 0)
                    {
                        List <ClientConnections> openConnections = unitOfWork.AuditRepository.GetConnectionsByClient(x => x, clientUser.Client.id)
                                                                   .Where(x => nowDateTime >= x.TokenStartDateTimeUTC && nowDateTime <= x.TokenEndDateTimeUTC).ToList();
                        if (openConnections != null && openConnections.Count() > openTokensLimit)
                        {
                            throw new AuthenticationException("Total number of open connection per client exceeds the limit.");
                        }
                    }

                    //Set timeouts
                    int tokenTimespanSec = clientUser.Client.TokenTimeOut;
                    if (tokenTimespanSec == 0 && !Int32.TryParse(ConfigurationManager.AppSettings["timeoutseconds"], out tokenTimespanSec))
                    {
                        tokenTimespanSec = 900;
                    }

                    DateTime tokenExpiration = nowDateTime.AddSeconds(tokenTimespanSec);

                    auditLog.TokenStartDateTimeUTC = nowDateTime;
                    auditLog.TokenEndDateTimeUTC   = tokenExpiration;
                    unitOfWork.Commit();

                    //record new connection
                    var newConnection = new ClientConnections()
                    {
                        LoginUser = clientUser,
                        ConnectionClientAccount = clientUser.Client,
                        ConnectionAuditLog      = auditLog,
                        TokenStartDateTimeUTC   = nowDateTime,
                        TokenEndDateTimeUTC     = tokenExpiration
                    };
                    unitOfWork.AuditRepository.CreateClientConnectionLog(newConnection);

                    //Generate claims for the token
                    var identity = new ClaimsIdentity("JWT");
                    identity.AddClaim(new Claim(ClaimTypes.Name, context.UserName));
                    identity.AddClaim(new Claim(ClaimTypes.Email, clientUser.Email));
                    identity.AddClaim(new Claim(ClaimTypes.Expiration, tokenExpiration.ToString()));
                    identity.AddClaim(new Claim("LogId", auditId.ToString()));
                    var tokenEnd = DateTime.UtcNow.AddSeconds(tokenTimespanSec);

                    var ticket = new AuthenticationTicket(identity, new AuthenticationProperties());
                    context.Validated(ticket);
                }
                catch (Exception ex)
                {
                    if (ex is AuthenticationException)
                    {
                        context.SetError("invalid_grant", ex.Message);
                    }
                    else
                    {
                        context.SetError("invalid_grant", String.Format("Internal Error (Please contact Exiger support with reference ID: {0})", auditLog.Id));
                    }
                    auditLog.ErrorMessage = ex.Message;
                }
                finally
                {
                    unitOfWork.Commit();
                }
            }
            return;
        }
Example #34
0
        private System.Threading.Tasks.Task GrantResourceOwnerCredentials(OAuthGrantResourceOwnerCredentialsContext context)
        {
            if (!string.IsNullOrEmpty(context.UserName) && !string.IsNullOrEmpty(context.Password))
            {
                var rockContext      = new RockContext();
                var userLoginService = new UserLoginService(rockContext);
                //Older Avalanche Clients use __PHONENUMBER__+1 prefix vs the newer SMS_ prefix
                //This makes sure we are using the new ROCK external sms authentication
                var userName = context.UserName.Replace("__PHONENUMBER__+1", "SMS_");

                //SMS login does not use the phone number as the username.
                //Instead we need to change it to use the person's id.
                if (userName.StartsWith("SMS_"))
                {
                    string error;
                    var    smsAuthentication = new SMSAuthentication();
                    var    person            = smsAuthentication.GetNumberOwner(userName.Split('_').Last(), rockContext, out error);
                    if (person != null)
                    {
                        userName = string.Format("SMS_{0}", person.Id);
                    }
                    //If we cannot find a person, do nothing and just pass through the existing username
                }
                var userLogin = userLoginService.GetByUserName(userName);
                if (userLogin != null && userLogin.EntityType != null)
                {
                    var component = AuthenticationContainer.GetComponent(userLogin.EntityType.Name);
                    if (component != null && component.IsActive &&
                        (!component.RequiresRemoteAuthentication || component.TypeName == "Rock.Security.ExternalAuthentication.SMSAuthentication"))
                    {
                        if (component.Authenticate(userLogin, context.Password))
                        {
                            if ((userLogin.IsConfirmed ?? true) && !(userLogin.IsLockedOut ?? false))
                            {
                                OAuthContext         oAuthContext         = new OAuthContext();
                                ClientScopeService   clientScopeService   = new ClientScopeService(oAuthContext);
                                AuthorizationService authorizationService = new AuthorizationService(oAuthContext);
                                ClientService        clientService        = new ClientService(oAuthContext);

                                var scopes = (context.Scope.FirstOrDefault() ?? "").Split(',');

                                bool     scopesApproved   = false;
                                Client   OAuthClient      = clientService.GetByApiKey(context.ClientId.AsGuid());
                                string[] authorizedScopes = authorizationService.Queryable().Where(a => a.Client.Id == OAuthClient.Id && a.UserLogin.UserName == userName && a.Active == true).Select(a => a.Scope.Identifier).ToArray <string>();
                                if (!clientScopeService.Queryable().Where(cs => cs.ClientId == OAuthClient.Id && cs.Active == true).Any() ||
                                    (authorizedScopes != null && scopes.Where(s => !authorizedScopes.Select(a => a.ToLower()).Contains(s.ToLower())).Count() == 0))
                                {
                                    scopesApproved = true;
                                }

                                if (scopesApproved)
                                {
                                    var identity = new ClaimsIdentity(new GenericIdentity(userName, OAuthDefaults.AuthenticationType));

                                    //only allow claims that have been requested and the client has been authorized for
                                    foreach (var scope in scopes.Where(s => clientScopeService.Queryable().Where(cs => cs.ClientId == OAuthClient.Id && cs.Active == true).Select(cs => cs.Scope.Identifier.ToLower()).Contains(s.ToLower())))
                                    {
                                        identity.AddClaim(new Claim("urn:oauth:scope", scope));
                                    }
                                    UserLoginService.UpdateLastLogin(userName);
                                    context.Validated(identity);
                                    return(System.Threading.Tasks.Task.FromResult(0));
                                }
                                else
                                {
                                    context.SetError("Authentication Error", "All scopes are not authorized for this user.");
                                }
                            }
                            if (!userLogin.IsConfirmed ?? true)
                            {
                                context.SetError("Authentication Error", "Account email is unconfirmed.");
                            }
                            if (userLogin.IsLockedOut ?? false)
                            {
                                context.SetError("Authentication Error", "Account is locked.");
                            }
                        }
                        else
                        {
                            context.SetError("Authentication Error", "Invalid Username/Password.");
                        }
                    }
                    else
                    {
                        context.SetError("Authentication Error", "Invalid Authentication Configuration.");
                    }
                }
                else
                {
                    context.SetError("Authentication Error", "Invalid Username/Password.");
                }
            }
            else
            {
                context.SetError("Authentication Error", "Invalid Username/Password.");
            }

            context.Rejected();
            return(System.Threading.Tasks.Task.FromResult(0));
        }
 async public override System.Threading.Tasks.Task GrantResourceOwnerCredentials(OAuthGrantResourceOwnerCredentialsContext context)
 {
     try
     {
         //context.OwinContext.Response.Headers.Add("Access-Control-Allow-Origin", new[] { "*" });
         var header = context.OwinContext.Response.Headers.SingleOrDefault(h => h.Key == "Access-Control-Allow-Origin");
         if (header.Equals(default(KeyValuePair <string, string[]>)))
         {
             context.OwinContext.Response.Headers.Add("Access-Control-Allow-Origin", new[] { "*" });
         }
         using (SSRepository ssRepo = new SSRepository())
         {
             if (await ssRepo.ValidateUserAsync(null, context.UserName, context.Password))
             {
                 context.SetError("invalid_grant", "The username 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"));
         context.Validated(identity);
     }
     catch (Exception ex)
     {
         context.SetError("serviceunreachable", ex.Message.ToString());
         return;
     }
 }
Example #36
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 });
            string dept = null;

            //_appbl = new IdentityClientBL(context.OwinContext.Get<InfraEntities>());
            //IdentityClient app = await new IdentityClientBL(context.OwinContext.Get<InfraEntities>()).GetByName(context.ClientId);
            IdentityClient app = await new IdentityClientBL(new InfraEntities()).GetByName(context.ClientId);

            if (!app.Validation.IsValid)
            {
                context.Rejected();
                context.SetError("error: invalid_client");
                return;
            }

            //_userbl = new IdentityUserBL(context.OwinContext.Get<InfraEntities>());
            //_userbl = new IdentityUserBL(new InfraEntities(), _logger);


            //var user = await new IdentityUserBL(context.OwinContext.Get<InfraEntities>()).GetByUserIdByLogin(context.UserName, context.Password); //check table USERLOGIN
            var user = await new IdentityUserBL(new InfraEntities()).GetByUserIdByLogin(context.UserName, context.Password); //check table USERLOGIN

            if (user == Guid.Empty)                                                                                          //if exists in USERLOGIN(not used atm.. always null)
            {
                //var mgr = context.OwinContext.GetUserManager<ApplicationUserManager>();
                //var result = await mgr.FindAsync(context.UserName, context.Password);

                //IdentityUser userdto = await new IdentityUserBL(context.OwinContext.Get<InfraEntities>()).AuthenticateAsync(context.UserName, context.Password);
                IdentityUser userdto = await new IdentityUserBL(new InfraEntities()).AuthenticateAsync(context.UserName, context.Password);
                if (userdto == null)
                {
                    context.Rejected();
                    context.SetError("The password or username is incorrect");
                    return;
                }

                if (!userdto.Validation.IsValid)
                {
                    context.Rejected();
                    context.SetError(userdto.Validation.Errors.FirstOrDefault().ErrorMessage);
                    return;
                }
                dept = userdto.Department.ToString();
            }
            //var permissions = await new IdentityUserBL(context.OwinContext.Get<InfraEntities>()).ListAdministrativePermissionAsync(context.UserName, app.Applicationname.ToString());
            var permissions = await new IdentityUserBL(new InfraEntities()).ListAdministrativePermissionAsync(context.UserName, app.Applicationname.ToString());

            if (context.Scope != null || context.Scope.GetEnumerator().MoveNext())
            {
                foreach (var item in context.Scope)
                {
                    //permissions.Add(item);
                    //var additionalscope = await new IdentityUserBL(context.OwinContext.Get<InfraEntities>()).ListAdministrativePermissionAsync(context.UserName, item.ToString());
                    var additionalscope = await new IdentityUserBL(new InfraEntities()).ListAdministrativePermissionAsync(context.UserName, item.ToString());
                    foreach (var additionalscopeitem in additionalscope)
                    {
                        permissions.Add(additionalscopeitem);
                    }
                }
            }

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

            identity.AddClaim(new Claim(ClaimTypes.Name, context.UserName));
            identity.AddClaim(new Claim("sub", context.UserName));
            identity.AddClaim(new Claim("aud", app.Applicationid.ToString()));
            identity.AddClaim(new Claim("role", "user"));
            identity.AddClaim(new Claim("system", app.Applicationname.ToString()));
            identity.AddClaim(new Claim("department", dept));
            identity.AddClaim(new Claim("permissions", JsonConvert.SerializeObject(permissions)));


            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(identity, props);

            context.Validated(ticket);
        }
 internal static void SetInvalidGrantErrorAndReject(this OAuthGrantResourceOwnerCredentialsContext context)
 {
     context.SetErrorAndReject("invalid_grant", "The username or password is incorrect");
 }
Example #38
0
 public Task OnGrantResourceOwnerCredentials(OAuthGrantResourceOwnerCredentialsContext context)
 {
     return(Task.FromResult(0));;
 }
 private static void SetErrorAndReject(this OAuthGrantResourceOwnerCredentialsContext context, string error, string description)
 {
     context.SetError(error, description);
     context.Rejected();
 }
Example #40
0
        public override async Task GrantResourceOwnerCredentials(OAuthGrantResourceOwnerCredentialsContext context)
        {
            var             userManager = context.OwinContext.GetUserManager <ApplicationUserManager>();
            ApplicationUser user;
            // find user by username first
            var userName = await userManager.FindByNameAsync(context.UserName);

            if (userName != null)
            {
                user = await userManager.FindAsync(context.UserName, context.Password);

                // When a user is lockedout, this check is done to ensure that even if the credentials are valid
                // the user can not login until the lockout duration has passed
                if (await userManager.IsLockedOutAsync(userName.Id))
                {
                    context.SetError("lockout", string.Format("Your account has been locked out for {0} minutes due to multiple failed login attempts.", ConfigurationManager.AppSettings["DefaultAccountLockoutTimeSpan"]));
                    return;
                }
                // if user is subject to lockouts and the credentials are invalid
                // record the failure and check if user is lockedout and display message, otherwise,
                // display the number of attempts remaining before lockout
                else if (await userManager.GetLockoutEnabledAsync(userName.Id) && user == null)
                {
                    // Record the failure which also may cause the user to be locked out
                    await userManager.AccessFailedAsync(userName.Id);

                    string message;

                    if (await userManager.IsLockedOutAsync(userName.Id))
                    {
                        message = string.Format("Your account has been locked out for {0} minutes due to multiple failed login attempts.", ConfigurationManager.AppSettings["DefaultAccountLockoutTimeSpan"]);
                    }
                    else
                    {
                        int accessFailedCount = await userManager.GetAccessFailedCountAsync(userName.Id);

                        int attemptsLeft =
                            Convert.ToInt32(
                                ConfigurationManager.AppSettings["MaxFailedAccessAttemptsBeforeLockout"]) -
                            accessFailedCount;

                        message = string.Format(
                            "Invalid credentials. You have {0} more attempt(s) before your account gets locked out.", attemptsLeft);
                    }

                    context.SetError("lockout", message);
                    return;
                }
                else if (user == null)
                {
                    context.SetError("invalid_grant", "The user name or password is incorrect.");
                    return;
                }
                else if (user.Inactive)
                {
                    context.SetError("invalid_grant", "The user name is Inactive. Please contact Administrator.");
                    return;
                }
                else if (user.IsNYAttorneyPortalUser == false)
                {
                    context.SetError("invalid_grant", "The user name is Invalid. Please contact Administrator.");
                    return;
                }
                else
                {
                    // When token is verified correctly, clear the access failed count used for lockout
                    await userManager.ResetAccessFailedCountAsync(userName.Id);

                    userName.LastLoginDate = DateTime.Now;
                    userName.LoginCount    = userName.LoginCount + 1;
                    userManager.Update(userName);
                }
            }
            else
            {
                context.SetError("invalid_grant", "User name is incorrect.");
                return;
            }
            ClaimsIdentity oAuthIdentity = await user.GenerateUserIdentityAsync(userManager, "JWT");

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

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

            context.Validated(ticket);
            context.Request.Context.Authentication.SignIn(cookiesIdentity);
        }
Example #41
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, "User"));
                }
                else
                {
                    oAuthIdentity.AddClaim(new Claim(ClaimTypes.Role, "xuser"));
                }


                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);
                properties.Dictionary.Add("AuthId", user.Id);
                var company = await unitOfWork.CompanyRepository.GetViewCompanyByMobile(context.UserName);

                if (roles == "Company")
                {
                    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 (company != null)
                    {
                        properties.Dictionary.Add("Name", company.FullName);
                        properties.Dictionary.Add("UserId", company.Id.ToString());
                        properties.Dictionary.Add("Image", string.IsNullOrEmpty(company.ImageUrl) ? "" : company.ImageUrl.ToString());
                        properties.Dictionary.Add("Role", "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)
        {
            try
            {
                _panelRepository = Bootstrapper.WindsorContainer.Resolve <IPanelRepository>();
                string deviceId      = context.OwinContext.Get <string>("as:device_id");
                var    allowedOrigin = context.OwinContext.Get <string>("as:clientAllowedOrigin");
                if (allowedOrigin == null)
                {
                    allowedOrigin = "*";
                }
                context.OwinContext.Response.Headers.Add("Access-Control-Allow-Origin", new[] { allowedOrigin });

                var client = _repository.FindClient(context.ClientId);
                if (client == null)
                {
                    context.SetError("invalid_clientId", $"Client '{context.ClientId}' is not registered in the system.");
                    return;
                }
                if (client.ApplicationType == ApplicationType.JavaScript)
                {
                    var user = await _panelRepository.FindUser(context.UserName, context.Password);

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

                    var identity = new ClaimsIdentity(context.Options.AuthenticationType);
                    identity.AddClaim(new Claim(ClaimTypes.Name, context.UserName));
                    identity.AddClaim(new Claim("FirstName", user.FirstName));
                    identity.AddClaim(new Claim("LastName", user.LastName));
                    identity.AddClaim(new Claim("UserId", user.Id));
                    foreach (var role in roles)
                    {
                        identity.AddClaim(new Claim(ClaimTypes.Role, role));
                    }
                    var props = new AuthenticationProperties(new Dictionary <string, string>
                    {
                        {
                            "as:client_id", context.ClientId ?? string.Empty
                        },
                        {
                            "userId", user.Id
                        },
                        {
                            "firstName", user.FirstName
                        },
                        {
                            "lastName", user.LastName
                        }
                    });
                    var ticket = new AuthenticationTicket(identity, props);
                    context.Validated(ticket);
                }
                else if (client.ApplicationType == ApplicationType.CustomerUserApp || client.ApplicationType == ApplicationType.ShopUserApp)
                {
                    var appUser  = _userManager.Users.SingleOrDefault(item => item.PhoneNumber == context.UserName);
                    var rolesApp = await _repository.GetUserRoles(appUser);

                    if (appUser == null)
                    {
                        context.SetError("invalid_grant", "کاربر یافت نشد");
                        return;
                    }

                    switch (client.ApplicationType)
                    {
                    case ApplicationType.CustomerUserApp:
                    {
                        if (!appUser.CustomerIsActive)
                        {
                            context.SetError("invalid_grant", "کاربر غیرفعال می باشد");
                        }
                        break;
                    }

                    case ApplicationType.ShopUserApp:
                    {
                        if (!appUser.ShopIsActive)
                        {
                            context.SetError("invalid_grant", "کاربر غیرفعال می باشد");
                        }
                        break;
                    }
                    }

                    await VerifyPhoneNumber(appUser, context.Password, context.UserName);

                    var identityApp = new ClaimsIdentity(context.Options.AuthenticationType);
                    identityApp.AddClaim(new Claim(ClaimTypes.Name, context.UserName));
                    identityApp.AddClaim(new Claim("UserId", appUser.Id));
                    identityApp.AddClaim(new Claim("MobileNumber", appUser.PhoneNumber));
                    identityApp.AddClaim(new Claim("DeviceId", deviceId));
                    identityApp.AddClaim(new Claim("ShopIsActive", appUser.ShopIsActive.ToString()));
                    identityApp.AddClaim(new Claim("CustomerIsActive", appUser.CustomerIsActive.ToString()));
                    identityApp.AddClaim(new Claim("RegisterDate", appUser.RegisterDate.ToString()));
                    foreach (var role in rolesApp)
                    {
                        identityApp.AddClaim(new Claim(ClaimTypes.Role, role));
                    }
                    var appProps = new AuthenticationProperties(new Dictionary <string, string>
                    {
                        {
                            "as:client_id", context.ClientId ?? string.Empty
                        },
                        {
                            "userId", appUser.Id
                        },
                        {
                            "mobileNumber", appUser.PhoneNumber
                        }
                    });
                    var appTicket = new AuthenticationTicket(identityApp, appProps);
                    context.Validated(appTicket);
                }
            }
            catch (Exception e)
            {
                context.SetError("invalid_grant", e.Message);
            }
        }
        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>();
            User user        = new User();

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

            var mapper = new DiObjectMapper();
            ApplicationLogViewModel logViewModel = new ApplicationLogViewModel()
            {
                Action = "Login",
                Data   = user,
                Entity = "User"
            };

            if (user == null)
            {
                logViewModel.Data = new { UserName = context.UserName }
            }
            ;

            var appLog = mapper.Map <ApplicationLogViewModel, ApplicationLog>(logViewModel);

            appLog.IpAddress = GeneralService.ClientIpFromHeader;
            appLog.LogType   = General.Enums.LogType.System;
            appLog.Date      = GeneralService.CurrentDate;

            var mbosContext = MBOSContext.Create();

            if (user == null)
            {
                appLog.Description = "Invalid username or password";
                mbosContext.ApplicationLogs.Add(appLog);
                mbosContext.SaveChanges();
                context.SetError("invalid_grant", "The username or password is incorrect.");
                return;
            }
            if (!user.EmailConfirmed)
            {
                appLog.Description = "Account email is not confirmed.";
                mbosContext.ApplicationLogs.Add(appLog);
                mbosContext.SaveChanges();
                context.SetError("invalid_grant", "Email is not confirmed yet.");
                return;
            }
            if (user.AccessFailedCount >= 3)
            {
                appLog.Description = "Account is locked.";
                mbosContext.ApplicationLogs.Add(appLog);
                mbosContext.SaveChanges();
                context.SetError("invalid_grant", "Your account has been locked. Please contact the administrator!");
                return;
            }
            appLog.UserId      = user.Id;
            appLog.Description = "Login successful.";
            mbosContext.ApplicationLogs.Add(appLog);
            mbosContext.SaveChanges();
            var loginInfo = new LoginInfo()
            {
                UserId            = user.Id,
                FullName          = user.FullName,
                DisplayPicture    = string.IsNullOrEmpty(user.DisplayPicture) ? "Resources/DisplayPictures/noimage.jpg" : user.DisplayPicture,
                LoginUserBranches = user.UserBranches.Select(c => new LoginUserBranch()
                {
                    Id = (Guid)c.BranchId, Name = c.Branch.Name, ShortName = c.Branch.ShortName
                }).ToList(),
                RoleId       = user.Roles.Select(c => c.RoleId).FirstOrDefault(),
                RoleType     = user.Roles.Select(c => c.Role.RoleType).FirstOrDefault(),
                DepartmentId = user.DepartmentId, Role = user.Roles.Select(c => c.Role.Name).FirstOrDefault()
            };
            var loginInfoValue = Newtonsoft.Json.JsonConvert.SerializeObject(loginInfo);
            IDictionary <string, string> authProp = new Dictionary <string, string>
            {
                { "LoginInfo", loginInfoValue }
            };
            var claims = new List <Claim>()
            {
                new Claim("LoginInfo", loginInfoValue)
            };
            ClaimsIdentity oAuthIdentity = await user.GenerateUserIdentityAsync(userManager, OAuthDefaults.AuthenticationType, claims);

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


            AuthenticationProperties properties = new AuthenticationProperties(authProp);
            AuthenticationTicket     ticket     = new AuthenticationTicket(oAuthIdentity, properties);

            context.Validated(ticket);
            context.Request.Context.Authentication.SignIn(cookiesIdentity);
        }
        /*public override async Task ValidateClientAuthentication(OAuthValidateClientAuthenticationContext context)
         * {
         *  context.Validated();
         * }*/

        public override async Task GrantResourceOwnerCredentials(OAuthGrantResourceOwnerCredentialsContext context)
        {
            context.OwinContext.Response.Headers.Add("Access-Control-Allow-Origin", new[] { "*" });
            //
            var identity = new ClaimsIdentity(context.Options.AuthenticationType);

            using (AuthenticationRepository _repo = new AuthenticationRepository())
            {
                IdentityUser user = await _repo.FindUser(context.UserName, context.Password);

                using (var db = new GatewayPCIPINContext())
                {
                    if (db != null)
                    {
                        var users = db.AspNetUsers.ToList();
                        //var roles = db.AspNetRoles.ToList();
                        //var users_roles = db.AspNetUserRoles.ToList();
                        var organizations = db.Organizations.ToList();

                        if (users != null && organizations != null && user != null)
                        {
                            if (!string.IsNullOrEmpty(users.Where(u => u.UserName == context.UserName && u.PasswordHash == context.Password).FirstOrDefault().UserName) && !string.IsNullOrEmpty(organizations.Where(o => o.OrganizationType.Id == organizme_type_merchant).FirstOrDefault().OrganizationType.Type))
                            {
                                //
                                identity.AddClaim(new Claim("sub", context.UserName));
                                identity.AddClaim(new Claim("role", "user_merchant"));
                                identity.AddClaim(new Claim(ClaimTypes.Role, "user_merchant"));
                                identity.AddClaim(new Claim(ClaimTypes.Name, context.UserName));
                                //

                                var props = new AuthenticationProperties(new Dictionary <string, string>
                                {
                                    {
                                        "userdisplayname", context.UserName
                                    },
                                    {
                                        "role", "user_merchant"
                                    }
                                });

                                var ticket = new AuthenticationTicket(identity, props);
                                context.Validated(ticket);
                            }
                        }
                        else
                        {
                            context.SetError("invalid_grant", "The user name or password is incorrect.");
                            return;
                        }
                    }
                }

                /*if (user == 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_merchant"));*/

            context.Validated(identity);
        }
Example #45
0
        public override async Task GrantResourceOwnerCredentials(OAuthGrantResourceOwnerCredentialsContext context)
        {
            var client = context.OwinContext.Get <Client>(Constant.OAuthorization_OAuth_Client);

            if (client == null)
            {
                return;
            }

            var allowedOrigin = context.OwinContext.Get <string>(Constant.OAuthorization_OAuth_ClientAllowedOrigin);

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

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

            UserManager <ApplicationUser> userManager = context.OwinContext.GetUserManager <UserManager <ApplicationUser> >();
            ApplicationUser user;

            try
            {
                user = await userManager.FindAsync(context.UserName, context.Password);
            }
            catch (Exception ex)
            {
                // Could not retrieve the user due to error.
                context.SetError(Constant.OAuthorization_Server_Error + ex);
                context.Rejected();
                return;
            }
            if (user != null)
            {
                //ClaimsIdentity identity = await userManager.CreateIdentityAsync(
                //                            user,
                //                            DefaultAuthenticationTypes.ExternalBearer);
                //context.Validated(identity);

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

                var claimsIdentity = new ClaimsIdentity(context.Options.AuthenticationType);
                var claims         = new List <Claim>();
                claims.Add(new Claim(ClaimTypes.NameIdentifier, user.UserName));
                claims.Add(new Claim(ClaimTypes.Role, string.Join(",", userRoles)));
                claims.Add(new Claim("Email", user.Email));
                claimsIdentity.AddClaims(claims);

                var props = new Dictionary <string, string>()
                {
                    [Constant.OAuthorization_Properties_ClientId] = context.ClientId == null ? string.Empty : context.ClientId,
                    [Constant.OAuthorization_Properties_UserName] = context.UserName
                };
                var oauthProperties = new AuthenticationProperties(props);
                var oauthTicket     = new AuthenticationTicket(claimsIdentity, oauthProperties);
                context.Validated(oauthTicket);
            }
            else
            {
                context.SetError(Constant.OAuthorization_Invalid_Grant, "Tài khoản hoặc mật khẩu không đúng.'");
                context.Rejected();
            }
        }
Example #46
0
        public override async Task GrantResourceOwnerCredentials(OAuthGrantResourceOwnerCredentialsContext context)
        {
            context.OwinContext.Response.Headers.Add("Access-Control-Allow-Origin", new[] { "*" });
            //IAuthRepository authRepository = new AuthRepository();
            //var companyCode = context.OwinContext.Environment["companyCode"].ToString();
            //var culture = context.OwinContext.Environment["culture"].ToString();

            var rep = ContainerManager.Resolve <IEfRepository>();

            var user = await rep.FirstOrDefaultAsync <UserModel>(s => s != null && s.IsDeleted != 1 && (s.ADAccount == context.UserName || s.Code == context.UserName) && s.Password == context.Password /*&& s.CompanyCode == companyCode*/);

            //var user = await ContainerManager.Resolve<IAuthRepository>().FindUser(context.UserName, context.Password, "");

            if (user == null)
            {
                context.SetError("invalid_grant", "The user name or password is incorrect.");
                context.SetError("res_code", "60005");
                context.SetError("ErrorCode", "ERROR_LOGIN");
                context.SetError("res_msg", "登录失败");
                return;
            }

            //var rep = ContainerManager.Resolve<IEfRepository>();
            var cache = ContainerManager.Resolve <ICacheManager>();
            var roles = (from a in rep.Table <RoleInfo>()
                         join b in rep.Table <UserRole>() on a.Id equals b.RoleId
                         where b.SapCode == user.Code && a.IsDeleted != 1 && b.IsDeleted != 1
                         select a).ToList();

            //cache.Clear();
            var workUser = new WorkUser
            {
                User  = user,
                Roles = roles
            };

            cache.Set(user.Id.ToString(), workUser, 12);

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

            identity.AddClaim(new Claim(ClaimTypes.Name, user.Id.ToString()));
            identity.AddClaim(new Claim(ClaimTypes.Role, "user"));
            //加入client字典用于刷新token
            var props = new AuthenticationProperties(new Dictionary <string, string>
            {
                {
                    "as:client_id", context.ClientId ?? string.Empty
                },
                {
                    "userName", context.UserName
                },
                {
                    "name", user.Code ?? string.Empty
                },
                {
                    "res_code", "6000"
                },
                {
                    "res_msg", "登录成功"
                }
            });
            var ticket = new AuthenticationTicket(identity, props);

            context.Validated(ticket);
        }
Example #47
0
        public override async System.Threading.Tasks.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>();

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

            if (user == null || user.Attempts >= MaxAttempts)
            {
                context.SetError("invalid_grant", "The user name or password is incorrect.");
                return;
            }
            context.
            if (!await userManager.CheckPasswordAsync(user, context.Password))
            {
                user.Attempts++;
                await userManager.UpdateAsync(user);

                await context.OwinContext.Get <ApplicationDbContext>().SaveChangesAsync();

                context.SetError("invalid_grant", "The user name or password is incorrect.");
                return;
            }
            user.Attempts = 0;
            await userManager.UpdateAsync(user);

            await context.OwinContext.Get <ApplicationDbContext>().SaveChangesAsync();

            string[] values;
            if (!context.Request.Headers.TryGetValue("Imei", out values))
            {
                context.SetError("no_imei", "Imei not specified");
                return;
            }
            var     imei = values.FirstOrDefault();
            UserKey key;

            try
            {
                using (var db = new ApplicationDbContext())
                {
                    var userEntity = await db.Users.FirstOrDefaultAsync(u => u.UserName == user.UserName);

                    key = await db.Keys.FirstOrDefaultAsync(k => k.User.UserName == userEntity.UserName && k.Imei == imei);

                    if (key == null)
                    {
                        key = new UserKey
                        {
                            Imei           = imei,
                            UserStorageKey = BouncyCastleHelper.DbProtection(BouncyCastleHelper.GenerateSerpentKey()),
                            User           = userEntity
                        };
                        db.Keys.Add(key);
                        await db.SaveChangesAsync();
                    }
                    else if (key.UserStorageKey == null)
                    {
                        key.UserStorageKey  = BouncyCastleHelper.DbProtection(BouncyCastleHelper.GenerateSerpentKey());
                        db.Entry(key).State = EntityState.Modified;
                        await db.SaveChangesAsync();
                    }
                }

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

                AuthenticationProperties properties = CreateProperties(user, key);
                AuthenticationTicket     ticket     = new AuthenticationTicket(oAuthIdentity, properties);
                context.Validated(ticket);
            }
            catch (Exception ex)
            {
                throw ex;
            }
        }
        public override async Task GrantResourceOwnerCredentials(OAuthGrantResourceOwnerCredentialsContext context)
        {
            context.OwinContext.Response.Headers.Add("Access-Control-Allow-Origin", new[] { "*" });

            User          user     = null;
            string        roleId   = string.Empty;
            StringBuilder roleName = new StringBuilder();

            //List<UserRolesModel> roles = null;
            //List<UserPermissionNamesModel> perms = null;

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

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

                Tuple <bool, string, List <RoleViewModel1> > result = await _repo.GetUserRoleByID(iuser.Id);

                if (result.Item1)
                {
                    foreach (RoleViewModel1 role in result.Item3)
                    {
                        roleId   = role.RoleID;
                        roleName = roleName.Append(role.RoleName + ", ");
                    }
                }

                user = new User
                {
                    Id       = iuser.Id,
                    UserName = iuser.UserName,
                    RoleID   = roleId,
                    RoleName = roleName.ToString().Substring(0, roleName.Length - 2)
                };
            }

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

            identity.AddClaim(new Claim(ClaimTypes.Name, user.UserName));
            identity.AddClaim(new Claim(ClaimTypes.NameIdentifier, user.Id));
            identity.AddClaim(new Claim(ClaimTypes.NameIdentifier, roleId));

            var properties = new AuthenticationProperties(new Dictionary <string, string>
            {
                { "as:client_id", context.ClientId ?? string.Empty },
                { "userName", context.UserName },
                { "userId", user.Id },
                { "roleId", roleId },
                { "roleName", user.RoleName }
            });


            var ticket = new AuthenticationTicket(identity, properties);

            context.Validated(ticket);

            context.Validated(identity);
        }
        public override async Task GrantResourceOwnerCredentials(OAuthGrantResourceOwnerCredentialsContext context)
        {
            ApplicationDbContext db = new ApplicationDbContext();
            var userManager         = context.OwinContext.GetUserManager <ApplicationUserManager>();

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

            if (user == null)
            {
                context.SetError("invalid_grant. The user name or password is incorrect.");
                return;
            }
            // check if account is lock or not
            if (await userManager.IsLockedOutAsync(user.Id))
            {
                context.SetError("Your account has been locked. Please contact system admin.");
                return;
            }
            var check = await userManager.CheckPasswordAsync(user, context.Password);

            if (!check)
            {
                int accessFailedCount = await userManager.GetAccessFailedCountAsync(user.Id);

                int attemptsLeft = userManager.MaxFailedAccessAttemptsBeforeLockout - (accessFailedCount + 1);
                if (attemptsLeft == 0)
                {
                    var result = await userManager.SetLockoutEnabledAsync(user.Id, true);

                    if (result.Succeeded)
                    {
                        await userManager.SetLockoutEndDateAsync(user.Id, DateTime.Now.AddYears(1));

                        context.SetError(string.Format("Your account has been locked as a result of too many unsuccessful attempts. Please contact system admin to unloack your account."));
                    }
                }
                else
                {
                    await userManager.AccessFailedAsync(user.Id);
                }
                string message = string.Format("Invalid credentials. You have {0} more attempt(s) before your account gets locked out.", attemptsLeft);
                context.SetError(message);
                return;
            }
            if (!await userManager.IsEmailConfirmedAsync(user.Id))
            {
                context.SetError(string.Format("Your account has been not activated. Please contact system admin to activate your account."));
                return;
            }
            await userManager.ResetAccessFailedCountAsync(user.Id);

            //Add role in token
            var roleid    = user.Roles.Where(x => x.UserId == user.Id).Select(y => y.RoleId).ToList();
            var roleStore = new RoleStore <IdentityRole>(db);
            var roleMngr  = new RoleManager <IdentityRole>(roleStore);
            var role      = roleMngr.Roles.Where(x => roleid.Contains(x.Id)).Select(y => y.Name).ToList();
            //var role = roleMngr.Roles.Where(x => x.Id == roleid).Select(y => y.Name).ToList();
            string Roles = string.Join(",", role);

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

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

            AuthenticationProperties properties = CreateProperties(user.UserName);

            properties.Dictionary.Add("role", Roles);
            properties.Dictionary.Add("id", user.Id);
            AuthenticationTicket ticket = new AuthenticationTicket(oAuthIdentity, properties);

            context.Validated(ticket);
            context.Request.Context.Authentication.SignIn(cookiesIdentity);

            //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 (await userManager.IsLockedOutAsync(user.Id))
            //{
            //    context.SetError("locked_out", "User is locked out");
            //    return;
            //}
            //var check = await userManager.CheckPasswordAsync(user, context.Password);
            //if (!check)
            //{
            //    userManager.MaxFailedAccessAttemptsBeforeLockout = 5;
            //    await userManager.AccessFailedAsync(user.Id);
            //    context.SetError("invalid_grant", "Wrong username or password."); //wrong password
            //    return;
            //}
            //await userManager.ResetAccessFailedCountAsync(user.Id);

            //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);
        }
        // Опис: Методот врши испраќање на валидираните кориснички податоци до сервер
        // Влезни параметри: OAuthGrantResourceOwnerCredentialsContext context
        // Излезни параметри: Task од извршеното валидирање на испратените кориснички податоци
        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 pk  = publicKey;
            var cpk = pk.Replace("i2n0t1e5rop", "+");

            _logger.Info("publicKey changed:" + cpk);
            using (AuthRepository _repo = new AuthRepository(new UnitOfWork(new InteropContext())))
            {
                ApplicationUser user = await _repo.FindUser(context.UserName, context.Password);

                _logger.Info("context.UserName:"******"context.Password:"******"publicKey compare:" + publicKey);
                if (user == null)
                {
                    _logger.Info("Userot e null");
                }
                else
                {
                    _logger.Info("user.PublicKey compare:" + user.PublicKey);
                }
                if (user == null || cpk != user.PublicKey)
                {
                    context.SetError("invalid_grant", "The user name or password is incorrect.");
                    return;
                }

                roleNames = await _repo.FindRoleAsync(user.Id);
            }

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

            identity.AddClaim(new Claim(ClaimTypes.Name, context.UserName));
            identity.AddClaim(new Claim("sub", context.UserName));
            foreach (var role in roleNames)
            {
                identity.AddClaim(new Claim(ClaimTypes.Role, role));
            }


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

            var ticket = new AuthenticationTicket(identity, props);

            // creating ACCESS TOKEN
            context.Validated(ticket);
        }
        public override async Task GrantResourceOwnerCredentials(OAuthGrantResourceOwnerCredentialsContext context)
        {
            context.OwinContext.Response.Headers.Add("Access-Control-Allow-Origin", new[] { "*" });
            string Username = string.Empty, Roles = string.Empty, CorrelationId = Guid.NewGuid().ToString();

            Username = context.UserName;
            //using owincontext
            if (string.IsNullOrEmpty(Username))
            {
                Username = HttpContext.Current.GetOwinContext().Request.User.Identity.Name;
            }

            CustomerInfo cust = new CustomerInfo();

            cust.email    = Username;
            cust.Password = context.Password;


            AccountManagementService    accService = new AccountManagementService();
            ReturnResult <CustomerInfo> result     = new ReturnResult <CustomerInfo>();

            result = accService.GetCustomer(cust);
            if (result.status.Status != StatusEnum.Success)
            {
                return;
            }


            //using windowsidentity
            //if (string.IsNullOrEmpty(Username))
            //{
            //    Username = WindowsIdentity.GetCurrent().Name;
            //}
            ////extract the username excluding domain name
            //Username = Username.Contains(@"\") ? Username.Substring(Username.LastIndexOf(@"\") + 1) : Username;
            //Username = Username.ToLower();

            ////hardcoded values for test
            //List<Role> roles = new List<Role>();
            //roles.Add(new Role() { Id = 2400, Name = "Viewer", Description = "Viewer" });
            //roles.Add(new Role() { Id = 2401, Name = "Originator", Description = "Originator" });
            //Roles = string.Join(",", from item in roles select item.Id.ToString());

            //check if the user has access
            //APIHelper api = new APIHelper();
            ////IList<int> roles = api.GetUserRoles(Username, CorrelationId);
            //IList<int> roles = new List<int>();
            //roles.Add(2600);



            string UserID = Convert.ToString(result.result.User.UserID);
            //if user has access generate token with Username and Roles in claims
            var identity = new ClaimsIdentity(context.Options.AuthenticationType);

            identity.AddClaim(new Claim(ClaimTypes.Name, Username));
            //identity.AddClaim(new Claim(ClaimTypes.Role, Roles));
            identity.AddClaim(new Claim(ClaimTypes.SerialNumber, CorrelationId));
            identity.AddClaim(new Claim(ClaimTypes.UserData, UserID));
            // identity.AddClaim(new Claim(ClaimTypes.GivenName, result.result.User.FirstName));
            AuthenticationProperties properties = CreateProperties(Username, result.result.User.FirstName, UserID);

            AuthenticationTicket ticket = new AuthenticationTicket(identity, properties);
            await Task.Run(() => context.Validated(ticket));
        }
Example #53
0
        /// <summary>
        /// Resource Owner Password Credentials Grantのカスタム認証ロジック
        /// TokenEndpointPathへの grant_type = password アクセスは、こちらに到達する。
        /// ・context.Username および context.Password を検証する。
        /// ・クライアントは"access_token" および "refresh_token" を取得する。
        /// </summary>
        /// <param name="context">OAuthGrantResourceOwnerCredentialsContext</param>
        /// <returns>Task</returns>
        /// <see cref="https://msdn.microsoft.com/ja-jp/library/dn343587.aspx"/>
        public override async Task GrantResourceOwnerCredentials(OAuthGrantResourceOwnerCredentialsContext context)
        {
            if (!ASPNETIdentityConfig.EnableResourceOwnerCredentialsGrantType)
            {
                throw new NotSupportedException(Resources.ApplicationOAuthBearerTokenProvider.EnableResourceOwnerCredentialsGrantType);
            }

            // この実装は、ValidateClientAuthenticationの続きで、ClientのOAuth権限を確認する。
            // 権限がある場合、Resource Owner Password Credentialsグラント種別の処理フローを継続する。

            try
            {
                // ApplicationUser を取得する。
                ApplicationUserManager userManager
                    = HttpContext.Current.GetOwinContext().GetUserManager <ApplicationUserManager>();

                // username=ユーザ名&password=パスワードとして送付されたクレデンシャルを検証する。
                ApplicationUser user = await userManager.FindAsync(context.UserName, context.Password);

                if (user != null)
                {
                    // ユーザーが見つかった場合。

                    try
                    {
                        // ユーザーに対応するClaimsIdentityを生成する。
                        ClaimsIdentity identity = await userManager.CreateIdentityAsync(
                            user, DefaultAuthenticationTypes.ExternalBearer);

                        // ClaimsIdentityに、その他、所定のClaimを追加する。
                        OAuth2ProviderHelper.AddClaim(identity, context.ClientId, "", "", context.Scope);

                        // 検証完了
                        context.Validated(identity);

                        // オペレーション・トレース・ログ出力
                        Logging.MyOperationTrace(string.Format("{0}({1}) passed the 'resource owner password credentials flow' by {2}({3}).",
                                                               user.Id, user.UserName, context.ClientId, OAuth2ProviderHelper.GetInstance().GetClientName(context.ClientId)));
                    }
                    catch
                    {
                        // ClaimManagerIdentityは、UserManagerで作成できませんでした。
                        context.SetError(
                            "server_error",
                            Resources.ApplicationOAuthBearerTokenProvider.server_error2);

                        // 拒否
                        context.Rejected();
                    }
                }
                else
                {
                    // ユーザーが見つからなかった場合。

                    // Resources Ownerの資格情報が無効であるか、Resources Ownerが存在しません。
                    context.SetError(
                        "access_denied",
                        Resources.ApplicationOAuthBearerTokenProvider.access_denied);

                    // 拒否
                    context.Rejected();
                }
            }
            catch
            {
                // ユーザーを取得できませんでした。
                context.SetError(
                    "server_error",
                    Resources.ApplicationOAuthBearerTokenProvider.server_error1);

                // 拒否
                context.Rejected();
            }
        }
Example #54
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);
                }
            }
        }
Example #55
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);
        }
        public override async Task GrantResourceOwnerCredentials(OAuthGrantResourceOwnerCredentialsContext context)
        {
            Client client = context.OwinContext.Get <Client>("as:requested_client");

            var allowedOrigin = "NONE";

            List <ClientAllowedOrigin> _allowedOrigins;

            if (!(client == null))
            {
                _allowedOrigins = client.AllowedOrigins;
            }
            else
            {
                _allowedOrigins = await UnitOfWork.ClientStore.ListAllowedOrigins(new Guid());
            }
            string _originPath = NullHandlers.NES(context.Request.Headers["Origin"]);

            if (_originPath == "")
            {
                allowedOrigin = "*";
            }
            else
            {
                string _originCompare = _originPath.ToLower().Trim();
                if (_originCompare.LastIndexOf("/") != (_originCompare.Length - 1))
                {
                    _originCompare += "/";
                }
                foreach (ClientAllowedOrigin _origin in _allowedOrigins)
                {
                    string _allowedCompare = _origin.AllowedURL.ToLower().Trim();
                    if ((_allowedCompare.LastIndexOf("/") != (_allowedCompare.Length - 1)) && (_allowedCompare != "*"))
                    {
                        _allowedCompare += "/";
                    }
                    if ((_origin.AllowedURL.ToLower().Trim() == "*") || (_origin.AllowedURL.ToLower().Trim() == _originCompare))
                    {
                        allowedOrigin = _originPath;
                        break;
                    }
                }
            }

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

            User user = await UnitOfWork.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 UnitOfWork.UserManager.GenerateUserIdentityAsync(user, "JWT");

            oAuthIdentity.AddClaims(UnitOfWork.ClaimStore.GetClaims(user));
            //oAuthIdentity.AddClaims(RolesFromClaims.CreateRolesBasedOnClaims(oAuthIdentity));

            AuthenticationProperties prop = new AuthenticationProperties();

            prop.Dictionary.Add("as:issuer", "http://localhost:50378");
            prop.Dictionary.Add("as:user_id", NullHandlers.NES(user.Id));
            prop.Dictionary.Add("as:client_id", ConfigurationManager.AppSettings["as:AudienceId"]);
            prop.Dictionary.Add("as:client_secret", ConfigurationManager.AppSettings["as:AudienceSecret"]);
            var ticket = new AuthenticationTicket(oAuthIdentity, prop);

            context.Validated(ticket);
        }
Example #57
0
        /// <summary>
        /// Called when a request to the Token endpoint arrives with a "grant_type" of "password". This occurs when the user has provided name and password
        ///             credentials directly into the client application's user interface, and the client application is using those to acquire an "access_token" and
        ///             optional "refresh_token". If the web application supports the
        ///             resource owner credentials grant type it must validate the context.Username and context.Password as appropriate. To issue an
        ///             access token the context.Validated must be called with a new ticket containing the claims about the resource owner which should be associated
        ///             with the access token. The application should take appropriate measures to ensure that the endpoint isn’t abused by malicious callers.
        ///             The default behavior is to reject this grant type.
        ///             See also http://tools.ietf.org/html/rfc6749#section-4.3.2
        /// </summary>
        /// <param name="context">The context of the event carries information in and results out.</param>
        /// <returns>
        /// Task to enable asynchronous execution
        /// </returns>
        public override async Task GrantResourceOwnerCredentials(OAuthGrantResourceOwnerCredentialsContext context)
        {
            string userName    = "";
            string memberEmail = "";
            var    logWallet   = new LogWallet();

            try
            {
                var aesPassword = ApiCommonConstant.AESPassword;
                var data        = await context.Request.ReadFormAsync();

                memberEmail = data["memberEmail"] != null?SimpleAesUtil.DecryptAES(data["memberEmail"], aesPassword) : string.Empty;

                var memberPassword = data["memberPassword"] != null?SimpleAesUtil.DecryptAES(data["memberPassword"], aesPassword) : string.Empty;

                userName = data["mobileapi"] != null && data["mobileapi"] == "1" ? SimpleAesUtil.DecryptAES(context.UserName, aesPassword) : context.UserName;
                var password = data["mobileapi"] != null && data["mobileapi"] == "1" ? SimpleAesUtil.DecryptAES(context.Password, aesPassword) : context.Password;

                var            type              = "apiuser";
                string         errorMessage      = "";
                bool           failedMemberLogin = false;
                ClaimsIdentity oAuthIdentity     = null;
                //ClaimsIdentity cookiesIdentity = null;

                if (data["memberEmail"] != null && data["memberPassword"] != null)
                {
                    //var memberUserManager =
                    //    new ApplicationUserManager(new UserStore<IdentityUser>());
                    //var memberUser = memberUserManager.FindByEmail(memberEmail);
                    //if (memberUser != null && memberUserManager.CheckPassword(memberUser, memberPassword))
                    //{
                    //    oAuthIdentity = await memberUserManager.CreateIdentityAsync(memberUser, context.Options.AuthenticationType);
                    //    cookiesIdentity = await memberUserManager.CreateIdentityAsync(memberUser, CookieAuthenticationDefaults.AuthenticationType);
                    //    type = "memberuser";
                    //}
                    //else
                    //{
                    //    errorMessage = "Invalid member email and/or password";
                    //    failedMemberLogin = true;
                    //}
                }
                using (UserManager <User> userManager = _userManagerFactory())
                {
                    var user = await userManager.FindAsync(userName, password);

                    if (user == null)
                    {
                        logWallet.Log(MethodBase.GetCurrentMethod(), "The user name or password is incorrect.", null, "");
                        context.SetError("invalid_grant", "The user name or password is incorrect.");
                        return;
                    }
                    if (oAuthIdentity == null)
                    {
                        oAuthIdentity = await userManager.CreateIdentityAsync(user,
                                                                              context.Options.AuthenticationType);
                    }
                    oAuthIdentity.AddClaim(new Claim("clientId", userName));
                    oAuthIdentity.AddClaim(new Claim("permission", user.Permission));
                    oAuthIdentity.AddClaim(new Claim("role", user.Role));
                    oAuthIdentity.AddClaim(new Claim("password", password));
                    oAuthIdentity.AddClaim(new Claim("secretkey", user.ApiSecretkey));
                    oAuthIdentity.AddClaim(new Claim("type", type));
                    oAuthIdentity.AddClaim(new Claim("environment", "staging"));
                    // For logging purposes. Accessed by User.Identity.Name in this project ONLY.
                    oAuthIdentity.AddClaim(new Claim(ClaimTypes.Name, userName));

                    //if (cookiesIdentity == null)
                    //{
                    //    cookiesIdentity = await userManager.CreateIdentityAsync(user,
                    //        CookieAuthenticationDefaults.AuthenticationType);
                    //}
                    //cookiesIdentity.AddClaim(new Claim("clientId", userName));
                    //cookiesIdentity.AddClaim(new Claim("permission", user.Permission));
                    //cookiesIdentity.AddClaim(new Claim("role", user.Role));
                    //cookiesIdentity.AddClaim(new Claim("password", password));
                    //cookiesIdentity.AddClaim(new Claim("secretkey", user.ApiSecretkey));
                    //cookiesIdentity.AddClaim(new Claim("type", type));
                    //cookiesIdentity.AddClaim(new Claim("environment", "staging" ));

                    AuthenticationProperties properties = CreateProperties(user.UserName);
                    properties.Dictionary.Add("type", type);
                    properties.Dictionary.Add("error_message", errorMessage);

                    if (failedMemberLogin)
                    {
                        properties.Dictionary.Add("failed_member_login", "1");
                    }
                    AuthenticationTicket ticket = new AuthenticationTicket(oAuthIdentity, properties);

                    context.Validated(ticket);
                    //context.Request.Context.Authentication.SignIn(cookiesIdentity);
                }
            }
            catch (Exception ex)
            {
                logWallet.Log(MethodBase.GetCurrentMethod(), "userName: "******". memberEmail: " + memberEmail, ex, "");
                EmailUtil.SendEmail("[Exception]-[OAUTH]", ex.StackTrace);
                throw;
            }
        }
        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 #59
0
        public override async Task GrantResourceOwnerCredentials(OAuthGrantResourceOwnerCredentialsContext context)
        {
            var identity = new ClaimsIdentity(context.Options.AuthenticationType);

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

            try
            {
                // ResponseDTO response = ActiveDirectroryAuthenticationHelper.GetAuthenticated(context.UserName , password);
                var props = new AuthenticationProperties(new Dictionary <string, string>
                {
                    {
                        "userdisplayname", context.UserName
                    },
                    {
                        "role", "admin"
                    }
                });

                //var props = new AuthenticationProperties("sunil",)

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

                /*
                 * using (var cnAPIEntities = new CNAPIEntities())
                 * {
                 *  if (cnAPIEntities != null)
                 *  {
                 *      var user = cnAPIEntities.UserRegisters.ToList();
                 *      var admin = cnAPIEntities.AdminUsers.ToList();
                 *      if (user != null)
                 *      {
                 *          string password = context.Password;
                 *          var UserDmin = admin.Find(u => u.UserADID == context.UserName);
                 *          if (UserDmin != null)
                 *          {
                 *              // ResponseDTO response = ActiveDirectroryAuthenticationHelper.GetAuthenticated(context.UserName , password);
                 *              var props = new AuthenticationProperties(new Dictionary<string, string>
                 *              {
                 *                 {
                 *                  "userdisplayname", context.UserName
                 *                 },
                 *                 {
                 *                   "role", "admin"
                 *                 }
                 *              });
                 *
                 *              var ticket = new AuthenticationTicket(identity, props);
                 *              context.Validated(ticket);
                 *
                 *          }
                 *          else if(!string.IsNullOrEmpty(user.Where(u => u.EmailAddress == context.UserName && u.Password == password).FirstOrDefault().FirstName))
                 *          {
                 *             // identity.AddClaim(new Claim("Age", "16"));
                 *
                 *              var props = new AuthenticationProperties(new Dictionary<string, string>
                 *              {
                 *                {
                 *                  "userdisplayname", context.UserName
                 *                },
                 *                {
                 *                   "role", "user"
                 *                }
                 *              });
                 *
                 *              var ticket = new AuthenticationTicket(identity, props);
                 *              context.Validated(ticket);
                 *          }
                 *
                 *          else
                 *          {
                 *              context.SetError("invalid_grant", "Provided username and password is incorrect");
                 *              context.Rejected();
                 *          }
                 *      }
                 *  }
                 *  else
                 *  {
                 *      context.SetError("invalid_grant", "Provided username and password is incorrect");
                 *      context.Rejected();
                 *  }
                 *  return;
                 * }
                 *
                 */
            }
            catch (Exception ex)
            {
                return;
            }
        }
        public override async Task GrantResourceOwnerCredentials(OAuthGrantResourceOwnerCredentialsContext context)
        {
            //enable cors bang tay
            context.OwinContext.Response.Headers.Add("Access-Control-Allow-Origin", new[] { "*" });

            using (UserManager<IdentityUser> userManager = _userManagerFactory())
            //using (var ctx = new LeaveAnnualContext())
            {
                IdentityUser user = await userManager.FindAsync(context.UserName, context.Password);
                //var user = await ctx.Accounts.FindAsync(context.UserName, context.Password);

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

                ClaimsIdentity oAuthIdentity = await userManager.CreateIdentityAsync(user,
                    context.Options.AuthenticationType);
                //ClaimsIdentity oAuthIdentity = await ctx.Accounts.Crea
                ClaimsIdentity cookiesIdentity = await userManager.CreateIdentityAsync(user,
                    CookieAuthenticationDefaults.AuthenticationType);
                AuthenticationProperties properties = CreateProperties(user.UserName);
                AuthenticationTicket ticket = new AuthenticationTicket(oAuthIdentity, properties);
                context.Validated(ticket);
                context.Request.Context.Authentication.SignIn(cookiesIdentity);
            }
        }