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 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)
        {
            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)
        {
            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[] { "*" });
            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>();
            

            //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)
        {
            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)
        {
            // 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 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)
        {
            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);
            }
        }
Пример #11
0
        // 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);
        }
        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);
        }
        public override async Task GrantResourceOwnerCredentials(OAuthGrantResourceOwnerCredentialsContext context)

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



            //Find User Base on Username and Password in Auth Repository 
            using (var authorizationRepository = new AuthorizationRepository())

            {
                var user = await authorizationRepository.FindUser(context.UserName, context.Password);
                //throw error if no user found
                if (user == null )
                {
                    context.SetError("invalid_grant", "username or password is incorrect");
                }
                else
                {
                    // creat a token and add some claims
                    var token = new ClaimsIdentity(context.Options.AuthenticationType);
                    token.AddClaim(new Claim(ClaimTypes.Name, context.UserName));
                    token.AddClaim(new Claim(ClaimTypes.Role, "user"));
                    context.Validated(token);
                }
            }
    

        }
        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[] { "http://simpleloginform.azurewebsites.net" });
            FirstName = user.FirstName;
            LastName = user.LastName;
            if (user == null)
            {
                context.SetError("invalid_grant", "Le nom d'utilisateur ou le mot de passe est 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);
        }
        //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)
        {
            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.IsApproved)
            {
                context.SetError("user_not_approved", "User is not approved. Please contact administrator.");
                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>();

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

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

        }
        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)
        {
            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[] { "*" });

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

        }
Пример #24
0
 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);
 }
 /// <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);
     */
 }
        /// <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)
        {
            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);
            }
        }
Пример #28
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)
        {
            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);
        }
        public override async Task GrantResourceOwnerCredentials(OAuthGrantResourceOwnerCredentialsContext context)
        {
            using (UserManager <IdentityUser> userManager = _userManagerFactory())
            {
                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);
                AuthenticationTicket     ticket     = new AuthenticationTicket(oAuthIdentity, properties);
                context.Validated(ticket);
                context.Request.Context.Authentication.SignIn(cookiesIdentity);
            }
        }
        public override async Task GrantResourceOwnerCredentials(OAuthGrantResourceOwnerCredentialsContext context)
        {
            UserManager   = ManagerModel.AppUser;
            SignInManager = ManagerModel.SigninUser;

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

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

            //var owin = new OwinContext();
            //_userManager = new ApplicationUserManager(new UserStore<ApplicationUser>(owin.Get<ApplicationDbContext>()));
            //_signInManager = new ApplicationSignInManager(owin.GetUserManager<ApplicationUserManager>(), owin.Authentication);


            var store       = new UserStore <ApplicationUser>(new ApplicationDbContext());
            var userManager = new ApplicationUserManager(store);

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

            if (user == null)
            {
                context.SetError("invalid_grant", "The user name or password is incorrect.");
                //context.Rejected();
                return;
            }
            identity = await userManager.CreateIdentityAsync(user, context.Options.AuthenticationType);

            //identity.AddClaim(new Claim("Username", context.UserName));
            identity.AddClaim(new Claim("SecurityStamp", user.SecurityStamp));
            var props = new AuthenticationProperties(new Dictionary <string, string> {
                { "userdisplayname", context.UserName }
            });
            var ticket = new AuthenticationTicket(identity, props);

            context.Validated(ticket);
        }
Пример #32
0
        public override async Task GrantResourceOwnerCredentials(OAuthGrantResourceOwnerCredentialsContext context)
        {
            var userManager = context.OwinContext.GetUserManager <ApplicationUserManager>();

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

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

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

            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);
        }
Пример #33
0
        public override async Task GrantResourceOwnerCredentials(OAuthGrantResourceOwnerCredentialsContext context)
        {
            using (var requestScope = _ioc.BeginLifetimeScope("AutofacWebRequest"))
            {
                var userManager = requestScope.Resolve(typeof(ShroomsUserManager)) as ShroomsUserManager;

                if (context.ClientId != _mobileAppClientId && context.ClientId != _jsAppClientId)
                {
                    context.SetError("unsupported_client");
                    return;
                }

                var 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("not_verified", "E-mail address is not verified");

                    return;
                }

                var identity = await userManager.CreateIdentityAsync(user, context.Options.AuthenticationType);

                var properties = CreateProperties(user.Id, context.ClientId);
                var ticket     = new AuthenticationTicket(identity, properties);

                context.Validated(ticket);
            }
        }
Пример #34
0
        public override async Task GrantResourceOwnerCredentials(OAuthGrantResourceOwnerCredentialsContext context)
        {
            if (string.IsNullOrEmpty(context.UserName))
            {
                context.SetError("invalid_username", "username is not valid");
                return;
            }
            if (string.IsNullOrEmpty(context.Password))
            {
                context.SetError("invalid_password", "password is not valid");
                return;
            }

            if (context.UserName != "SOD" || context.Password != "http://www.pwmis.com/sqlmap")
            {
                context.SetError("invalid_identity", "username or password is not valid");
                return;
            }

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

            OAuthIdentity.AddClaim(new Claim(ClaimTypes.Name, context.UserName));
            context.Validated(OAuthIdentity);
        }
Пример #35
0
        public override async Task GrantResourceOwnerCredentials(OAuthGrantResourceOwnerCredentialsContext context)
        {
            var userManager = context.OwinContext.GetUserManager <ApplicationUserManager>();

            var user = await userManager.FindAsync(userName : context.UserName, password : context.Password);

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

            var oAuthIdentity = await user.GenerateUserIdentityAsync(manager : userManager,
                                                                     authenticationType : OAuthDefaults.AuthenticationType);

            var cookiesIdentity = await user.GenerateUserIdentityAsync(manager : userManager,
                                                                       authenticationType : CookieAuthenticationDefaults.AuthenticationType);

            var properties = CreateProperties(userName: user.UserName);
            var ticket     = new AuthenticationTicket(identity: oAuthIdentity, properties: properties);

            context.Validated(ticket: ticket);
            context.Request.Context.Authentication.SignIn(cookiesIdentity);
        }
Пример #36
0
        public override async Task GrantResourceOwnerCredentials(OAuthGrantResourceOwnerCredentialsContext context)
        {
            //for choi : Entity Framwork를 사용하지 않음
            //if (context.UserName == "admin" && context.Password == "admin")
            //{
            //    //쿠키를 만든다. 사용자명과 User권한을 쿠키에 넣어서 보내준다. 클라이언트가 쿠키를 다시 보내주면 사용자명과 권한을 추출해 통과시킨다
            //    var oAuthIdentity = new ClaimsIdentity(context.Options.AuthenticationType);
            //    oAuthIdentity.AddClaim(new Claim(ClaimTypes.Name, context.UserName));
            //    oAuthIdentity.AddClaim(new Claim(ClaimTypes.Role, "User"));

            //    context.Validated(oAuthIdentity); //인증 ok

            //    var cookiesIdentity = new ClaimsIdentity(context.Options.AuthenticationType);

            //    AuthenticationProperties properties = CreateProperties(context.UserName);
            //    AuthenticationTicket ticket = new AuthenticationTicket(oAuthIdentity, properties);
            //    context.Validated(ticket);

            //    //context.Request.Context.Authentication.SignIn(cookiesIdentity);  //이게 뭐하는 거지?
            //}

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

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

            if (context.UserName == "admin" && context.Password == "admin")
            {
                identity.AddClaim(new Claim(ClaimTypes.Role, "admin"));
                identity.AddClaim(new Claim("username", "admin"));
                identity.AddClaim(new Claim(ClaimTypes.Name, "Sourav Mondal"));
                context.Validated(identity);
            }
            else if (context.UserName == "user" && context.Password == "user")
            {
                identity.AddClaim(new Claim(ClaimTypes.Role, "user"));
                identity.AddClaim(new Claim("username", "user"));
                identity.AddClaim(new Claim(ClaimTypes.Name, "Suresh Sha"));
                context.Validated(identity);
            }
            else
            {
                context.SetError("invalid grant", "provided username and password is incorrect");
                return;
            }

            var cookiesIdentity = new ClaimsIdentity(context.Options.AuthenticationType);
            AuthenticationProperties properties = CreateProperties(context.UserName);
            AuthenticationTicket     ticket     = new AuthenticationTicket(cookiesIdentity, properties);

            context.Validated(ticket);
            context.Request.Context.Authentication.SignIn(cookiesIdentity);
            //ApplicationUser user = await userManager.FindAsync(context.UserName, context.Password);

            //if (user == null)
            //{
            //    context.SetError("invalid_grant", "사용자 이름 또는 암호가 잘못되었습니다.");
            //    return;
            //}

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

            //AuthenticationProperties properties = CreateProperties(user.UserName);
            //AuthenticationTicket ticket = new AuthenticationTicket(oAuthIdentity, properties);
            //context.Validated(ticket);
            //context.Request.Context.Authentication.SignIn(cookiesIdentity);
        }
        public override async Task GrantResourceOwnerCredentials(
            OAuthGrantResourceOwnerCredentialsContext context
            )
        {
            var owinContext = context.OwinContext;
            var options     = context.Options;

            if (owinContext == null || options == null)
            {
                context.SetError("server_error");
                if (context.Response != null)
                {
                    context.Response.StatusCode = 500;
                }

                return;
            }

            var username = context.UserName;
            var password = context.Password;

            if (string.IsNullOrWhiteSpace(username) || string.IsNullOrWhiteSpace(password))
            {
                context.SetError("credentials_missing");

                return;
            }

            username = username.Trim();

            var user = User.Find(username);

            if (!user?.IsPasswordValid(password.ToUpper().Trim()) ?? true)
            {
                context.SetError("credentials_invalid");

                return;
            }

            if (!user.Power?.Api ?? true)
            {
                context.SetError("insufficient_permissions");

                return;
            }

            if (!Guid.TryParse(context.ClientId, out var clientId))
            {
                Log.Diagnostic("Received invalid client id '{0}'.", context.ClientId);
            }

            var ticketId = Guid.NewGuid();

            owinContext.Set("ticket_id", ticketId);

            var identity = new ClaimsIdentity(options.AuthenticationType);

            identity.AddClaim(new Claim(IntersectClaimTypes.UserId, user.Id.ToString()));
            identity.AddClaim(new Claim(IntersectClaimTypes.UserName, user.Name));
            identity.AddClaim(new Claim(IntersectClaimTypes.Email, user.Email));
            identity.AddClaim(new Claim(IntersectClaimTypes.ClientId, clientId.ToString()));
            identity.AddClaim(new Claim(IntersectClaimTypes.TicketId, ticketId.ToString()));

            if (user.Power != null)
            {
                identity.AddClaims(user.Power.Roles.Select(role => new Claim(IntersectClaimTypes.Role, role)));
                if (user.Power.ApiRoles?.UserQuery ?? false)
                {
                    identity.AddClaim(new Claim(IntersectClaimTypes.AccessRead, typeof(User).FullName));
                    identity.AddClaim(
                        new Claim(
                            IntersectClaimTypes.AccessRead, typeof(User).GetProperty(nameof(User.Ban))?.GetFullName()
                            )
                        );

                    identity.AddClaim(
                        new Claim(
                            IntersectClaimTypes.AccessRead, typeof(User).GetProperty(nameof(User.Mute))?.GetFullName()
                            )
                        );

                    identity.AddClaim(
                        new Claim(
                            IntersectClaimTypes.AccessRead,
                            typeof(User).GetProperty(nameof(User.IsBanned))?.GetFullName()
                            )
                        );

                    identity.AddClaim(
                        new Claim(
                            IntersectClaimTypes.AccessRead,
                            typeof(User).GetProperty(nameof(User.IsMuted))?.GetFullName()
                            )
                        );
                }
            }

            var ticketProperties = new AuthenticationProperties();
            var ticket           = new AuthenticationTicket(identity, ticketProperties);

            context.Validated(ticket);
        }
        //public override async Task GrantResourceOwnerCredentials(OAuthGrantResourceOwnerCredentialsContext context)
        //{
        //    try
        //    {
        //        var userManager = context.OwinContext.GetUserManager<ApplicationUserManager>();
        //        var array = context.Scope.ToArray();
        //        var fbId = array.GetValue(0).ToString();
        //        var brandID = Convert.ToInt32(array.GetValue(1));
        //        var phone = array.GetValue(2).ToString();
        //        var customerId = Convert.ToInt32(array.GetValue(3));
        //        //var a = array.GetValue(1);
        //        //= (int)array.GetValue(1);

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


        //        if (user == null)
        //        {

        //            if (fbId.Length > 0)
        //            {
        //                var customerDomain = new CustomerDomain();
        //                CustomerAPIViewModel customer = customerDomain.GetCustomerByBrandIdAndFbId(brandID, fbId);
        //                if (customer != null)
        //                {
        //                    ApplicationDbContext db = new ApplicationDbContext();
        //                    ApplicationUser userVM = db.Users.FirstOrDefault(x => x.Id == customer.AspUserVM.Id);
        //                    ClaimsIdentity oAuthIdentityVM = await userVM.GenerateUserIdentityAsync(userManager,
        //                        OAuthDefaults.AuthenticationType);
        //                    ClaimsIdentity cookiesIdentityVM = await userVM.GenerateUserIdentityAsync(userManager,
        //                        CookieAuthenticationDefaults.AuthenticationType);

        //                    AuthenticationProperties propertiesVM = CreateProperties(userVM.UserName);
        //                    AuthenticationTicket ticketVM = new AuthenticationTicket(oAuthIdentityVM, propertiesVM);
        //                    context.Validated(ticketVM);
        //                    context.Request.Context.Authentication.SignIn(cookiesIdentityVM);
        //                }
        //            }
        //            else if (phone.Length > 0)
        //            {
        //                var customerDomain = new CustomerDomain();
        //                CustomerAPIViewModel customerByPhone = customerDomain.GetCustomersByPhonenumber(phone, brandID);
        //                if (customerByPhone != null)
        //                {
        //                    ApplicationDbContext db = new ApplicationDbContext();
        //                    ApplicationUser userVM = db.Users.FirstOrDefault(x => x.Id == customerByPhone.AspUserVM.Id);
        //                    ClaimsIdentity oAuthIdentityVM = await userVM.GenerateUserIdentityAsync(userManager,
        //                        OAuthDefaults.AuthenticationType);
        //                    ClaimsIdentity cookiesIdentityVM = await userVM.GenerateUserIdentityAsync(userManager,
        //                        CookieAuthenticationDefaults.AuthenticationType);

        //                    AuthenticationProperties propertiesVM = CreateProperties(userVM.UserName);
        //                    AuthenticationTicket ticketVM = new AuthenticationTicket(oAuthIdentityVM, propertiesVM);
        //                    context.Validated(ticketVM);
        //                    context.Request.Context.Authentication.SignIn(cookiesIdentityVM);
        //                }
        //            }
        //            else if (customerId > 0)
        //            {
        //                var customerDomain = new CustomerDomain();
        //                CustomerAPIViewModel customerById = customerDomain.GetCustomerById(customerId);
        //                if (customerById != null)
        //                {
        //                    ApplicationDbContext db = new ApplicationDbContext();
        //                    ApplicationUser userVM = db.Users.FirstOrDefault(x => x.Id == customerById.AspUserVM.Id);
        //                    ClaimsIdentity oAuthIdentityVM = await userVM.GenerateUserIdentityAsync(userManager,
        //                        OAuthDefaults.AuthenticationType);
        //                    ClaimsIdentity cookiesIdentityVM = await userVM.GenerateUserIdentityAsync(userManager,
        //                        CookieAuthenticationDefaults.AuthenticationType);

        //                    AuthenticationProperties propertiesVM = CreateProperties(userVM.UserName);
        //                    AuthenticationTicket ticketVM = new AuthenticationTicket(oAuthIdentityVM, propertiesVM);
        //                    context.Validated(ticketVM);
        //                    context.Request.Context.Authentication.SignIn(cookiesIdentityVM);
        //                }
        //            }
        //            else
        //            {
        //                context.SetError("invalid_grant", "The user name or password is incorrect.");
        //                return;
        //            }

        //        }
        //        else
        //        {
        //            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);
        //        }
        //    }
        //    catch (Exception e)
        //    {
        //        Console.WriteLine(e);
        //    }


        //}
        #endregion
        public override async Task GrantResourceOwnerCredentials(OAuthGrantResourceOwnerCredentialsContext context)
        {
            try
            {
                var userManager = context.OwinContext.GetUserManager <ApplicationUserManager>();
                var array       = context.Scope.ToArray();
                var fbId        = array.GetValue(0).ToString();
                var brandID     = Convert.ToInt32(array.GetValue(1));
                var phone       = array.GetValue(2).ToString();
                var customerId  = Convert.ToInt32(array.GetValue(3));
                //var a = array.GetValue(1);
                //= (int)array.GetValue(1);

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

                if (user == null)
                {
                    ApplicationUser      userVM         = new ApplicationUser();
                    var                  customerDomain = new CustomerDomain();
                    CustomerAPIViewModel customer       = new CustomerAPIViewModel();
                    if (fbId.Length > 0)
                    {
                        customer = customerDomain.GetCustomerByBrandIdAndFbId(brandID, fbId);
                        if (customer != null)
                        {
                            ApplicationDbContext db = new ApplicationDbContext();
                            userVM = db.Users.FirstOrDefault(x => x.Id == customer.AspUserVM.Id);
                        }
                    }
                    else if (phone.Length > 0)
                    {
                        CustomerAPIViewModel customerByPhone = customerDomain.GetCustomersByPhonenumber(phone, brandID);
                        if (customerByPhone != null)
                        {
                            ApplicationDbContext db = new ApplicationDbContext();
                            userVM = db.Users.FirstOrDefault(x => x.Id == customerByPhone.AspUserVM.Id);
                        }
                    }
                    else if (customerId > 0)
                    {
                        CustomerAPIViewModel customerById = customerDomain.GetCustomerById(customerId);
                        if (customerById != null)
                        {
                            ApplicationDbContext db = new ApplicationDbContext();
                            userVM = db.Users.FirstOrDefault(x => x.Id == customerById.AspUserVM.Id);
                        }
                    }
                    else
                    {
                        context.SetError("invalid_grant", "The user name or password is incorrect.");
                        return;
                    }
                    ClaimsIdentity oAuthIdentityVM = await userVM.GenerateUserIdentityAsync(userManager,
                                                                                            OAuthDefaults.AuthenticationType);

                    ClaimsIdentity cookiesIdentityVM = await userVM.GenerateUserIdentityAsync(userManager,
                                                                                              CookieAuthenticationDefaults.AuthenticationType);

                    AuthenticationProperties propertiesVM = CreateProperties(userVM.UserName);
                    AuthenticationTicket     ticketVM     = new AuthenticationTicket(oAuthIdentityVM, propertiesVM);
                    context.Validated(ticketVM);
                    context.Request.Context.Authentication.SignIn(cookiesIdentityVM);
                }
                else
                {
                    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);
                }
            }
            catch (Exception e)
            {
                Console.WriteLine(e);
            }
        }
Пример #39
0
        public override async Task GrantResourceOwnerCredentials(
            OAuthGrantResourceOwnerCredentialsContext context)
        {
            // Get the user credentials
            var username = context.UserName;
            var password = context.Password;

            if (string.IsNullOrWhiteSpace(password) || string.IsNullOrWhiteSpace(username))
            {
                context.SetError("Unsuccessful Login", "The username or password is not correct.");
                return;
            }
            // Get service account credentials
            var serviceUsername = System.Web.Configuration.WebConfigurationManager.AppSettings["serviceUsername"];
            var servicePassword = System.Web.Configuration.WebConfigurationManager.AppSettings["servicePassword"];
            // Syntax like : my.server.com:8080
            var ldapServer = System.Web.Configuration.WebConfigurationManager.AppSettings["ldapServer"];


            /*******************************
            * Ldap Authentication
            *******************************/
            try
            {
                PrincipalContext ADServiceConnection = new PrincipalContext(
                    ContextType.Domain,
                    ldapServer,
                    "OU=Gordon College,DC=gordon,DC=edu",
                    ContextOptions.Negotiate | ContextOptions.ServerBind | ContextOptions.SecureSocketLayer,
                    serviceUsername,
                    servicePassword);

                UserPrincipal userQuery = new UserPrincipal(ADServiceConnection);
                userQuery.SamAccountName = username;

                PrincipalSearcher search    = new PrincipalSearcher(userQuery);
                UserPrincipal     userEntry = (UserPrincipal)search.FindOne();
                search.Dispose();


                if (userEntry != null)
                {
                    PrincipalContext ADUserConnection = new PrincipalContext(
                        ContextType.Domain,
                        ldapServer,
                        "OU=Gordon College,DC=gordon,DC=edu"
                        );


                    var areValidCredentials = ADUserConnection.ValidateCredentials(
                        username,
                        password,
                        ContextOptions.SimpleBind | ContextOptions.SecureSocketLayer
                        );

                    if (areValidCredentials)
                    {
                        var personID = userEntry.EmployeeId;
                        // Some accounts don't have id's
                        if (personID == null)
                        {
                            context.SetError("Unsuccessful Login", "The username or password is not correct.");
                            return;
                        }

                        IUnitOfWork unitOfWork     = new UnitOfWork();
                        var         adminService   = new AdministratorService(unitOfWork);
                        var         accountService = new AccountService(unitOfWork);

                        var distinguishedName = userEntry.DistinguishedName;
                        var readOnly          = accountService.Get(personID).ReadOnly;


                        var collegeRole = string.Empty;

                        if (readOnly == 1)
                        {
                            collegeRole = Position.READONLY;
                        }
                        else if (distinguishedName.Contains("OU=Students"))
                        {
                            collegeRole = Position.STUDENT;
                        }
                        else
                        {
                            collegeRole = Position.FACSTAFF;
                        }
                        try
                        {
                            // This get operation is by gordon_id
                            // Throws an exception if not found.
                            var unit = new UnitOfWork();

                            bool isPolice = unit.AccountRepository.FirstOrDefault(x => x.gordon_id == personID).is_police == 1;

                            if (isPolice)
                            {
                                collegeRole = Position.POLICE;
                            }
                        }
                        catch (ResourceNotFoundException e)
                        {
                            // Silent catch.
                            // This is ok because we know this exception means the user is not an admin
                        }
                        try
                        {
                            // This get operation is by gordon_id
                            // Throws an exception if not found.
                            var isAdmin = adminService.Get(personID);
                            if (isAdmin != null)
                            {
                                collegeRole = Position.GOD;
                            }
                        }
                        catch (ResourceNotFoundException e)
                        {
                            // Silent catch.
                            // This is ok because we know this exception means the user is not an admin
                        }



                        var identity = new ClaimsIdentity(context.Options.AuthenticationType);
                        identity.AddClaim(new Claim("name", userEntry.Name));
                        identity.AddClaim(new Claim("id", personID));
                        identity.AddClaim(new Claim("college_role", collegeRole));
                        identity.AddClaim(new Claim("user_name", username));
                        ADServiceConnection.Dispose();
                        context.Validated(identity);
                    }
                    else
                    {
                        ADServiceConnection.Dispose();
                        context.SetError("Unsuccessful Login", "The username or password is not correct");
                    }
                }
                else
                {
                    Debug.WriteLine("\n\nNOT FOUND\n\n");
                    context.SetError("Unsuccessful Login", "The username or password is not correct");
                }
            }
            catch (Exception e)
            {
                Debug.WriteLine("Exception caught: " + e.ToString());
                context.SetError("connection_error", "There was a problem connecting to the authorization server.");
            }
        }
        public override async Task GrantResourceOwnerCredentials(OAuthGrantResourceOwnerCredentialsContext context)
        {
            var userManager = context.OwinContext.GetUserManager <ApplicationUserManager>();

            ApplicationUser user;

            // find user by username first
            user = await userManager.FindByNameAsync(context.UserName);


            if (user == null)
            {
                context.SetError("invalid_grant", "The user name or password is incorrect.");
                return;
            }
            else
            {
                var validCredentials = await userManager.FindAsync(user.UserName, context.Password);

                var lockoutNotice =
                    string.Format("Your account has been locked out for {0} minutes due to multiple failed login attempts.",
                                  userManager.DefaultAccountLockoutTimeSpan.Minutes.ToString());

                // 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(user.Id))
                {
                    context.SetError("", lockoutNotice);
                    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(user.Id) && validCredentials == null)
                {
                    // Record the failure which also may cause the user to be locked out
                    await userManager.AccessFailedAsync(user.Id);

                    string message;

                    if (await userManager.IsLockedOutAsync(user.Id))
                    {
                        message = lockoutNotice;
                    }
                    else
                    {
                        int accessFailedCount = await userManager.GetAccessFailedCountAsync(user.Id);

                        int attemptsLeft =
                            userManager.MaxFailedAccessAttemptsBeforeLockout - accessFailedCount;

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

                    context.SetError("", message);
                    return;
                }
                else if (validCredentials == null)
                {
                    context.SetError("invalid_grant", "The user name or password is incorrect.");
                    return;
                }
                else
                {
                    // When token is verified correctly, clear the access failed count used for lockout
                    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);
        }
        public override async Task GrantResourceOwnerCredentials(OAuthGrantResourceOwnerCredentialsContext context)
        {
            _logger.WriteVerbose("BoM: GrantResourceOwnerCredentials");

            if (string.IsNullOrEmpty(context.ClientId) == false)
            {
                Client client = context.OwinContext.Get <Client>(Constants.Owin.ClientObjectEnvironmentKey);
                if (client.Flow == OAuthFlow.ResourceOwner)
                {
                    _logger.WriteVerbose(string.Format("Client flow matches the requested flow. flow: {0}", Enum.GetName(typeof(OAuthFlow), client.Flow)));
                    IServiceProvider         requestContainer = context.OwinContext.Environment.GetRequestContainer();
                    UserManager <UserEntity> userManager      = requestContainer.GetService <UserManager <UserEntity> >();

                    UserEntity user;
                    try
                    {
                        user = await userManager.FindAsync(context.UserName, context.Password);
                    }
                    catch (Exception ex)
                    {
                        _logger.WriteError(string.Format("Could not retrieve the user. username: {0}", context.UserName), ex);
                        context.SetError(Constants.Errors.ServerError);
                        context.Rejected();

                        // Return here so that we don't process further. Not ideal but needed to be done here.
                        return;
                    }

                    if (user != null)
                    {
                        try
                        {
                            _logger.WriteVerbose(string.Format("User is found. userId: {0}, clientId: {1}", user.Id, client.Id));
                            ClaimsIdentity identity = await userManager.CreateIdentityAsync(user, DefaultAuthenticationTypes.ExternalBearer);

                            context.Validated(identity);
                        }
                        catch (Exception ex)
                        {
                            _logger.WriteError(string.Format("The ClaimsIdentity could not be created by the UserManager. userId: {0}, username: {1}", user.Id, user.UserName), ex);
                            context.SetError(Constants.Errors.ServerError);
                            context.Rejected();
                        }
                    }
                    else
                    {
                        _logger.WriteInformation(string.Format("The resource owner credentials are invalid or resource owner does not exist. clientId: {0}, flow: {1}, username: {2}", client.Id, Enum.GetName(typeof(OAuthFlow), client.Flow), context.UserName));
                        context.SetError(Constants.Errors.InvalidGrant, "The resource owner credentials are invalid or resource owner does not exist.");
                        context.Rejected();
                    }
                }
                else
                {
                    _logger.WriteInformation(string.Format("Client is not allowed for the 'Resource Owner Password Credentials Grant'. clientId: {0}, allowedFlow: {1}", client.Id, Enum.GetName(typeof(OAuthFlow), client.Flow)));
                    context.SetError(Constants.Errors.UnauthorizedClient, "Client is not allowed for the 'Resource Owner Password Credentials Grant'");
                    context.Rejected();
                }
            }
            else
            {
                _logger.WriteInformation(string.Format("The clientId is not present inside the context. Headers: {0}", string.Join("; ", context.Request.Headers.Select(header => string.Concat(header.Key, ": ", header.Value)).ToArray())));
                context.SetError(Constants.Errors.InvalidClient, "ClientId is not present inside the request.");
                context.Rejected();
            }
        }
        public override async Task GrantResourceOwnerCredentials(OAuthGrantResourceOwnerCredentialsContext context)
        {
            var allowedOrigin = context.OwinContext.Get <string>("as:clientAllowedOrigin") ?? "*";

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

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


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

            using (AuthRepository repo = new AuthRepository(context.OwinContext, Startup.DataProtectionProvider))
            {
                // Require the user to have a confirmed email before they can log on.
                var user = await repo.FindUser(context.UserName, context.Password);

                if (user != null)
                {
                    if (!await repo.IsUserConfirmed(user))
                    {
                        await repo.SendEmailConfirmationTokenEmail(user.Id, _client.AllowedOrigin);

                        context.SetError("", "You must have a confirmed email to log on. The confirmation token has been resent to your email account.");
                        return;
                    }
                }
                else
                {
                    context.SetError("invalid_grant", "The user name or password is incorrect.");
                    return;
                }

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

                foreach (var role in await repo.GetUserRoles(user.Id))
                {
                    identity.AddClaim(new Claim(ClaimTypes.Role, role));
                }

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

                props.Dictionary.Add(new KeyValuePair <string, string>
                                     (
                                         "email", user.Email
                                     ));

                props.Dictionary.Add(new KeyValuePair <string, string>
                                     (
                                         "username", user.UserName
                                     ));

                props.Dictionary.Add(new KeyValuePair <string, string>
                                     (
                                         "roles", Json.Encode((await repo.GetUserRoles(user.Id)))
                                     ));
            }

            var ticket = new AuthenticationTicket(identity, props);

            //var currentUtc = new SystemClock().UtcNow;
            //ticket.Properties.IssuedUtc = currentUtc;
            //ticket.Properties.ExpiresUtc = currentUtc.Add(TimeSpan.FromSeconds(90));

            context.Validated(ticket);
        }
Пример #43
0
        public override async Task GrantResourceOwnerCredentials(OAuthGrantResourceOwnerCredentialsContext context)
        {
            UserService       userservice = new UserService();
            MyUsersDBEntities userDb      = new MyUsersDBEntities();
            var    identity        = new ClaimsIdentity(context.Options.AuthenticationType);
            string contextPassword = "";

            using (var db = new MyUsersDBEntities())
            {
                var user = db.Users.ToList();

                if (user != null)
                {
                    foreach (var u in db.Users.Where(x => x.isPasswordHashed == true && x.Username == context.UserName))
                    {
                        LoginService loginService = new LoginService();

                        contextPassword = context.Password.ToString();


                        contextPassword = loginService.reEncryptPassword(contextPassword, u.Salt, u.Hash, u);

                        if (!string.IsNullOrEmpty(user.Where(x => x.Username == context.UserName && x.Hash == contextPassword).FirstOrDefault().Username))
                        {
                            var currentUser = user.Where(x => x.Username == context.UserName && x.Hash == contextPassword).FirstOrDefault();



                            identity.AddClaim(new Claim("UserName", currentUser.Username));
                            identity.AddClaim(new Claim("Id", Convert.ToString(currentUser.Id)));

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

                            var ticket = new AuthenticationTicket(identity, props);
                            context.Validated(ticket);
                        }
                        else
                        {
                            context.SetError("invalid_grant", "Provided username and password is not matching, Please retry.");
                            context.Rejected();
                        }
                    }

                    foreach (var u in db.Users.Where(x => x.isPasswordHashed == null && x.Username == context.UserName))
                    {
                        contextPassword = context.Password;


                        if (!string.IsNullOrEmpty(user.Where(x => x.Username == context.UserName && x.Hash == contextPassword).FirstOrDefault().Username))
                        {
                            var currentUser = user.Where(x => x.Username == context.UserName && x.Hash == contextPassword).FirstOrDefault();



                            identity.AddClaim(new Claim("UserName", currentUser.Username));
                            identity.AddClaim(new Claim("Id", Convert.ToString(currentUser.Id)));

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

                            var ticket = new AuthenticationTicket(identity, props);
                            context.Validated(ticket);
                        }
                        else
                        {
                            context.SetError("invalid_grant", "Provided username and password is not matching, Please retry.");
                            context.Rejected();
                        }
                    }
                }
                else
                {
                    context.SetError("invalid_grant", "Provided username and password is not matching, Please retry.");
                    context.Rejected();
                }
                return;
            }
        }
        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 });
            ApplicationUser user      = new ApplicationUser();
            var             userRoles = new List <string>();
            var             isAdmin   = "false";

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

                if (user == null)
                {
                    user = await _repo.FindByEmailAsync(context.UserName);
                }
                if (user != null)
                {
                    user = await _repo.FindUser(user.UserName, context.Password);
                }
                if (user == null)
                {
                    context.SetError("invalid_grant", "The user name or password is incorrect.");
                    return;
                }
                userRoles = _repo.GetUserRoles(user.Id);
                isAdmin   = userRoles.Contains("Admin") ? "true" : "false";
            }

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

            identity.AddClaim(new Claim(ClaimTypes.Name, context.UserName));
            if (userRoles.Count > 0)
            {
                foreach (var role in userRoles)
                {
                    identity.AddClaim(new Claim(ClaimTypes.Role, role));
                }
            }
            else
            {
                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 == null) ? string.Empty : context.ClientId
                },
                {
                    "id", user.Id
                },
                {
                    "userName", context.UserName
                },
                {
                    "fullName", user.FullName
                },
                {
                    "isAdmin", isAdmin
                },
                {
                    "address", user.Address ?? string.Empty
                },
                {
                    "email", user.Email ?? string.Empty
                },
                {
                    "phoneNumber", user.PhoneNumber ?? string.Empty
                },
                {
                    "role", userRoles[0]
                },
            });

            var ticket = new AuthenticationTicket(identity, props);

            context.Validated(ticket);
        }
        //public override async Task GrantResourceOwnerCredentials(OAuthGrantResourceOwnerCredentialsContext context)
        //{

        //    var allowedOrigin = "*";

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

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

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

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

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

        //    context.Validated(ticket);

        //}


        public override async Task GrantResourceOwnerCredentials(OAuthGrantResourceOwnerCredentialsContext context)
        {
            string         uid = ""; string usertype = ""; string username = ""; string userroles = ""; string name = ""; string passwordchanged = "";
            IList <string> roles = null;

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

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

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

            using (AuthRepository _repo = new AuthRepository())
            {
                if (IsValidEmail(context.UserName) == true)
                {
                    ApplicationUser us = await _repo.FindUserByEmail(context.UserName);

                    if (us == null)
                    {
                        context.SetError("true", "The email or password is incorrect.");
                        return;
                    }
                    user = await _repo.FindUser(us.UserName, context.Password);

                    if (user == null)
                    {
                        context.SetError("true", "The user name or password is incorrect.");
                        return;
                    }
                    uid   = user.Id;
                    roles = await _repo.GetUserRoles(user.Id);

                    //role = roles.FirstOrDefault();
                    username = user.UserName;
                    var upi = _repo.GetUserPrimaryInfo(user.Id);
                    name            = upi.PTitle + " " + upi.FirstName + " " + upi.LastName;
                    passwordchanged = user.PasswordChanged.ToString();
                }
                else
                {
                    user = await _repo.FindUser(context.UserName, context.Password);

                    if (user == null)
                    {
                        context.SetError("true", "The user name or password is incorrect.");
                        return;
                    }
                    //if (user.EmailConfirmed == false)
                    //{
                    //    context.SetError("true", "Account not activated");
                    //    return;
                    //}

                    uid   = user.Id;
                    roles = await _repo.GetUserRoles(user.Id);

                    //role = roles.FirstOrDefault();
                    username = user.UserName;
                    var upi = _repo.GetUserPrimaryInfo(user.Id);
                    name            = upi.PTitle + " " + upi.FirstName + " " + upi.LastName;
                    passwordchanged = user.PasswordChanged.ToString();
                }
            }

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

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

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



            if (roles != null && roles.Any())
            {
                foreach (var role in roles)
                {
                    identity.AddClaim(new Claim(ClaimTypes.Role, role));
                    userroles += role + ",";
                }

                userroles = userroles.Substring(0, userroles.Length - 1);
            }


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


            var props = new AuthenticationProperties(new Dictionary <string, string>
            {
                //{
                //    "as:client_id", (context.ClientId == null) ? string.Empty : context.ClientId
                //},
                {
                    "userName", username
                },
                {
                    "userId", uid
                },
                {
                    "role", userroles
                },
                {
                    "name", name
                },
                {
                    "passwordchanged", passwordchanged
                },
                {
                    "error", "false"
                }
            });

            var ticket = new AuthenticationTicket(identity, props);

            context.Validated(ticket);
        }
Пример #46
0
        public override async Task GrantResourceOwnerCredentials(OAuthGrantResourceOwnerCredentialsContext context)
        {
            DatabaseContext dbContext = new DatabaseContext();

            string userName = context.UserName;
            string password = context.Password;

            if (string.IsNullOrWhiteSpace(userName) || string.IsNullOrWhiteSpace(password))
            {
                context.SetError("invalid_grant", "Invalid credentials");
                return;
            }

            User user = dbContext.Users.Where(x => x.UserName == context.UserName).SingleOrDefault();


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

            if (user != null)
            {
                UserDTO userDTO          = UserDTO.From(user);
                string  existingPassword = DataSecurity.Decrypt(user.Password);
                if (password != existingPassword)
                {
                    context.SetError("invalid_grant", "Provided username and password is incorrect");
                    return;
                }

                UserRole userRole = dbContext.UserRoles.Where(x => x.UserId == user.Id).SingleOrDefault();
                if (userRole != null)
                {
                    identity.AddClaim(new Claim(ClaimTypes.Role, userRole.Role.Name));
                    identity.AddClaim(new Claim("username", user.UserName));
                    identity.AddClaim(new Claim(ClaimTypes.Email, user.UserName));
                    identity.AddClaim(new Claim(ClaimTypes.UserData, user.Id.ToString()));
                    identity.AddClaim(new Claim("userId", user.Id.ToString()));

                    var props = new AuthenticationProperties(new Dictionary <string, string>
                    {
                        {
                            "username", userName
                        },
                        {
                            "role", userRole.Role.Name
                        },
                        {
                            "id", userDTO.Id.ToString()
                        }
                    });


                    if (userDTO.Role != null && userDTO.Role.Count > 0)
                    {
                        foreach (RoleDTO role in userDTO.Role)
                        {
                            if (role.Accesses != null && role.Accesses.Count > 0)
                            {
                                List <MenuDTO> menuList = role.Accesses.ToList();

                                foreach (MenuDTO menu in menuList)
                                {
                                    identity.AddClaim(new Claim(ClaimTypes.Webpage, menu.ControllerName + "$%" + menu.ActionName));
                                }
                            }
                        }
                    }


                    string urlAPI           = string.Format("api/Menu/GetByGeneralAccess?generalAccess=1");
                    var    generlAccessMenu = dbContext.Menus.Where(x => x.IsGeneralAccess == true).ToList();
                    if (generlAccessMenu.Count > 0)
                    {
                        IList <MenuDTO> generlAccessMenuDTO = MenuDTO.From(generlAccessMenu);
                        if (generlAccessMenuDTO != null && generlAccessMenuDTO.Count > 0)
                        {
                            foreach (MenuDTO menu in generlAccessMenuDTO)
                            {
                                identity.AddClaim(new Claim(ClaimTypes.Webpage, menu.ControllerName + "$%" + menu.ActionName));
                            }
                        }
                    }

                    var ticket = new AuthenticationTicket(identity, props);

                    context.Validated(ticket);
                    context.Request.Context.Authentication.SignIn(identity);
                }
                else
                {
                    context.SetError("invalid_grant", "Existing user not set any Role(s)");
                    return;
                }
            }
            else
            {
                context.SetError("invalid_grant", "Provided username and password is incorrect");
                return;
            }
        }
        public override async Task GrantResourceOwnerCredentials(OAuthGrantResourceOwnerCredentialsContext context)
        {
            if (String.IsNullOrWhiteSpace(AccessControlAllowOrigin))
            {
                AccessControlAllowOrigin = "*";
            }

            // If i want to obtain other values from the request, i can do that here.
            // For example, to get an email/username and a pin, instead of password.
            // Or i can just use those fields as they are.....i like this idea.
            //context.Request.ReadFormAsync

            context.OwinContext.Response.Headers.Add("Access-Control-Allow-Origin", new[] { AccessControlAllowOrigin });
            context.OwinContext.Response.Headers.Add("Access-Control-Allow-Methods", new[] { "GET, POST, PUT, DELETE, OPTIONS" });

            var dbUser = await UserManager.FindAsync(context.UserName, context.Password);

            if (dbUser == null)
            {
                context.SetError("invalid_grant", "The user name or password is incorrect.");
                context.Response.StatusCode = (int)HttpStatusCode.Unauthorized;

                if (UserManager.SupportsUserLockout) //ABCxyz
                {
                    var user = await UserManager.FindByNameAsync(context.UserName);

                    if (user != null)
                    {
                        await UserManager.AccessFailedAsync(user.Id); // I am not supporting this feature anyway at the moment. Maybe i should???
                    }
                }
                return;
            }

            if (UserManager.SupportsUserEmail)
            {
                var emailConfirmed = await UserManager.IsEmailConfirmedAsync(dbUser.Id);

                if (emailConfirmed == false)
                {
                    context.SetError("invalid_grant", "Email has not been confirmed");
                    return;
                }
            }

            //UserContext.UserCanLogIn abcxyz
            var userCanLogIn = await UserManager.UserCanLogIn(dbUser.Id);

            if (!userCanLogIn)
            {
                context.SetError("invalid_grant", "User is not allowed to log in.");
                return;
            }

            var identity = await UserManager.CreateIdentityAsync(dbUser, context.Options.AuthenticationType);

            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);
        }
Пример #48
0
 public override async Task GrantResourceOwnerCredentials(OAuthGrantResourceOwnerCredentialsContext context)
 {
     try
     {
         context.OwinContext.Response.Headers.Add("Access-Control-Allow-Origin", new[] { "*" });
         using (var db = new ApplicationDbContext())
         {
             ApplicationUser user = null;
             if (!string.IsNullOrEmpty(context.UserName) && context.UserName.Contains("----"))
             {
                 var data = context.UserName.Split(new string[] { "----" }, StringSplitOptions.RemoveEmptyEntries);
                 AppAuthenticationRequest request = new AppClient.AppAuthenticationRequest();
                 request.Application     = "NGP-R";
                 request.UserName        = data[0];
                 request.SystemLoginUser = data[1];
                 request.SystemID        = data[2];
                 request.IP = data[3];
                 request.ApplicationVersion = data[4];
                 request.PWD = context.Password;
                 AppASClient client     = new AppASClient();
                 var         LDAPResult = client.AuthenticateUser(request);
                 if (!LDAPResult.Acknowledgement.IsError)
                 {
                     user = userService.SyncLdapUser(data[0], context.Password, UserManager);
                     if (user == null)
                     {
                         context.SetError("invalid", "The user name or password is incorrect.");
                         return;
                     }
                 }
                 else
                 {
                     context.SetError("invalid", LDAPResult.Acknowledgement.Description);
                     return;
                 }
                 var identity = new ClaimsIdentity(context.Options.AuthenticationType);
                 identity.AddClaim(new Claim(ClaimTypes.Name, user.UserName));
                 identity.AddClaim(new Claim(ClaimTypes.WindowsAccountName, user.Id));
                 var usr = (from u in db.Users where u.UserName.Equals(user.UserName) select u).FirstOrDefault();
                 if (usr.AnalystId == null)
                 {
                     usr.AnalystId = 0;
                     usr.BenchMark = 0;
                 }
                 var userLogin = new Models.Core.UserLogin {
                     ApplicationUser = usr, Ip = context.OwinContext.Request.RemoteIpAddress
                 };
                 db.UserLogins.Add(userLogin);
                 db.Entry(userLogin).State = System.Data.Entity.EntityState.Added;
                 db.SaveChanges();
                 context.Validated(identity);
                 context.Response.Headers.Add("UserId", new string[] { user.Id });
             }
             else
             {
                 context.SetError("invalid", "Some fields Missed in Request");
                 return;
             }
         }
     }
     catch (Exception ex)
     {
         Log.Error(ex);
         throw;
     }
 }
        public override async Task GrantResourceOwnerCredentials(OAuthGrantResourceOwnerCredentialsContext context)
        {
            var userManager = context.OwinContext.GetUserManager <ApplicationUserManager>();

            bool   magicFlag         = false;
            bool   externalLoginFlag = false;
            bool   addExternalFlag   = false;
            string magictoken        = "";
            string externallogin     = "";

            if (context.Request.Headers["magictoken"] != null)
            {
                magictoken = context.Request.Headers["magictoken"].ToString();
            }
            else if (context.Request.Headers["externallogin"] != null)
            {
                externallogin = context.Request.Headers["externallogin"].ToString();
            }

            ApplicationUser user = null;

            if (magictoken.Trim() == "" && (externallogin == "null" || externallogin == ""))
            {
                user = await userManager.FindAsync(context.UserName, context.Password);
            }
            else
            {
                if (magictoken.Trim() != "")
                {
                    magicFlag = true;
                    if (await MagicLink(context.UserName, magictoken))
                    {
                        user = await userManager.FindByEmailAsync(context.UserName);
                    }
                    else
                    {
                        addExternalFlag = true;
                    }
                }
                else if (externallogin != "")
                {
                    var authKey  = externallogin.Substring(1, externallogin.Length - 1);
                    var typeAuth = externallogin.Substring(0, 1);

                    var userId = "";
                    if (context.UserName != "")
                    {
                        user = await userManager.FindByEmailAsync(context.UserName);

                        if (user != null)
                        {
                            if (!await AddExternalLogin(typeAuth, authKey, user.Id))
                            {
                                user            = null;
                                addExternalFlag = true;
                            }
                        }
                        else
                        {
                            addExternalFlag = true;
                        }
                    }
                    else
                    {
                        externalLoginFlag = true;
                        userId            = await ExternalLogin(authKey, userId);

                        if (userId != "")
                        {
                            user = await userManager.FindByIdAsync(userId);
                        }
                    }
                }
            }

            if (user == null)
            {
                if (magicFlag)
                {
                    context.SetError("invalid_grant", "The magic link is invalid or has expired");
                }
                else if (externalLoginFlag)
                {
                    context.SetError("invalid_grant", "externallogin");
                }
                else if (addExternalFlag)
                {
                    context.SetError("invalid_grant", "Invalid Associated email");
                }
                else
                {
                    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);
        }
Пример #50
0
        public override Task GrantResourceOwnerCredentials(OAuthGrantResourceOwnerCredentialsContext context)
        {
            context.OwinContext.Response.Headers.Add("Access-Control-Allow-Origin", new[] { "*" });

            string wechatLoginKey = ConfigurationManager.AppSettings["wxLoginKey"];

            if (string.IsNullOrWhiteSpace(wechatLoginKey))
            {
                context.SetError("AppSettings", "Key:wxLoginKey is not found");
                return(Task.FromResult <object>(null));
            }

            var identity = new ClaimsIdentity("JWT");

            if (context.Password == wechatLoginKey.Trim())
            {
                string apiUrl            = string.Format(wxLoginApi, ConfigurationManager.AppSettings["wxAppid"], ConfigurationManager.AppSettings["wxAppsercret"], context.UserName);
                JavaScriptSerializer js  = new JavaScriptSerializer();
                WechatLoginMsg       msg = js.Deserialize <WechatLoginMsg>(HttpHelper.HttpGet(apiUrl));

                //msg.Openid = "oqK0I0VG0jE5udoT1jIVBZOkQr3w";
                //msg.Session_key = "87LCUedsESieDCbaABh/4g==";

                if (!string.IsNullOrWhiteSpace(msg.Openid) && !string.IsNullOrWhiteSpace(msg.Session_key))
                {
                    using (var userAppService = IocManager.Instance.ResolveAsDisposable <IUserAppService>())
                    {
                        LoginOutput output = userAppService.Object.WechatLogin(new WechatLoginInput {
                            Openid = msg.Openid, Session_key = msg.Session_key
                        });
                        identity.AddClaim(new Claim("UserId", output.UserId.ToString()));
                        identity.AddClaim(new Claim("IsNewUser", output.IsNewUser.ToString()));
                        if (!string.IsNullOrEmpty(output.NickName))
                        {
                            identity.AddClaim(new Claim("nickname", output.NickName));
                        }
                        if (!string.IsNullOrEmpty(output.UserName))
                        {
                            identity.AddClaim(new Claim("username", output.UserName));
                        }
                        if (!string.IsNullOrEmpty(output.UserType))
                        {
                            identity.AddClaim(new Claim("usertype", output.UserType));
                        }
                    }
                }
                else
                {
                    context.SetError(msg.Errcode, msg.Errmsg);
                    return(Task.FromResult <object>(null));
                }
            }
            else
            {
                using (var userAppService = IocManager.Instance.ResolveAsDisposable <IUserAppService>())
                {
                    LoginOutput output = userAppService.Object.ManageLogin(new ManageLoginInput {
                        PassWord = context.Password, UserName = context.UserName
                    });

                    if (!output.UserId.HasValue)
                    {
                        context.SetError("invalid_grant", "The user name or password is incorrect");
                        return(Task.FromResult <object>(null));
                    }

                    identity.AddClaim(new Claim("UserId", output.UserId.ToString()));
                    identity.AddClaim(new Claim("IsNewUser", output.IsNewUser.ToString()));
                    if (!string.IsNullOrEmpty(output.NickName))
                    {
                        identity.AddClaim(new Claim("nickname", output.NickName));
                    }
                    if (!string.IsNullOrEmpty(output.UserName))
                    {
                        identity.AddClaim(new Claim("username", output.UserName));
                    }
                    if (!string.IsNullOrEmpty(output.UserType))
                    {
                        identity.AddClaim(new Claim("usertype", output.UserType));
                    }
                }
            }

            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));
        }
Пример #51
0
        public override async Task GrantResourceOwnerCredentials(OAuthGrantResourceOwnerCredentialsContext context)
        {
            _iAuthorizationBus = (IAuthorizationBus)GlobalConfiguration.Configuration.DependencyResolver.GetService(typeof(IAuthorizationBus));

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

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

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

            if (context.UserName == null || context.Password == null)
            {
                context.SetError("invalid_request", Resources.InvalidLoginRequest);
                return;
            }

            var user = await _iAuthorizationBus.FindUser(context.UserName, context.Password);

            if (user == null)
            {
                context.SetError("invalid_grant", Resources.InvalidEmailOrPassword);
                return;
            }

            var userRoles = await _iAuthorizationBus.UserRoles(user.Id);

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

            identity.AddClaim(new Claim(ClaimTypes.Name, context.UserName));
            identity.AddClaim(new Claim(AuthConstants.CustomClaims.UserId, user.Id));

            foreach (var role in userRoles)
            {
                identity.AddClaim(new Claim(ClaimTypes.Role, role));
            }

            var props = new AuthenticationProperties(new Dictionary <string, string>
            {
                {
                    AuthConstants.CustomAuthProps.ClientId, (context.ClientId == null) ? string.Empty : context.ClientId
                },
                {
                    AuthConstants.CustomAuthProps.UserName, context.UserName
                },
                {
                    AuthConstants.CustomAuthProps.IsAdmin, (userRoles.Contains(ApplicationConstants.ADMIN)) ? "true" : "false"
                },
                {
                    AuthConstants.CustomAuthProps.UserId, user.Id
                },
                {
                    AuthConstants.CustomAuthProps.FullName, user.FirstName + " " + user.LastName
                },
                {
                    AuthConstants.CustomAuthProps.ProfilePic, user.ProfileImage
                }
            });

            var ticket = new AuthenticationTicket(identity, props);

            context.Validated(ticket);
        }
Пример #52
0
        /// <summary>
        ///     Realiza a autenticação do usuário
        /// </summary>
        /// <param name="context"></param>
        /// <returns></returns>
        public override async Task GrantResourceOwnerCredentials(OAuthGrantResourceOwnerCredentialsContext context)
        {
            var allowedOrigin = context.OwinContext.Get <string>("as:clientAllowedOrigin");

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

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

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

            authenticateResult = new AuthenticateResult {
                IsAuthenticated = false, Username = context.UserName
            };

            if (!ApplicationUserManager.AuthenticateTypeIsSet())
            {
                authenticateResult.IsAuthenticated    = false;
                authenticateResult.MessageCode        = "alerts:error.authentication_type_not_set";
                authenticateResult.MessageDescription = "Authentication not set(see General Settings)";
            }
            else
            {
                var user = await userManager.FindUserAsync(context.UserName);

                authenticateResult = CheckUser(user, context.UserName, SettingHelper.Get());
                if (authenticateResult.CheckUserIsOk && user.AuthenticationType == AuthenticationType.DataBase)
                {
                    var signInManager = context.OwinContext.Get <ApplicationSignInManager>();

                    var result = await AuthenticateDataBaseAsync(signInManager, user.UserName, context.Password);

                    authenticateResult = CheckAuthenticatedInDataBase(user, authenticateResult, result);

                    if (authenticateResult.IsAuthenticated)
                    {
                        await userManager.ResetAccessFailedCountAsync(user.Id);  // Zerando contador de logins errados.
                    }
                }
                else if (authenticateResult.CheckUserIsOk && user.AuthenticationType == AuthenticationType.ActiveDirectory)
                {
                    authenticateResult.IsAuthenticated = AuthenticateActiveDirectory(context.UserName, context.Password);
                    if (!authenticateResult.IsAuthenticated)
                    {
                        authenticateResult.MessageCode        = "alerts:error.invalid_grant";
                        authenticateResult.MessageDescription = "The user name or password is incorrect.";
                    }
                }

                if (authenticateResult.IsAuthenticated)
                {
                    authenticateResult.Username = user.UserName;

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

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

                    AddCustomClaims(oAuthIdentity, user);

                    var properties = CreateProperties(user.UserName, context.ClientId);
                    var ticket     = new AuthenticationTicket(oAuthIdentity, properties);
                    context.Validated(ticket);
                    context.Request.Context.Authentication.SignIn(cookiesIdentity);
                }
            }


            SaveAccessLog(authenticateResult);

            if (!authenticateResult.IsAuthenticated)
            {
                context.SetError(authenticateResult.MessageCode, authenticateResult.MessageDescription);
            }
        }
Пример #53
0
        public override async Task GrantResourceOwnerCredentials(OAuthGrantResourceOwnerCredentialsContext context)
        {
            if (string.IsNullOrEmpty(context.UserName) || string.IsNullOrEmpty(context.Password))
            {
                context.SetError("invalid_grant", "The user name or password not supplied.");
                return;
            }
            var extraParams = await context.Request.ReadFormAsync();

            string username = extraParams["username"];
            string password = extraParams["password"];

            if (string.IsNullOrEmpty(username) && string.IsNullOrEmpty(password))
            {
                context.SetError("invalid_grant", "username or password not provided.");
                return;
            }
            int    memberId           = 0;
            string role               = "Member";
            string AuthenticationType = "Authenticated";
            bool   isAdmin            = false;
            string apiUrl             = "";

            using (NSAKLEntities asContext = new NSAKLEntities())
            {
                string hashPassword = System.Web.Security.FormsAuthentication.HashPasswordForStoringInConfigFile(context.Password, "sha1");
                try
                {
                    var queryResult = "";
                    //var queryResult = asContext.Database.SqlQuery<List<string>>("exec spInternetUserWithTermsAccept_Validate '" + context.UserName + "','" + hashPassword + "','',''").ToList();
                }
                catch (SqlException ex)
                {
                    context.SetError("invalid_user", ex.Message);
                    return;
                }
                catch (Exception ex)
                {
                    context.SetError("invalid_user", ex.Message);
                    return;
                }
                var internetUser = asContext.users.Where(x => x.username == context.UserName && x.password == hashPassword).FirstOrDefault();
                if (internetUser == null)
                {
                    context.SetError("invalid_grant", "The user name or password is incorrect.");
                    return;
                }
                apiUrl = System.Configuration.ConfigurationManager.AppSettings["APIUrl"];
                var memberinfo = asContext.members.Where(x => x.username == internetUser.username).FirstOrDefault();

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

                if (internetUser != null)
                {
                    if (memberinfo != null)
                    {
                        memberId = memberinfo.recid;
                        var coordinatorinfo = asContext.coordinators.Where(x => x.member_id == memberId).FirstOrDefault();
                        var admininfo       = asContext.committees.Where(x => x.user_id == memberId).FirstOrDefault();
                        if (coordinatorinfo != null)
                        {
                            role = "Coordinator";
                        }
                        if (admininfo != null)
                        {
                            role = "Admin";
                        }
                    }
                    if (string.IsNullOrEmpty(internetUser.username))//if interface doesnt' have IMEI and MAC, let the user log in
                    {
                        AuthenticationType = "UserNameBlank";
                    }
                    else
                    {
                        AuthenticationType = "AuthenticatedValueMatch";
                    }
                }
            }
            var identity = new ClaimsIdentity(context.Options.AuthenticationType);

            identity.AddClaim(new Claim(ClaimTypes.Name, context.UserName));
            identity.AddClaim(new Claim(ClaimTypes.NameIdentifier, memberId.ToString()));
            identity.AddClaim(new Claim(ClaimTypes.Role, role.ToString()));


            AuthenticationProperties properties = CreateProperties(context.UserName, AuthenticationType);


            AuthenticationTicket ticket = new AuthenticationTicket(identity, properties);

            context.Validated(ticket);
        }
Пример #54
0
        public override async Task GrantResourceOwnerCredentials(OAuthGrantResourceOwnerCredentialsContext poContext)
        {
            poContext.OwinContext.Response.Headers.Add("Access-Control-Allow-Origin", new[] { "*" });

            bool   bOk     = true;
            int    nStatus = 0;
            string sError  = "";

            Int64  nId;
            string sUsername;
            string sPasswrd;

            nId       = -1;
            sUsername = "";
            sPasswrd  = "";


            ClaimsIdentity ClaimsInToken;



            if (bOk)
            {
                try
                {
                    sUsername = poContext.UserName;
                    sPasswrd  = poContext.Password;
                }
                catch (Exception ex)
                {
                    bOk    = false;
                    sError = "Incomplete authentication or authorization data.| Message: " + ex.Message;
                }
            }

            // Finding user
            if (nStatus == 0)
            {
                //  nStatus = oBalMUsers.udfChkLoginDetails(out sError, out nId, sPhoneNum, sPasswrd);

                chkLoginDets(out sError, out bOk, out nId, sUsername, sPasswrd);
            }

            // Returning Auth type and claims
            if (bOk)
            {
                ClaimsInToken = new ClaimsIdentity(poContext.Options.AuthenticationType);
                ClaimsInToken.AddClaim(new Claim("sUserId", nId.ToString()));

                poContext.Validated(ClaimsInToken);
            }
            else if (bOk)
            {
                poContext.SetError("invalid_grant", sError);
                return;
            }
            else
            {
                poContext.SetError("Server Error", sError);
                return;
            }
        }
Пример #55
0
        public override async Task GrantResourceOwnerCredentials(OAuthGrantResourceOwnerCredentialsContext context)
        {
            try
            {
                var allowedOrigin = "*";
                context.OwinContext.Response.Headers.Add("Access-Control-Allow-Origin", new[] { allowedOrigin });

                var roleHeader     = "Role";
                var userIdHeader   = "UserId";
                var userNameHeader = "UserName";
                context.OwinContext.Response.Headers.Add("Access-Control-Expose-Headers", new[] { roleHeader, userIdHeader, userNameHeader });

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

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


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

                BAContext BAContext = new BAContext();
                var       userRole  = user.Roles.First().RoleId;
                var       role      = BAContext.Roles.FirstOrDefault(r => r.Id == userRole);

                //BAContext.Roles.Where(x =>
                //bool isAdmin = await userManager.IsInRoleAsync(user.UserName, "Admin");



                if (role.Name.Equals("Admin"))
                {
                    context.OwinContext.Response.Headers.Add("Role", new[] { "Admin" });
                }
                else if (role.Name.Equals("Manager"))
                {
                    context.OwinContext.Response.Headers.Add("Role", new[] { "Manager" });
                }
                else
                {
                    context.OwinContext.Response.Headers.Add("Role", new[] { "User" });
                }

                context.OwinContext.Response.Headers.Add("UserId", new[] { user.AppUserId.ToString() });


                if (role.Name.Equals("Admin"))
                {
                    string username = "******" + user.Email;
                    context.OwinContext.Response.Headers.Add("UserName", new[] { username });
                }
                else
                {
                    AppUser appUser  = BAContext.AppUsers.Where(au => au.Id == user.AppUserId).FirstOrDefault();
                    string  username = role.Name + ": " + appUser.Name + " " + appUser.LastName;
                    context.OwinContext.Response.Headers.Add("UserName", new[] { username });
                }

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

                var ticket = new AuthenticationTicket(oAuthIdentity, null);

                context.Validated(ticket);
            }
            catch (Exception e)
            {
                Console.WriteLine(e);
            }
        }
Пример #56
0
        public override async Task GrantResourceOwnerCredentials(OAuthGrantResourceOwnerCredentialsContext context)
        {
            var    identity   = new ClaimsIdentity(context.Options.AuthenticationType);
            string UserTypeID = context.OwinContext.Get <string>("UserTypeID");

            Login loginsetdetails = new Login();

            loginsetdetails.UserName     = context.UserName;
            loginsetdetails.UserPassword = context.Password;
            loginsetdetails.UserTypeID   = Convert.ToInt32(context.OwinContext.Get <string>("UserTypeID"));
            //Login logingetdetails = _iBAccount.GetUserDetails(loginsetdetails);
            Login logingetdetails = DataAccessLayer.DAccount.GetUserDetails1(loginsetdetails);

            // var currentUserRole = "Admin";
            if (logingetdetails != null)
            {
                var currentUserRole = logingetdetails.UserType;
                identity.AddClaim(new Claim("Role", currentUserRole));
                var props = new AuthenticationProperties(new Dictionary <string, string>
                {
                    {
                        "DisplayName", context.UserName
                    },
                    {
                        "Role", currentUserRole
                    },
                    {
                        "UserID", logingetdetails.UserID.ToString()
                    },
                    {
                        "FirstName", logingetdetails.FirstName
                    },
                    {
                        "LastName", logingetdetails.LastName
                    },
                    {
                        "MobileNo", logingetdetails.MobileNo
                    }
                });
                var token = new AuthenticationTicket(identity, props);
                context.Validated(token);
            }
            else if (context.UserName == "student")
            {
                if (context.Password == "student")
                {
                    var currentUserRole = "Student";
                    identity.AddClaim(new Claim("Role", currentUserRole));
                    var props = new AuthenticationProperties(new Dictionary <string, string>
                    {
                        {
                            "DisplayName", context.UserName
                        },
                        {
                            "Role", currentUserRole
                        }
                    });
                    var token = new AuthenticationTicket(identity, props);
                    context.Validated(token);
                }
            }
            else if (context.UserName == "superadmin")
            {
                if (context.Password == "superadmin")
                {
                    var currentUserRole = "SuperAdmin";
                    identity.AddClaim(new Claim("Role", currentUserRole));
                    var props = new AuthenticationProperties(new Dictionary <string, string>
                    {
                        {
                            "DisplayName", context.UserName
                        },
                        {
                            "Role", currentUserRole
                        }
                    });
                    var token = new AuthenticationTicket(identity, props);
                    context.Validated(token);
                }
            }
            else
            {
                context.SetError("invalid_grant", "The username or password is incorrect.");
            }
            // context.Response.Headers.Add("AuthorizationResponse",new[]{"Failed"});
            return;
        }
Пример #57
0
        public override async Task GrantResourceOwnerCredentials(OAuthGrantResourceOwnerCredentialsContext context)
        {
            var             allowedOrigin     = context.OwinContext.Get <string>("as:clientAllowedOrigin") ?? "*";
            ApplicationUser user              = new ApplicationUser();
            var             claimsIdentity    = new ClaimsIdentity(context.Options.AuthenticationType);
            var             concatenatedRoles = "";

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

            using (AuthRepository _repo = new AuthRepository())
            {
                if (TokenIdentityHelper.IsCredentialForSingleClick(context.Password))
                {
                    var userId = TokenIdentityHelper.GetUserIdSingleClickSignInToken(context.Password);
                    user = await _repo.FindByUserIdAsync(userId);
                }
                else
                {
                    user = await _repo.FindUser(context.UserName, context.Password);
                }

                if (user == null)
                {
                    context.SetError("invalid_grant", "The user name or password is incorrect.");
                    return;
                }
                else if (!user.IsActive || _repo.IsLockedOut(user.Id))
                {
                    context.SetError("blocked_user", "Your account is disabled.");
                    return;
                }

                var userRoles = await _repo.FindRolesAsync(user.Id);

                foreach (var role in userRoles)
                {
                    claimsIdentity.AddClaim(new Claim(ClaimTypes.Role, role));
                }
                concatenatedRoles = string.Join(",", userRoles);

                //Add user property
                userProperty = await _repo.FindUserProperty(user.Id);

                //addingclaims
                claimsIdentity.AddClaim(new Claim(ClaimTypes.Name, user.FirstName));
                claimsIdentity.AddClaim(new Claim(GlobalConstants.Account.ClaimTypes.UserName, user.UserName));
                claimsIdentity.AddClaim(new Claim(GlobalConstants.Account.ClaimTypes.Subject, user.Id));
                claimsIdentity.AddClaim(new Claim(GlobalConstants.Account.ClaimTypes.Issuer, GlobalConstants.EhrsIssuerUri));
            }

            Dictionary <string, string> properties = new Dictionary <string, string>
            {
                {
                    "as:client_id", (context.ClientId == null) ? string.Empty : context.ClientId
                }
            };

            properties.Add("userName", context.UserName);
            properties.Add("firstName", user.FirstName);
            properties.Add("roles", concatenatedRoles);

            var authProps = new AuthenticationProperties(properties);
            var ticket    = new AuthenticationTicket(claimsIdentity, authProps);

            context.Validated(ticket);
        }
Пример #58
0
        public override async Task GrantResourceOwnerCredentials(
            OAuthGrantResourceOwnerCredentialsContext context)
        {
            Client client = context.OwinContext.Get <Client>("oauth:client");

            if (client.AllowedGrant == OAuthGrant.ResourceOwner)
            {
                // Client flow matches the requested flow. Continue...
                UserManager <IdentityUser> userManager =
                    context.OwinContext.GetUserManager <UserManager <IdentityUser> >();

                IdentityUser user;
                try
                {
                    user = await userManager.FindAsync(context.UserName, context.Password);
                }
                catch
                {
                    // Could not retrieve the user.
                    context.SetError("server_error");
                    context.Rejected();

                    // Return here so that we don't process further. Not ideal but needed to be done here.
                    return;
                }

                if (user != null)
                {
                    try
                    {
                        // User is found. Signal this by calling context.Validated
                        ClaimsIdentity identity = await userManager.CreateIdentityAsync(
                            user,
                            DefaultAuthenticationTypes.ExternalBearer);

                        context.Validated(identity);
                    }
                    catch
                    {
                        // The ClaimsIdentity could not be created by the UserManager.
                        context.SetError("server_error");
                        context.Rejected();
                    }
                }
                else
                {
                    // The resource owner credentials are invalid or resource owner does not exist.
                    context.SetError(
                        "access_denied",
                        "The resource owner credentials are invalid or resource owner does not exist.");

                    context.Rejected();
                }
            }
            else
            {
                // Client is not allowed for the 'Resource Owner Password Credentials Grant'.
                context.SetError(
                    "invalid_grant",
                    "Client is not allowed for the 'Resource Owner Password Credentials Grant'");

                context.Rejected();
            }
        }
Пример #59
0
        public override async Task GrantResourceOwnerCredentials(OAuthGrantResourceOwnerCredentialsContext context)
        {

            try
            {
                var userStore = new UserStore<ApplicationUserIdentity>(new AuthenticationDbContext());
                var manager = new UserManager<ApplicationUserIdentity>(userStore);
                var userAuth = await manager.FindAsync(context.UserName, context.Password);

                if (userAuth != null)
                {
                    var identity = new ClaimsIdentity(context.Options.AuthenticationType);
                    identity.AddClaim(new Claim("Username", userAuth.UserName));
                    identity.AddClaim(new Claim("Email", userAuth.Email));
                    identity.AddClaim(new Claim("UserRefID", userAuth.UserRefID.ToString()));
                    identity.AddClaim(new Claim("LoggedOn", DateTime.Now.ToString()));


                    var user = ServiceProvider.EntityContext.Users.Get(int.Parse(userAuth.UserRefID.ToString()));

                    if (!user.IsActive)
                    {
                         context.SetError("invalid_grant", "The user name or password is incorrect.");
                    }
                    else {
                        var userRoles = manager.GetRoles(userAuth.Id);
                        foreach (string roleName in userRoles)
                        {
                            identity.AddClaim(new Claim(ClaimTypes.Role, roleName));
                        }
                        //return data to client
                        var additionalData = new AuthenticationProperties(new Dictionary<string, string>{
                        {
                            "role", Newtonsoft.Json.JsonConvert.SerializeObject(userRoles)
                        },
                        {
                            "userName", context.UserName
                        },
                        {
                            "isUseDiningRoom", user.IsUseDiningRoom.ToString()
                        }
                        
                    });

                        AuthenticationProperties properties = CreateProperties(context.UserName);
                        AuthenticationTicket ticket = new AuthenticationTicket(identity, additionalData);
                        context.Validated(ticket);
                    }
                }
                else
                {
                    context.SetError("invalid_grant", "The user name or password is incorrect.");
                }
                return;
            }
            catch (Exception ep)
            {

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