public override async Task GrantResourceOwnerCredentials(OAuthGrantResourceOwnerCredentialsContext context)
        {
            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 due to error.
                context.SetError("server_error");
                context.Rejected();
                return;
            }
            if (user != null)
            {
                ClaimsIdentity identity = await userManager.CreateIdentityAsync(
                    user,
                    DefaultAuthenticationTypes.ExternalBearer);

                context.Validated(identity);
            }
            else
            {
                context.SetError("invalid_grant", "Invalid User Id or password'");
                context.Rejected();
            }
        }
        public override async Task GrantResourceOwnerCredentials(OAuthGrantResourceOwnerCredentialsContext context)
        {
            try
            {
                context.OwinContext.Response.Headers.Add("Access-Control-Allow-Origin", new[] { "*" });

                DB_PersonSpecificationsEntities db = new DB_PersonSpecificationsEntities();
                var user = db.Users.Where(d => d.UserName == context.UserName).FirstOrDefault();
                if (user == null)
                {
                    context.SetError("Error Message");
                    context.Rejected();
                    return;
                }
                var x = new Microsoft.AspNet.Identity.PasswordHasher().VerifyHashedPassword(user.Password, context.Password);
                if (x.ToString() != "Success")
                {
                    context.SetError("Error Message");
                    context.Rejected();
                    return;
                }
                var identity = new ClaimsIdentity("JWT");

                identity.AddClaim(new Claim(ClaimTypes.Name, user.UserName));
                var ticket = new AuthenticationTicket(identity, null);
                context.Validated(ticket);
            }
            catch (Exception ex)
            {
                context.SetError("invalid_grant", "message");
            }
        }
        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)
        {
            var identity = new ClaimsIdentity(context.Options.AuthenticationType);

            using (var db = new PurchaseEntities())
            {
                if (db != null)
                {
                    var user = db.Users.Where(o => o.UserName == context.UserName && o.Password == context.Password).FirstOrDefault();
                    if (user != null)
                    {
                        identity.AddClaim(new Claim("UserName", context.UserName));
                        identity.AddClaim(new Claim("LoggedOn", DateTime.Now.ToString()));
                        context.Validated(identity);
                    }
                    else
                    {
                        context.SetError("Wrong Crendtials", "Provided username and password is incorrect");
                        context.Rejected();
                    }
                }
                else
                {
                    context.SetError("Wrong Crendtials", "Provided username and password is incorrect");
                    context.Rejected();
                }
                return;
            }
        }
Пример #5
0
        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)
        {
            UserApi userApi = new UserApi();

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

            try
            {
                var ok = await userApi.Login(context.UserName, context.Password);

                if (!ok)
                {
                    context.SetError("Login failure", "The user name or password is incorrect.");
                    context.Rejected();
                }

                else
                {
                    var identity = new ClaimsIdentity(context.Options.AuthenticationType);
                    identity.AddClaim(new Claim(ClaimTypes.Name, context.UserName));

                    context.Validated(identity);
                }
            }
            catch (Exception ex)
            {
                context.SetError("Login Exception", "An error occured while trying to login.");
                File.AppendAllText(Path.Combine(Environment.CurrentDirectory, "log.txt"), ex.ToString());
                context.Rejected();
            }
        }
Пример #7
0
        public override async Task GrantResourceOwnerCredentials(OAuthGrantResourceOwnerCredentialsContext context)
        {
            var user = await userService.GetByLogin(context.UserName);

            if (user == null)
            {
                context.Rejected();

                context.SetError("User doesn't exist.", "Username or password is incorrect.");
            }
            else
            {
                if (MD5Hash.Verify(context.Password, user.Password))
                {
                    SetParams(context, user);

                    var identity = ConfigureClaims(context.Options.AuthenticationType, user);

                    context.Validated(identity);
                }
                else
                {
                    context.Rejected();

                    context.SetError("User doesn't exist.", "Username or password is incorrect.");
                }
            }

            return;
        }
Пример #8
0
        public override Task GrantResourceOwnerCredentials(OAuthGrantResourceOwnerCredentialsContext context)
        {
            var userService = HostContainer.GetInstance <IUserService>();

            try
            {
                var user = userService.CheckLogin(context.UserName, context.Password);
                if (user != null)
                {
                    var id = new ClaimsIdentity("Embedded");

                    id.AddClaim(new Claim("sub", context.UserName));
                    id.AddClaim(new Claim(ClaimTypes.Name, context.UserName));
                    id.AddClaim(new Claim(ClaimTypes.Role, string.Join(FrameworkConstants.Colon, user.UserUserGroups.Select(i => i.UserGroup.Name))));
                    context.Validated(id);
                }
                else
                {
                    context.Rejected();
                }
            }
            catch (Exception)
            {
                context.Rejected();
            }

            return(base.GrantResourceOwnerCredentials(context));
        }
        public override async Task GrantResourceOwnerCredentials(OAuthGrantResourceOwnerCredentialsContext context)
        {
            //If the request has valid and it contain username and password than this method will check correct crenstials and than generate a valid token
            var identity = new ClaimsIdentity(context.Options.AuthenticationType); //it will check the authenticate type

            using (var db = new DataContext())
            {
                if (db != null)
                {
                    var user = db.Users.Where(o => o.UserName == context.UserName && o.Password == context.Password).FirstOrDefault();//LINQ query checking the username
                    //and password from db
                    if (user != null)
                    {
                        //Store information againest the request
                        identity.AddClaim(new Claim("UserName", context.UserName));
                        identity.AddClaim(new Claim("LoggedOn", DateTime.Now.ToString()));
                        context.Validated(identity);
                    }
                    else
                    {
                        context.SetError("Wrong Crendtials", "Provided username and password is incorrect");
                        context.Rejected();
                    }
                }
                else
                {
                    context.SetError("Wrong Crendtials", "Provided username and password is incorrect");
                    context.Rejected();
                }
                return;
            }
        }
Пример #10
0
        public override Task GrantResourceOwnerCredentials(OAuthGrantResourceOwnerCredentialsContext context)
        {
            var             userManager = context.OwinContext.GetUserManager <ApplicationUserManager>();
            ApplicationUser user        = null;

            try
            {
                user = userManager.Find(context.UserName, context.Password);
            }
            catch (Exception e)
            {
                context.SetError("server_error");
                context.Rejected();
                return(base.GrantResourceOwnerCredentials(context));
            }

            if (user != null)
            {
                var identity =
                    userManager.CreateIdentity(user, DefaultAuthenticationTypes.ExternalBearer);

                context.Validated(identity);
            }
            else
            {
                context.SetError("invalid_grant", "Invalid User Id or password'");
                context.Rejected();
            }

            return(base.GrantResourceOwnerCredentials(context));
        }
 public async override Task GrantResourceOwnerCredentials(OAuthGrantResourceOwnerCredentialsContext context)
 {
     if (context.UserName == null || context.Password == null)
     {
         context.Rejected();
         return;
     }
     var users = new InMemoryUsers();
     var user = users.FirstOrDefault(u => u.Name.ToLower().Trim() == context.UserName.ToLower().Trim());
     if (user != null)
     {
         if (context.Password == user.Name.ToLower())
         {
             var id = new ClaimsIdentity(context.Options.AuthenticationType);
             id.AddClaim(new Claim("sub", user.Name));
             id.AddClaim(new Claim("email", user.Email));
             foreach (var role in user.Roles)
             {
                 id.AddClaim(new Claim("role", role));
             }
             context.Validated(id);
         }
     }
     else
     {
         context.Rejected();
     }
 }
Пример #12
0
 public override async Task GrantResourceOwnerCredentials(OAuthGrantResourceOwnerCredentialsContext context)
 {
     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 due to error.
         context.SetError("server_error");
         context.Rejected();
         return;
     }
     if (user != null)
     {
         ClaimsIdentity identity = await userManager.CreateIdentityAsync(
                                                 user,
                                                 DefaultAuthenticationTypes.ExternalBearer);
         context.Validated(identity);
     }
     else
     {
         context.SetError("invalid_grant", "Invalid UserId or password'");
         context.Rejected();
     }
 }
Пример #13
0
            public override async Task GrantResourceOwnerCredentials(OAuthGrantResourceOwnerCredentialsContext context)
            {
                UserManager <ApplicationUser> userManager = context.OwinContext.GetUserManager <UserManager <ApplicationUser> >();
                ApplicationUser user;

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

                    context.Validated(identity);
                    context.OwinContext.Response.Context.Response.Headers.Add("FullName", new[] { user.FullName });
                }
                else
                {
                    context.SetError("invalid_grant", "Tài khoản hoặc mật khẩu không đúng.'");
                    context.Rejected();
                }
            }
Пример #14
0
        public override Task GrantResourceOwnerCredentials(OAuthGrantResourceOwnerCredentialsContext context)
        {
            context.OwinContext.Response.Headers.Add("Access-Control-Allow-Origin", new[] { "*" });

            var user = context.OwinContext.Get <InsuranceContext>().Users
                       .FirstOrDefault(u => u.UserName == context.UserName);

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

            var loginResult = context.OwinContext.Get <IdentityService>()
                              .Authenticate(user.UserName, context.Password).Result;

            if (!loginResult)
            {
                context.SetError("invalid_grant", "The user name or password is incorrect");
                context.Rejected();
                return(Task.FromResult("The user name or password is incorrect"));
            }

            var ticket = new AuthenticationTicket(SetClaimsIdentity(context, user), new AuthenticationProperties());

            context.Validated(ticket);

            return(Task.FromResult <object>(null));
        }
Пример #15
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", "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);

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

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

            using (var db = new VTGEntities())
            {
                if (db != null)
                {
                    var vtgUsers = db.VtgStaffs.ToList();
                    if (vtgUsers != null)
                    {
                        var user = vtgUsers.Where(u => u.Username == context.UserName).FirstOrDefault().Username;
                        if (!string.IsNullOrEmpty(user))
                        {
                            var props = new AuthenticationProperties(new Dictionary <string, string>
                            {
                                { "userDisplayName", context.UserName }
                            });
                            var ticket = new AuthenticationTicket(identity, props);
                            context.Validated(ticket);
                        }
                        else
                        {
                            context.SetError("invalid_grant", "Provided username and password is incorrect");
                            context.Rejected();
                        }
                    }

                    else
                    {
                        context.SetError("invalid_grant", "Provided username and password is incorrect");
                        context.Rejected();
                    }
                    return;
                }
            }
        }
        /**
         * Performs CAS ticket validation & grants authorization
         *
         * Expected params (POST method):
         * "ticket" (provided to the client by the CAS server on a successful login)
         * "service" (application url - against which the login attempt was performed)
         * "grant_type=password"
         *
         * See TokenEndpointPath in Startup.cs for the autorization entry point URL
         *
         * If successful, grants authorization and returns client a response with
         * a valid "access_token", "username" and (app-specific) "AccessControl" dataset
         */
        public override async Task GrantResourceOwnerCredentials(
            OAuthGrantResourceOwnerCredentialsContext context)
        {
            dynamic args = await context.Request.ReadFormAsync();

            if (string.IsNullOrEmpty(args["ticket"]) || string.IsNullOrEmpty(args["service"]))
            {
                context.Rejected();
                context.SetError("invalid_grant", "No CAS ticket or service URL sent");
                return;
            }

            var res = await ValidateCasTicket(args["ticket"], args["service"]);

            if (res.success == null && !string.IsNullOrEmpty(serviceUser))
            {
                res.success = new CasServiceValidationSuccess {
                    user = serviceUser
                };
            }

            if (res.success == null)
            {
                context.Rejected();
                context.SetError("invalid_grant", "CAS validation failed: " + (res.failure != null
                    ? res.failure.description : "No response received from the CAS server"));
                return;
            }

            // once the CAS auth is done, gather additional data about the user (app-specific)
            //var acda = new AccessControlDA();
            //var ac = acda.GetAccessControl(res.success.user);
            var ac = new { userId = res.success.user, canRead = true, canSave = true };

            if (ac == null)
            {
                context.Rejected();
                context.SetError("invalid_grant", $"User '{res.success.user}' not found");
                return;
            }

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

            identity.AddClaim(new Claim(ClaimTypes.Name, res.success.user));
            identity.AddClaim(new Claim(ClaimTypes.Role, "User"));

            // To add app-specific data to the access token response use AuthenticationProperties
            // as below, for plain access token response identity will be encoded into it this way:
            //context.Validated(identity);

            var props = new AuthenticationProperties(new Dictionary <string, string> {
                { "username", res.success.user },
                { "AccessControl", JsonConvert.SerializeObject(ac) },
            });

            var ticket = new AuthenticationTicket(identity, props);

            context.Validated(ticket);
        }
Пример #17
0
            public override async Task GrantResourceOwnerCredentials(OAuthGrantResourceOwnerCredentialsContext context)
            {
                var allowedOrigin = context.OwinContext.Get <string>("as:clientAllowedOrigin");

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

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

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

                try
                {
                    user = userManager.Find(context.UserName, context.Password);
                    var ListUserGroup = db.ApplicationUserGroups.Where(s => s.UserId == user.Id).ToList();
                    foreach (var group in ListUserGroup)
                    {
                        var gname = db.ApplicationGroups.Where(s => s.ID == group.GroupId && s.Name == "Admin").Select(s => s.Name).FirstOrDefault();
                        if (gname != null)
                        {
                            GroupName = gname;
                            break;
                        }
                    }
                }
                catch (Exception ex)
                {
                    var err = ex.ToString();
                    // Could not retrieve the user due to error.
                    context.SetError("server_error");
                    context.Rejected();
                    return;
                }

                if (GroupName == null)
                {
                    context.SetError("Tài khoản không có quyền đăng nhập quản trị.");
                    context.Rejected();
                    return;
                }
                else if (user != null)
                {
                    ClaimsIdentity identity = await userManager.CreateIdentityAsync(
                        user,
                        DefaultAuthenticationTypes.ExternalBearer);

                    context.Validated(identity);
                }
                else
                {
                    context.SetError("invalid_grant", "Tài khoản hoặc mật khẩu không đúng.'");
                    context.Rejected();
                    return;
                }
            }
        public override async Task GrantResourceOwnerCredentials(OAuthGrantResourceOwnerCredentialsContext context)
        {

            //var userManager = context.OwinContext.GetUserManager<ApplicationUserManager>();
            //ApplicationUser user = await userManager.FindAsync(context.UserName, context.Password); //debug
            using (var lifeTimeScope = _lifetimeScope.BeginLifetimeScope())
            {

                Account user = _queryProcessor.Execute(new GetAccountQueryDto(context.UserName));

                if (user == null)
                {
                    context.SetError("invalid_grant", "Invalid credentials: Username or Password incorrect");
                    context.Rejected();
                    return;
                }

                if (!user.VerifyPassword(context.Password))
                {
                    context.SetError("invalid_grant", "Invalid credentials: Username or Password incorrect");
                    context.Rejected();
                    return;
                }

                //if (!user.EmailConfirmed)
                //{
                //    context.SetError("invalid_grant", "User did not confirm email.");
                //    return;
                //}
                
                var claimsIdentity = new ClaimsIdentity(context.Options.AuthenticationType);
                //ClaimsIdentity oAuthIdentity = await accountManager.CreateIdentityAsync(user, "JWT");
                claimsIdentity.AddClaim(new Claim(ClaimTypes.Name, user.Username));
                claimsIdentity.AddClaim(new Claim("accountId", user.Id.ToString()));
                claimsIdentity.AddClaim(new Claim("IP", context.Request.RemoteIpAddress));
               
                foreach (AccountRole role in user.AccountRoles)
                {
                    claimsIdentity.AddClaim(new Claim(ClaimTypes.Role, role.AccountRoleType.ToString()));
                }


                var authenticationProperties = new AuthenticationProperties()
                {
                    ExpiresUtc = DateTime.UtcNow.AddHours(24),
                    IsPersistent = true,
                };

                claimsIdentity.AddClaim(new Claim(ClaimTypes.Expiration, authenticationProperties.ExpiresUtc.ToString()));


                var ticket = new AuthenticationTicket(claimsIdentity, authenticationProperties);

                context.Validated(ticket);
               
           
            }
        }
        public override async Task GrantResourceOwnerCredentials(OAuthGrantResourceOwnerCredentialsContext context)
        {
            _applicationSignInManager = context.OwinContext.GetUserManager <ApplicationSignInManager>();
            _applicationUserManager   = context.OwinContext.Get <ApplicationUserManager>();
            var identity  = new ClaimsIdentity(context.Options.AuthenticationType);
            var dbcontext = ServiceLocator.Current.GetInstance <ApplicationIdentityContext>();
            var result    = await _applicationSignInManager.PasswordSignInAsync(context.UserName, context.Password, false, true);

            if (result == SignInStatus.Success)
            {
                var user = await _applicationUserManager.FindByNameAsync(context.UserName);

                if (!user.IsActive)
                {
                    context.Rejected();
                    context.SetError("Lỗi đăng nhập", "Tài khoản không tồn tại.");
                    return;
                }
                var roles = _applicationUserManager.GetRoles(user.Id);
                //identity.AddClaim(new Claim(ClaimTypes.Role, String.Join(";", user.Roles.Select(x => x.RoleId).ToArray())));
                identity.AddClaim(new Claim(ClaimTypes.Name, user.UserName));
                identity.AddClaim(new Claim(ClaimTypes.Sid, user.Id.ToString()));

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

                var data = new Dictionary <string, string>
                {
                    { "userName", user.UserName },
                    { "roles", string.Join(",", user.Roles) }
                };
                var properties = new AuthenticationProperties(data);


                var ticket = new AuthenticationTicket(identity, properties);
                context.Validated(ticket);
            }
            else
            {
                context.Rejected();
                if (result == SignInStatus.Failure)
                {
                    context.SetError("Lỗi đăng nhập", "Tài khoản hoặc mật khẩu không chính xác. ");
                }
                if (result == SignInStatus.LockedOut)
                {
                    context.SetError("Khóa tài khoản", "Tài khoản của bạn đã bị khóa, đợi 15 phút để mở lại");
                }

                if (result == SignInStatus.RequiresVerification)
                {
                    context.SetError("Chưa xác minh tài khoản", "Tài khoản của bạn chưa được xác nhận bởi email hay Admin");
                }
            }
        }
Пример #20
0
        /// <summary>
        /// USage:
        /// Make a post request to
        /// http://[Server]:[port]/token
        /// Body type: x-www-form-urlencoded
        /// Key - Values
        /// username - [username]
        /// password - [password]
        /// grant_type - password
        /// </summary>
        /// <param name="context"></param>
        /// <returns>
        /// {
        ///     "access_token": [actual token here],
        ///     "token_type": "bearer",
        ///     "expires_in": 1199
        /// }
        /// </returns>
        public override async Task GrantResourceOwnerCredentials(OAuthGrantResourceOwnerCredentialsContext context)
        {
            var identity = new ClaimsIdentity(context.Options.AuthenticationType);

            //var res = context.OwinContext.Response;
            //res.Headers.Add("Access-Control-Allow-Origin", new[] { "*" });
            //res.Headers.Add("Access-Control-Allow-Methods", new[] { "HEAD", "GET", "POST", "PUT", "PATCH", "DELETE", "OPTIONS" });
            //res.Headers.Add("Access-Control-Allow-Headers", new[] { "Origin", "Content-Type", "X-Auth-Token" });


            //Models.Employee authenticatedEmployee = new EmployeeService().Authenticate(context.UserName, context.Password);

            //    if (authenticatedEmployee == null)
            //    {
            //        return BadRequest("Username or password is incorrect");
            //    }

            using (var db = new WebAPIDemoDBEntities())
            {
                if (db != null)
                {
                    var empl = db.Employees.ToList();
                    //var user = db.Users.ToList();
                    if (empl != null)
                    {
                        if (!string.IsNullOrEmpty(empl.Where(u => u.Username == context.UserName && u.Password == context.Password).FirstOrDefault().Name))
                        {
                            identity.AddClaim(new Claim("Age", "16"));

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

                            var ticket = new AuthenticationTicket(identity, props);
                            context.Validated(ticket);
                        }
                        else
                        {
                            context.SetError("invalid_grant", "Provided username and password is incorrect");
                            context.Rejected();
                        }
                    }
                }
                else
                {
                    context.SetError("invalid_grant", "Provided username and password is incorrect");
                    context.Rejected();
                }
                return;
            }
        }
        public override async Task GrantResourceOwnerCredentials(OAuthGrantResourceOwnerCredentialsContext context)
        {
            var identity = new ClaimsIdentity(context.Options.AuthenticationType);

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

            using (var db = new LoadContext())
            {
                if (db != null)
                {
                    var user = db.B3G_USERS
                               .Where(b => b.USER_NAME.ToUpper() == context.UserName.ToUpper() && b.PASSWORD == context.Password)
                               .FirstOrDefault();
                    if (user != null)
                    {
                        if (!string.IsNullOrEmpty(user.USER_NAME) && user.INACTIVE == "N")
                        {
                            identity.AddClaim(new Claim("UserAuth", "*****@*****.**"));

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

                            var ticket = new AuthenticationTicket(identity, props);
                            context.Validated(ticket);
                        }
                        else if (!string.IsNullOrEmpty(user.USER_NAME) && user.INACTIVE == "Y")
                        {
                            context.SetError("inactive_user");
                            context.Rejected();
                        }
                        else
                        {
                            context.SetError("invalid_user");
                            context.Rejected();
                        }
                    }
                    else
                    {
                        context.SetError("invalid_user");
                        context.Rejected();
                    }
                }
                else
                {
                    context.SetError("invalid_db");
                    context.Rejected();
                }
                return;
            }
        }
Пример #22
0
            // cho phép đăng nhập từ các domain khác
            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 });

                // mới 1 user theo Identity tìm kiếm user đăng nhập, password trong database
                UserManager <ApplicationUser> userManager = context.OwinContext.GetUserManager <UserManager <ApplicationUser> >();
                ApplicationUser user;

                try
                {
                    user = await userManager.FindAsync(context.UserName, context.Password);
                }
                catch
                {
                    // Could not retrieve the user due to error.
                    context.SetError("server_error");
                    context.Rejected();
                    return;
                }
                if (user != null)
                {
                    // đăng nhập thành công tạo ra 1 userclaims(chứa tất cả thông tin user) gán vào session
                    //ClaimsIdentity identity = await userManager.CreateIdentityAsync(user, DefaultAuthenticationTypes.ExternalBearer);
                    //context.Validated(identity);

                    // check quyền admin
                    var applicationGroupService = ServiceFactory.Get <IApplicationGroupService>();
                    var listGroup = applicationGroupService.GetListGroupByUserId(user.Id);
                    if (listGroup.Any(x => x.Name == CommonConstants.Administrator))
                    {
                        // đăng nhập thành công tạo ra 1 userclaims(chứa tất cả thông tin user) gán vào session
                        ClaimsIdentity identity = await userManager.CreateIdentityAsync(
                            user,
                            DefaultAuthenticationTypes.ExternalBearer);

                        context.Validated(identity);
                    }
                    else
                    {
                        context.Rejected();
                        context.SetError("invalid_group", "Bạn không phải là admin");
                    }
                }
                else
                {
                    context.Rejected();
                    context.SetError("invalid_grant", "Tài khoản hoặc mật khẩu không đúng -__- ");
                }
            }
Пример #23
0
        public override async Task GrantResourceOwnerCredentials(OAuthGrantResourceOwnerCredentialsContext context)
        {
            var identity = new ClaimsIdentity(context.Options.AuthenticationType);

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

            try
            {
                using (var db = new MetallicaContext())
                {
                    if (db != null)
                    {
                        //var empl = db.Employees.ToList();
                        var user = db.Users.ToList();
                        if (user != null)
                        {
                            if (!string.IsNullOrEmpty(user.Where(u => u.UserName == context.UserName && u.Password == context.Password).FirstOrDefault().UserName))
                            {
                                identity.AddClaim(new Claim("Age", "16"));

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

                                var ticket = new AuthenticationTicket(identity, props);
                                context.Validated(ticket);
                            }
                            else
                            {
                                context.SetError("invalid_grant", "Provided username and password is incorrect");
                                context.Rejected();
                            }
                        }
                    }
                    else
                    {
                        context.SetError("invalid_grant", "Provided username and password is incorrect");
                        context.Rejected();
                    }
                    return;
                }
            }
            catch (System.Exception)
            {
                context.SetError("invalid_grant", "Provided username and password is incorrect");
                context.Rejected();
                return;
            }
        }
        public override async Task GrantResourceOwnerCredentials(OAuthGrantResourceOwnerCredentialsContext context)
        {
            // context.OwinContext.Response.Headers.Add("Access-Control-Allow-Origin", new[] { "*" });
            var client = context.OwinContext.Get <ApplicationClient>("oauth:client");

            if (string.IsNullOrEmpty(context.UserName) || string.IsNullOrEmpty(context.Password))
            {
                context.SetError("invalid_request", "No username or password are provided.");
                context.Rejected();
                return;
            }

            if (context.UserName != "John" && context.Password != "Smith")
            {
                context.SetError("invalid_grant", "The username or password is incorrect.");
                context.Rejected();
                return;
            }

            if (client.AllowedGrant != OAuthGrant.ResourceOwner)
            {
                context.SetError("invalid_grant", "The resource owner credentials are invalid or resource owner does not exist.");
                context.Rejected();
                return;
            }

            try
            {
                string uid = context.OwinContext.Get <string>("SmartCard");

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

                identity.AddClaim(new Claim("MyClaim", "I don't know"));

                var props = new AuthenticationProperties(new Dictionary <string, string>
                {
                    { "name", "John" },
                    { "surname", "Smith" },
                    { "age", "40" },
                    { "gender", "Male" }
                });

                var ticket = new AuthenticationTicket(identity, props);
                context.Validated(ticket);
            }
            catch (Exception)
            {
                // The ClaimsIdentity could not be created by the UserManager.
                context.Rejected();
                context.SetError("server_error");
            }
        }
Пример #25
0
            public override async Task GrantResourceOwnerCredentials(OAuthGrantResourceOwnerCredentialsContext context)
            {
                var allowedOrigin = context.OwinContext.Get <string>("as:clientAllowedOrigin");

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

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

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

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

                    context.Validated(identity);

                    //    var applicationGroupService = ServiceFactory.Get<IApplicationGroupService>();
                    //    var listGroup = applicationGroupService.GetListGroupByUserId(user.Id);
                    //    if (listGroup.Any(x => x.Name == CommonConstants.Administrator))
                    //    {
                    //        ClaimsIdentity identity = await userManager.CreateIdentityAsync(
                    //                       user,
                    //                       DefaultAuthenticationTypes.ExternalBearer);
                    //        context.Validated(identity);
                    //    }
                    //    else
                    //    {
                    //        context.Rejected();
                    //        context.SetError("invalid_group", "Bạn không phải là admin");
                    //    }
                }
                else
                {
                    context.SetError("invalid_grant", "Tài khoản hoặc mật khẩu không đúng.'");
                    context.Rejected();
                }
            }
Пример #26
0
            public override async Task GrantResourceOwnerCredentials(OAuthGrantResourceOwnerCredentialsContext context)
            {
                UserManager <IdentityUser> userManager = context.OwinContext.GetUserManager <UserManager <IdentityUser> >();
                IdentityUser user;

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


                    List <Claim> oAuthClaim = new List <Claim>()
                    {
                        new Claim(ClaimTypes.Email, "XXXXXXXX"),
                        new Claim(ClaimTypes.Name, user.UserName)
                    };

                    var identity = new ClaimsIdentity(oAuthClaim, context.Options.AuthenticationType);
                    var data     = new Dictionary <string, string>
                    {
                        { "userName", user.UserName },
                        { "isAuthenticated", "true" },
                        { "canAccessCategory", "true" },
                        { "canAccessProducts", "true" },
                        { "canAddProducts", "true" },
                        { "canSaveProduct", "true" },
                        { "canAddCategory", "true" }
                    };
                    var properties = new AuthenticationProperties(data);

                    var ticket = new AuthenticationTicket(identity, properties);

                    //context.Validated(token);
                    context.Validated(ticket);
                }
                else
                {
                    context.SetError("invalid_grant", "Invalid UserId or password'");
                    context.Rejected();
                }
            }
        // ********************************************************************************
        /// <summary>
        /// grant resource owner credentials
        /// </summary>
        /// <param name="context"></param>
        /// <returns></returns>
        // ********************************************************************************
        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;

            try
            {
                user = await userManager.FindAsync(context.UserName, context.Password);
            }
            catch
            {
                // Could not retrieve the user.
                context.SetError("The user name or password is incorrect.");
                //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("The user name or password is incorrect.");
                    //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();
            }
        }
Пример #28
0
        public override async Task GrantResourceOwnerCredentials(
            OAuthGrantResourceOwnerCredentialsContext context)
        {
            var client = context.OwinContext.Get <ApplicationUser>("oauth:client");

            // Client flow matches the requested flow. Continue...
            var userManager = DependencyResolver.Current.GetService <ApplicationUserManager>();

            ApplicationUser 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();
            }
        }
Пример #29
0
        public override async Task GrantResourceOwnerCredentials(OAuthGrantResourceOwnerCredentialsContext context)
        {
            Client _client = context.OwinContext.Get <Client>("oauth:client");

            if (_client.AllowedGrant == OAuthGrant.ResourceOwner)
            {
                IList <string> roles = new List <string> {
                    "admin", "superadmin"
                };
                TestAPIUser user = null;

                if (context.UserName.Equals("admin") && context.Password.Equals("admin"))
                {
                    user = new TestAPIUser
                    {
                        UserName       = "******",
                        EmailConfirmed = true
                    };
                }

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

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

                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 ticket = new AuthenticationTicket(identity, null);

                context.Validated(ticket);
            }
            else
            {
                // Client is not allowed for the 'Resource Owner Password Credentials Grant'.
                context.Rejected();
                context.SetError("invalid_grant", "Client is not allowed for the 'Resource Owner Password Credentials Grant'");
            }
        }
Пример #30
0
        public override async Task GrantResourceOwnerCredentials(OAuthGrantResourceOwnerCredentialsContext context)
        {
            UserManager <AppUser> userManager = context.OwinContext.GetUserManager <UserManager <AppUser> >();
            AppUser user;

            try
            {
                user = await userManager.FindAsync(context.UserName, context.Password);
            }
            catch
            {
                // Could not retrieve the user due to error.
                context.SetError("server_error", "Lỗi trong quá trình xử lý.");
                context.Rejected();
                return;
            }



            if (user != null)
            {
                var            permissions          = ServiceFactory.Get <IPermissionService>().GetByUserId(user.Id);
                var            permissionViewModels = AutoMapper.Mapper.Map <ICollection <Permission>, ICollection <PermissionViewModel> >(permissions);
                var            roles    = userManager.GetRoles(user.Id);
                ClaimsIdentity identity = await userManager.CreateIdentityAsync(user, DefaultAuthenticationTypes.ExternalBearer);

                string avatar = string.IsNullOrEmpty(user.Avatar) ? "" : user.Avatar;
                string email  = string.IsNullOrEmpty(user.Email) ? "" : user.Email;
                identity.AddClaim(new Claim("fullName", user.FullName));
                identity.AddClaim(new Claim("avatar", avatar));
                identity.AddClaim(new Claim("email", email));
                identity.AddClaim(new Claim("username", user.UserName));
                identity.AddClaim(new Claim("roles", JsonConvert.SerializeObject(roles)));
                identity.AddClaim(new Claim("permissions", JsonConvert.SerializeObject(permissionViewModels)));
                var props = new AuthenticationProperties(new Dictionary <string, string>
                {
                    { "fullName", user.FullName },
                    { "avatar", avatar },
                    { "email", email },
                    { "username", user.UserName },
                    { "permissions", JsonConvert.SerializeObject(permissionViewModels) },
                    { "roles", JsonConvert.SerializeObject(roles) }
                });
                context.Validated(new AuthenticationTicket(identity, props));
            }
            else
            {
                context.SetError("invalid_grant", "Tài khoản hoặc mật khẩu không đúng.");
                context.Rejected();
            }
        }
        public override async Task GrantResourceOwnerCredentials(OAuthGrantResourceOwnerCredentialsContext context)
        {
            var identity = new ClaimsIdentity(context.Options.AuthenticationType);

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

            using (var db = new DeepCartContext())
            {
                if (db != null)
                {
                    var user = db.Registrations.ToList();
                    if (user != null)
                    {
                        if (!string.IsNullOrEmpty(user.Where(u => u.UserName == context.UserName && u.Password == context.Password).FirstOrDefault().UserName))
                        {
                            var currentUser = user.Where(u => u.UserName == context.UserName && u.Password == context.Password).FirstOrDefault();
                            identity.AddClaim(new Claim("Role", currentUser.Role));
                            identity.AddClaim(new Claim("Id", Convert.ToString(currentUser.Id)));
                            identity.AddClaim(new Claim("UserName", Convert.ToString(currentUser.UserName)));
                            identity.AddClaim(new Claim("Phone", Convert.ToString(currentUser.Phone)));
                            identity.AddClaim(new Claim("Email", Convert.ToString(currentUser.Email)));


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

                            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;
            }
        }
Пример #32
0
            public override async Task GrantResourceOwnerCredentials(OAuthGrantResourceOwnerCredentialsContext context)
            {
                //cho phép đăng nhập từ các domain khác ()
                var allowedOrigin = context.OwinContext.Get <string>("as:clientAllowedOrigin");

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

                context.OwinContext.Response.Headers.Add("Access-Control-Allow-Origin", new[] { allowedOrigin });
                //tìm kiếm user pass trong data để có hợp lệ hay không
                UserManager <ApplicationUser> userManager = context.OwinContext.GetUserManager <UserManager <ApplicationUser> >();
                ApplicationUser user;

                try
                {
                    user = await userManager.FindAsync(context.UserName, context.Password);
                }
                catch
                {
                    // Không thể truy xuất người dùng do lỗi.
                    context.SetError("server_error");
                    context.Rejected();
                    return;
                }
                if (user != null)                                                                  //đăng nhập thành công
                {
                    var applicationGroupService = ServiceFactory.Get <IApplicationGroupService>(); //dùng class ServiceFactory gọi DI mà không qua Controller
                    var listGroup = applicationGroupService.GetListGroupByUserId(user.Id);         //lấy ra user thuộc group Administrator
                    if (listGroup.Any(x => x.Name == CommonConstants.Administrator))
                    {
                        ClaimsIdentity identity = await userManager.CreateIdentityAsync(
                            user,
                            DefaultAuthenticationTypes.ExternalBearer);

                        context.Validated(identity);
                    }
                    else
                    {
                        context.Rejected();
                        context.SetError("invalid_group", "Bạn không phải là admin");
                    }
                }
                else
                {
                    context.Rejected();
                    context.SetError("invalid_group", "Tài khoản hoặc mật khẩu không đúng.");
                }
            }
        public override async Task GrantResourceOwnerCredentials(OAuthGrantResourceOwnerCredentialsContext context)
        {
            var     userManager = context.OwinContext.GetUserManager <UserManager <AppUser> >();
            AppUser user;

            try
            {
                user = await userManager.FindAsync(context.UserName, context.Password);
            }
            catch
            {
                // Could not retrieve the user due to error.
                context.SetError("server_error", ApiMessage.ServerError);
                context.Rejected();
                return;
            }
            if (user != null)
            {
                var            permissions          = ServiceFactory.Get <IPermissionService>().GetPermissionsByUserId(user.Id);
                var            permissionViewModels = Mapper.Map <IEnumerable <PermissionDto> >(permissions);
                var            roles    = userManager.GetRoles(user.Id);
                ClaimsIdentity identity = await userManager.CreateIdentityAsync(user, DefaultAuthenticationTypes.ExternalBearer);

                identity.AddClaim(new Claim("firstName", user.FirstName ?? ""));
                identity.AddClaim(new Claim("lastName", user.LastName ?? ""));
                identity.AddClaim(new Claim("avatar", user.Avatar ?? ""));
                identity.AddClaim(new Claim("email", user.Email));
                identity.AddClaim(new Claim("userName", user.UserName));
                identity.AddClaim(new Claim("roles", JsonConvert.SerializeObject(roles)));
                identity.AddClaim(new Claim("permissions", JsonConvert.SerializeObject(permissionViewModels)));


                var props = new AuthenticationProperties(new Dictionary <string, string>
                {
                    ["firstName"]   = user.FirstName ?? "",
                    ["lastName"]    = user.LastName ?? "",
                    ["avatar"]      = user.Avatar ?? "",
                    ["email"]       = user.Email,
                    ["userName"]    = user.UserName,
                    ["permissions"] = JsonConvert.SerializeObject(permissionViewModels),
                    ["roles"]       = JsonConvert.SerializeObject(roles)
                });
                context.Validated(new AuthenticationTicket(identity, props));
            }
            else
            {
                context.SetError("invalid_grant", ApiMessage.InvalidLogin);
                context.Rejected();
            }
        }
Пример #34
0
        public override async Task GrantResourceOwnerCredentials(OAuthGrantResourceOwnerCredentialsContext context)
        {
            var identity = new ClaimsIdentity(context.Options.AuthenticationType);

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

            using (var db = new BaroneapiContext())
            {
                if (db != null)
                {
                    var user = new UserServices();
                    if (user != null)
                    {
                        var userExist = user.Authenticate(context.UserName, context.Password);
                        if (!(userExist == null))
                        {
                            identity.AddClaim(new Claim("role", userExist.Role));
                            identity.AddClaim(new Claim("userdisplayname", context.UserName));
                            // var props = new AuthenticationProperties(new Dictionary<string, string>());
                            var props = new AuthenticationProperties(new Dictionary <string, string>
                            {
                                {
                                    "userdisplayname", context.UserName
                                },
                                {
                                    "role", userExist.Role
                                },
                                {
                                    "success", "true"
                                }
                            });

                            var ticket = new AuthenticationTicket(identity, props);
                            context.Validated(ticket);
                        }
                        else
                        {
                            context.SetError("invalid_grant", "Provided username and password is incorrect");
                            context.Rejected();
                        }
                    }
                }
                else
                {
                    context.SetError("invalid_grant", "Provided username and password is incorrect");
                    context.Rejected();
                }
                return;
            }
        }
        public override Task GrantResourceOwnerCredentials(OAuthGrantResourceOwnerCredentialsContext context)
        {
           
            try
            {
                context.OwinContext.Response.Headers.Add("Access-Control-Allow-Origin", new[] { "*" });
                if (Utilities.ADAuthentication.AuthenticateUser.UserExist(context.UserName, ref userADEmail, ref userADName, ref userADPhone))
                {
                    Boolean isAuthorized = Utilities.ADAuthentication.AuthenticateUser.IsUserAuthorized(context.UserName, context.Password);
                    if (isAuthorized)
                    {
                        var id = new ClaimsIdentity("Embedded");
                        id.AddClaim(new Claim("sub", context.UserName));
                        id.AddClaim(new Claim("role", "user"));
                        context.Validated(id);
                        return Task.FromResult<int>(0);
                    }
                    else
                    {
                        context.SetError("The Password is incorrect.", "The password is incorrect.");
                        context.Rejected();
                        return Task.FromResult<int>(0);
                    }
                }
                else
                {
                    context.SetError("The user name is incorrect", "The user name is incorrect.");
                    context.Rejected();
                    return Task.FromResult<int>(0);
                }
            }
            catch (Exception ex)
            {
                lgLogging.LogFatalException(ex);
                if (ex.InnerException != null && ex.InnerException.ToString() != String.Empty)
                {
                    context.SetError("invalid_grant", "Problem occured while authenticating user. Problem: " + ex.InnerException.ToString());
                    context.Rejected();
                }
                else
                {
                    context.SetError("invalid_grant", "Problem occured while authenticating user. Problem: ");
                    context.Rejected();
                }
                return Task.FromResult<int>(0);

            }
            // create identity
        }
        public async override Task GrantResourceOwnerCredentials(OAuthGrantResourceOwnerCredentialsContext context)
        {

            //On créer le usermanager
            var userManager = context.OwinContext.GetUserManager<UserManager<MyUser>> ();

            //On verifie le login et mot de passe
            var user = await userManager.FindAsync(context.UserName, context.Password);


            if(user == null)
            {
                //si user n'existe pas on envoie un message d'erreur
                context.Rejected();
                context.SetError("invalidate_grant", "Le login ou le mot de passe est incorrect");
                return;
            }

            //On créer un id unique
            var id = await userManager.CreateIdentityAsync(user, OAuthDefaults.AuthenticationType);
            //on créer le token complet
            var ticket = new AuthenticationTicket(id, null);
            //on le valide et il est renvoyer à "l'utilisateur"
            context.Validated(ticket);
        }
        public override async Task GrantResourceOwnerCredentials
            (OAuthGrantResourceOwnerCredentialsContext context)
        {
            // validate user credentials (demo!)
            // user credentials should be stored securely (salted, iterated, hashed…)
            if (!((context.UserName == "*****@*****.**" && context.Password == "test123")||
                (context.UserName == "*****@*****.**" && context.Password == "test123")))
            {
                context.Rejected();
                return;
            }

            // create identity
            var id = new ClaimsIdentity("Embedded");
            id.AddClaim(new Claim("sub", context.UserName));
            id.AddClaim(new Claim("role", "user"));
            id.AddClaim(new Claim("privileges", "Admin,AccountViewer,AccountSubmit"));

            // create metadata to pass on to refresh token provider
            var props = new AuthenticationProperties(new Dictionary<string, string>
            {
                {"client_key", context.ClientId}
            });

            var ticket = new AuthenticationTicket(id, props);
            context.Validated(ticket);
        }
        public override async Task GrantResourceOwnerCredentials(
            OAuthGrantResourceOwnerCredentialsContext context)
        {
            // Retrieve user from database:
            var store = new CustomUserStore(new ApplicationDbContext());
            var user = await store.FindByEmailAsync(context.UserName);

            // Validate user/password:
            if(user == null || !store.PasswordIsValid(user, context.Password))
            {
                context.SetError(
                    "invalid_grant", "The user name or password is incorrect.");
                context.Rejected();
                return;
            }

            // Add claims associated with this user to the ClaimsIdentity object:
            var identity = new ClaimsIdentity(context.Options.AuthenticationType);
            foreach(var userClaim in user.Claims)
            {
                identity.AddClaim(new Claim(userClaim.ClaimType, userClaim.ClaimValue));
            }
            
            context.Validated(identity);
        }
Пример #39
0
        public override async Task GrantResourceOwnerCredentials(OAuthGrantResourceOwnerCredentialsContext context)
        {
            var credentials = Validator.ValidateUser(context.UserName, context.Password);

            if (credentials == null)
            {
                context.Rejected();
                return;
            }

            // create identity
            var id = new ClaimsIdentity(context.Options.AuthenticationType);
            id.AddClaim(new Claim("sub", context.UserName));
            id.AddClaim(new Claim(ClaimTypes.Name, context.UserName));
            id.AddClaim(new Claim(ClaimTypes.Role,credentials.Role));

            // create metadata to pass on to refresh token provider
            var props = new AuthenticationProperties(new Dictionary<string, string>
                {
                    {"oauth:client_id", context.ClientId}
                });

            var ticket = new AuthenticationTicket(id, props);
            context.Validated(ticket);
        }
        /// <summary>
        /// Validates a request for an access token based on username and password
        /// </summary>
        /// <param name="context"></param>
        /// <returns></returns>
        public override async Task GrantResourceOwnerCredentials(OAuthGrantResourceOwnerCredentialsContext context)
        {
            // Get the user manager
            var userManager = context.OwinContext.GetUserManager<ApplicationUserManager>();

            // Find the user based on the credentials provided
            var user = await userManager.FindAsync(context.UserName, context.Password);

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

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

            // Create ticket
            var ticket = new AuthenticationTicket(
                oAuthIdentity,
                CreateProperties(user.UserName, context.ClientId));

            // Validate our request for a token
            context.Validated(ticket);
        }
Пример #41
0
        public override async Task GrantResourceOwnerCredentials(OAuthGrantResourceOwnerCredentialsContext context)
        {
            using (var userManager = _userManagerFactory())
            {
                // Validate the username and password credentials.
                var user = await userManager.FindAsync(context.UserName, context.Password);

                // Avoid error:  "No 'Access-Control-Allow-Origin' header is present on the requested resource" via
                //               specifying CLIENT Url with port. '[EnableCorsAttribute]' annotation must be added
                //               to all applicable controllers.
                context.OwinContext.Response.Headers.Add("Access-Control-Allow-Origin", new[]{"http://localhost:5969/"});

                if (user == null || (string.IsNullOrWhiteSpace(context.UserName) || string.IsNullOrWhiteSpace(context.Password) ))
                {
                    context.SetError("invalid_grant", "The user name and/or password is invalid.");
                    context.Rejected();
                    return; 
                }

                // Create a ClaimsIdentity that represents the authenticated user; any claims added describe the identity of
                // the user, e.g. his user id (the ‘sub’ claim) or roles he is a member of, and becomes part of the token.
                // ASP.NET Identity supports claims-based authentication, where the user’s identity is represented as a set of claims.
                // Claims allow developers to be a lot more expressive in describing a user’s identity than roles allow. Whereas role 
                // membership is just a boolean (member or non-member), a claim can include rich information about the user’s
                // identity and membership.
                var oAuthClaimsIdentity = await userManager.CreateIdentityAsync(user, context.Options.AuthenticationType);
                oAuthClaimsIdentity.AddClaim(new Claim("sub", context.UserName)); // RPA: redundant?
                oAuthClaimsIdentity.AddClaim(new Claim("role", "user"));          // RPA: added per D.Baier article
                var authSessionValues = CreateProperties(user.UserName);
                var ticket = new AuthenticationTicket(oAuthClaimsIdentity, authSessionValues);
                context.Validated(ticket);
            }
        }
        /// <summary>
        /// Called when a request to the Token endpoint arrives with a "grant_type" of "password". 
        /// This occurs when the user has provided name and password credentials directly into the 
        /// client application's user interface, and the client application is using those to acquire an 
        /// "access_token" and optional "refresh_token". If the web application supports the resource owner 
        /// credentials grant type it must validate the context.Username and context.Password as appropriate. 
        /// To issue an access token the context.Validated must be called with a new ticket containing the 
        /// claims about the resource owner which should be associated with the access token. 
        /// The application should take appropriate measures to ensure that the endpoint isn’t abused by malicious callers. 
        /// The default behavior is to reject this grant type. See also http://tools.ietf.org/html/rfc6749#section-4.3.2
        /// </summary>
        public override async Task GrantResourceOwnerCredentials(OAuthGrantResourceOwnerCredentialsContext context)
        {

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

            if (context.UserName == "Pussy" && context.Password == "Cat")
            {


                // create identity
                var identity = new ClaimsIdentity(context.Options.AuthenticationType);
                identity.AddClaim(new Claim("sub", "test"));
                identity.AddClaim(new Claim("role", "user"));
                identity.AddClaim(new Claim(ClaimTypes.Name, context.UserName));

                // 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(identity, props);
                context.Validated(ticket);
                //context.Validated(identity);
                return;
            }
            context.Rejected();
        }
Пример #43
0
        public override Task GrantResourceOwnerCredentials(OAuthGrantResourceOwnerCredentialsContext context)
        {
            // validate user credentials (demo!)
            // user credentials should be stored securely (salted, iterated, hashed yada)
            if (string.IsNullOrWhiteSpace( context.UserName) || string.IsNullOrWhiteSpace(context.Password))
            {
                context.Rejected();
                return Task.FromResult<object>(null);
            }

            var userService = userServiceFactory.Invoke();
            User user;
            int authType;
            if(((user = userService.FindByEmail(context.UserName).Result) == null || !PasswordHash.ValidatePassword(user.Salt, context.Password, user.Password))
                && (!int.TryParse(context.UserName, out authType) || (user = userService.FindByAuthTypeAndAuthId((AuthType)authType, context.Password).Result) == null))
            {
                context.Rejected();
                return Task.FromResult<object>(null);
            }

            // create identity
            var id = new ClaimsIdentity(context.Options.AuthenticationType);
            if (user.Confirmed)
            {
                id.AddClaim(new Claim(ClaimTypes.Email, user.Email));
                id.AddClaim(new Claim(ClaimTypes.Role, ((int)user.Role).ToString()));
            }

            if (user.MobileNumber != null)
                id.AddClaim(new Claim(ClaimTypes.MobilePhone, user.MobileNumber));

            var country = user.Country.HasValue ? userService.FindCountry(user.Country.Value).Result : null;
            if (country != null)
                id.AddClaim(new Claim(ClaimTypes.Country, country.Id.ToString()));

            if (user.MobileNumberConfirmed)
                id.AddClaim(new Claim("MobileNumberConfirmed", user.MobileNumberConfirmed.ToString()));

            context.Validated(id);
            return Task.FromResult<object>(null);
        }
        public override async Task GrantResourceOwnerCredentials(OAuthGrantResourceOwnerCredentialsContext context)
        {
            if (context.UserName != context.Password)
            {
                context.Rejected();
                return;
            }

            var id = new ClaimsIdentity(context.Options.AuthenticationType);
            id.AddClaim(new Claim(ClaimTypes.Name, context.UserName));
           
            context.Validated(id);
        }
        //validate that the client id is allowed to use Resource Owner Password Credentials Grant, authenticate the user, and verify the organizations match
        public override async Task GrantResourceOwnerCredentials(OAuthGrantResourceOwnerCredentialsContext context)
        {
            bool validated=false;
            OAuthClient oauthClient = context.OwinContext.Get<OAuthClient>(OwinClientKey);
            //Make sure the client is allowed to be used for the Resource Owner Password Credentials Grant
            if(oauthClient!=null && oauthClient.AllowedGrant == OAuthGrant.ResourceOwnerPasswordCredentials)
            {
                ApplicationUserManager userManager = context.OwinContext.GetUserManager<ApplicationUserManager>();
                //ApplicationUser user = await userManager.FindAsync(context.UserName, context.Password);
                ApplicationUser user = await userManager.FindWithLockoutAsync(context.UserName, context.Password);

                if (user != null && user.OrganizationId == oauthClient.OrganizationId)                
                {
                    ClaimsIdentity oAuthIdentity = await user.GenerateUserIdentityAsync(userManager, OAuthDefaults.AuthenticationType);                    
                    //ClaimsIdentity cookiesIdentity = await user.GenerateUserIdentityAsync(userManager,CookieAuthenticationDefaults.AuthenticationType);
                    Guid oauthSessionValue=Guid.NewGuid();
                    oAuthIdentity.AddClaim(new Claim(OAuthBearerAuthenticationWithRevocationProvider.OAuthSessionClaimKey, oauthSessionValue.ToString()));
                    string[] scopes = {NicksOAuthConstants.ValuesReadScope};
                    oAuthIdentity.AddClaim(new Claim(NicksOAuthConstants.ScopeClaimType, String.Join(" ", scopes)));
                    ApplicationDbContext dbContext = context.OwinContext.Get<ApplicationDbContext>();
                    var oauthSessions = dbContext.OAuthSessions.Where(oas => oas.UserId.ToString() == user.Id && oas.ClientId == oauthClient.Id);
                    foreach(OAuthSession oauthSession in oauthSessions){
                        dbContext.OAuthSessions.Remove(oauthSession);
                    }
                    
                    dbContext.OAuthSessions.Add(new OAuthSession
                    {
                        ClientId = oauthClient.Id,                        
                        OrganizationId = user.OrganizationId,
                        UserId = user.Id,
                        Id = oauthSessionValue
                    });
                    dbContext.SaveChanges();                    
                    AuthenticationProperties properties = CreateProperties(user.UserName);
                    properties.Dictionary.Add("scope", String.Join(" ", scopes));
                    AuthenticationTicket ticket = new AuthenticationTicket(oAuthIdentity, properties);
                    //context.Validated(oAuthIdentity);
                    context.Validated(ticket);
                    context.Request.Context.Authentication.SignIn(oAuthIdentity);
                    context.OwinContext.Set<ApplicationUser>(OwinUserKey, user);
                    validated = true;                    
                }
            }

            if (!validated)
            {
                context.SetError("Authentication Failed");
                context.Rejected();
            }
        }
        public override Task GrantResourceOwnerCredentials(OAuthGrantResourceOwnerCredentialsContext context)
        {
            ExternalUser user = DAExternalUser.LoadUsers(context.UserName, context.Password);
            if (user==null)
            {
                context.Rejected();
                return Task.FromResult(0);
            }

            ClaimsIdentity claims = new ClaimsIdentity(context.Options.AuthenticationType);
            claims.AddClaim(new Claim("Username", context.UserName));
            claims.AddClaim(new Claim("Password", context.Password));
            context.Validated(claims);
            return Task.FromResult(0);
            
        }
        /*Called when a form to the Token endpoint arrives with a "grant_type" of "password". 
         * This occurs when the user has provided name and password credentials directly into the
         * client application's user interface, and the client application is using those to acquire
         * an "access_token" and optional "refresh_token". If the web application supports the resource
         * owner credentials grant type it must validate the context.Username and context.Password as 
         * appropriate. To issue an access token the context.Validated must be called with a new ticket
         * containing the claims about the resource owner which should be associated with the access token. 
         * The application should take appropriate measures to ensure that the endpoint isn’t abused by malicious 
         * callers. The default behavior is to reject this grant type. 
         * See also http://tools.ietf.org/html/rfc6749#section-4.3.2*/
        public override async Task GrantResourceOwnerCredentials(OAuthGrantResourceOwnerCredentialsContext context)
        {
            var client = await GetClient(context.ClientId);
            var user = await GetUser(context.UserName, context.Password);

            if (user == null 
                || string.IsNullOrEmpty(user.UserName))
            {
                context.Rejected();
                context.SetError("invalid_grant", "Invalid credentials.");
                return;
            }

            context.Validated(AuthTicketBuilder.BuildTicket(context.Options.AuthenticationType, user,
                client.AccessTokenLifetimeHours));
        }
        public override Task GrantResourceOwnerCredentials(OAuthGrantResourceOwnerCredentialsContext context)
        {
            if (context.UserName == "username" && context.Password == "pwd")
            {
                var claimsIdentity = new ClaimsIdentity(context.Options.AuthenticationType);
                claimsIdentity.AddClaim(new Claim("username", context.UserName));

                context.Validated(claimsIdentity);
            }
            else
            {
                context.SetError("Invalid credentials");
                context.Rejected();
            }

            return Task.FromResult(0);
        }
        public override Task GrantResourceOwnerCredentials(OAuthGrantResourceOwnerCredentialsContext context)
        {
            Organisation o = OrganisationDA.CheckCredentials(context.UserName, context.Password);
            if (o == null)
            {
                context.Rejected();
                return Task.FromResult(0);
            }

            var id = new ClaimsIdentity(context.Options.AuthenticationType);
            id.AddClaim(new Claim("dbname", o.DbName));
            id.AddClaim(new Claim("dblogin", o.DbLogin));
            id.AddClaim(new Claim("dbpass", o.DbPassword));

            context.Validated(id);
            return Task.FromResult(0);
        }
        public override async Task GrantResourceOwnerCredentials(OAuthGrantResourceOwnerCredentialsContext context)
        {
            // validate user credentials (demo!)
            // user credentials should be stored securely (salted, iterated, hashed yada)
            if (context.UserName != context.Password)
            {
                context.Rejected();
                return;
            }

            // create identity
            var id = new ClaimsIdentity(context.Options.AuthenticationType);
            id.AddClaim(new Claim("sub", context.UserName));
            id.AddClaim(new Claim("role", "user"));

            context.Validated(id);
        }
Пример #51
0
 public override Task GrantResourceOwnerCredentials(OAuthGrantResourceOwnerCredentialsContext context)
 {
     if (context.UserName == "admin" && context.Password == "p@ssw0rd")
     {
         var identity = new ClaimsIdentity(context.Options.AuthenticationType);
         identity.AddClaims(new[]
         {
             new Claim(ClaimTypes.GivenName, context.UserName)
         });
         context.Validated(identity);
     }
     else
     {
         context.Rejected();
     }
     return Task.FromResult(0);
 }
Пример #52
0
        public override Task GrantResourceOwnerCredentials(OAuthGrantResourceOwnerCredentialsContext context)
        {
            if (context.Password == context.UserName)
            {
                ClaimsIdentity id = new ClaimsIdentity("Embedded");
                id.AddClaim(new Claim("sub", context.UserName));
                id.AddClaim(new Claim(ClaimTypes.Role, "user"));
                
                context.Validated(id);
            }
            else
            {
                context.Rejected();
            }

            return Task.FromResult(0);
        }
        public async override Task GrantResourceOwnerCredentials
            (OAuthGrantResourceOwnerCredentialsContext context)
        {
            // Validate credentials
            if (!await Validator(context.UserName, context.Password))
            {
                context.Rejected();
                return;
            }

            // Create identity
            var identity = new ClaimsIdentity(GetUserClaims(context.UserName),
                context.Options.AuthenticationType);

            // Create ticket
            var ticket = new AuthenticationTicket(identity, new AuthenticationProperties());
            context.Validated(ticket);
        }
Пример #54
0
 public override async Task GrantResourceOwnerCredentials(OAuthGrantResourceOwnerCredentialsContext context)
 {
     User user = await this.TryGetUserWithCredentials(context.UserName, context.Password, context.OwinContext);
     if (user != null)
     {
         ClaimsIdentity oAuthIdentity = new ClaimsIdentity(context.Options.AuthenticationType);
         AuthenticationProperties properties = new AuthenticationProperties(new Dictionary<string, string>
         {
             { "userId", user.UserId.ToString() }
         });
         context.Validated(new AuthenticationTicket(oAuthIdentity, properties));
         context.Request.Context.Authentication.SignIn(oAuthIdentity);
     }
     else
     {
         context.Rejected();
     }
 }
        public override Task GrantResourceOwnerCredentials(OAuthGrantResourceOwnerCredentialsContext context)
        {
            // Hier controleren we of een gebruiker al dan niet zal bestaan in de database. Indien de gebruiker niet bestaat dan zal de gebruiker moeten 
            // weigeren. Onderstaande code zal daarvoor zorgen.

            ExternalUser user = ExternalUserDA.CheckCredentials(context.UserName, context.Password);
            if (user == null)
            {
                context.Rejected();
                return Task.FromResult(0);
            }

            var id = new ClaimsIdentity(context.Options.AuthenticationType);
            id.AddClaim(new Claim("username", context.UserName));
            id.AddClaim(new Claim("role", "user"));

            context.Validated(id);
            return Task.FromResult(0);
        }
        public override async Task GrantResourceOwnerCredentials(OAuthGrantResourceOwnerCredentialsContext context)
        {
            // validate user credentials (demo!)
            // user credentials should be stored securely (salted, iterated, hashed yada)
            // using a browser like Postman following oauth2 password granttype and
            // set grant_type=password, username and password
            if (context.UserName != null && context.UserName != context.Password)
            {
                context.Rejected();
                return;
            }

            // create identity
            var id = new ClaimsIdentity(context.Options.AuthenticationType);
            id.AddClaim(new Claim("sub", context.UserName));
            id.AddClaim(new Claim("role", "user"));

            context.Validated(id);
        }
Пример #57
0
		public override async Task GrantResourceOwnerCredentials(OAuthGrantResourceOwnerCredentialsContext context)
		{
			var userRep = new UsersRepository();

			if (!await userRep.IsUserValid(int.Parse(context.UserName), Guid.Parse(context.Password)))
			{
				Logger.Trace("Отказано в выдаче токена.");

				context.SetError("invalid_grant", "Имя пользователя или пароль неправильны.");
				context.Rejected();
				return;
			}

			Logger.Trace("Токен выдан.");
			
			var identity = new ClaimsIdentity(context.Options.AuthenticationType);
			identity.AddClaim(new Claim("user_name", context.UserName));
			
			context.Validated(identity);
		}
        public override async Task GrantResourceOwnerCredentials(OAuthGrantResourceOwnerCredentialsContext context)
        {
            var userManager = context.OwinContext.GetUserManager<ApplicationUserManager>();
            var user = await userManager.FindAsync(context.UserName, context.Password);

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

            var identity = new ClaimsIdentity(context.Options.AuthenticationType);
            foreach (var userClaim in user.Claims)
            {
                identity.AddClaim(new Claim(userClaim.ClaimType, userClaim.ClaimValue));
            }

            context.Validated(identity);
        }
        private static BasicAuthElement FindUser(OAuthGrantResourceOwnerCredentialsContext context)
        {
            var configuration = ConfigurationManager.GetSection("basicAuth") as BasicAuthConfigSection;

            if (configuration == null)
            {
                throw new ConfigurationErrorsException("Cannot find basicAuth section in Web.config");
            }

            var users = configuration.Instances.Cast<BasicAuthElement>();
            var authenticatedUser = users.SingleOrDefault(u =>
                u.UserName.Equals(context.UserName, StringComparison.InvariantCultureIgnoreCase) &&
                u.Password.Equals(context.Password.CreateSha2Hash()));

            if (authenticatedUser == null)
            {
                context.Rejected();
            }

            return authenticatedUser;
        }
        public override async Task GrantResourceOwnerCredentials(OAuthGrantResourceOwnerCredentialsContext context)
        {
            await Task.Run(() =>
            {
                if (context.UserName != "vincenzo" || context.Password != "ceccio")
                {
                    context.Rejected();
                    return;
                }


                // create identity
                var id = new ClaimsIdentity(context.Options.AuthenticationType);
                id.AddClaim(new Claim("sub", context.UserName));
                id.AddClaim(new Claim("role", "user"));

                context.Validated(id);
                context.Request.Context.Authentication.SignIn(id);

            });
        }