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

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

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

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

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

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

            ClaimsIdentity oAuthIdentity = await user.GenerateUserIdentityAsync(userManager);

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

            var ticket = new AuthenticationTicket(oAuthIdentity, null);

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

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

            // If we got this far, something failed, redisplay form
            return View(model);
        }
Exemplo n.º 3
0
        // validate username and password from the request and validate them against our ASP.NET 2.1 Identity system
        public override async Task GrantResourceOwnerCredentials(OAuthGrantResourceOwnerCredentialsContext context)
        {
            // cors allowed
            var allowedOrigin = "*";

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

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

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

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

            ClaimsIdentity oAuthIdentity = await signManager.CreateUserIdentityAsync(user);

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

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

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

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

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

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

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

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

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

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

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

            var ticket = new AuthenticationTicket(oAuthIdentity, props);

            context.Validated(ticket);
        }
        public async Task <ClaimsIdentity> GetClaimIdentityAsync(ApplicationUser appUser, ApplicationUserManager appUserManager)
        {
            ClaimsIdentity oAuthIdentity = await appUser.GenerateUserIdentityAsync(appUserManager, "JWT");

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

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

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

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

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

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

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

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

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

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

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

            var ticket = new AuthenticationTicket(oAuthIdentity, props);

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

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

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

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

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

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

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

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

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

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

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

            var ticket = new AuthenticationTicket(oAuthIdentity, null);

            context.Validated(ticket);

            if (ticket == null)
            {
                logger.Error($"Login failed The user name or password is incorrect: {context.UserName}", systemUser.Id);
            }
            else
            {
                List <Claim> claimsList = oAuthIdentity.Claims.Where(c => c.Type == ClaimTypes.Role).ToList();
                string       rolesList  = string.Join(",", claimsList.Select(r => r.Value).ToList());
                logger.Info($"Login Successful for {context.UserName} Roles: {rolesList}", systemUser.Id);
            }
        }
        public override async Task GrantResourceOwnerCredentials(OAuthGrantResourceOwnerCredentialsContext context)
        {
            var allowedOrigin = context.OwinContext.Get <string>("as:clientAllowedOrigin");

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

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

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

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

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

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

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

            context.Validated(ticket);
        }
Exemplo n.º 9
0
        public override async Task GrantResourceOwnerCredentials(OAuthGrantResourceOwnerCredentialsContext context)
        {
            try
            {
                var allowedOrigin = "*";

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

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

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

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

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

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

            return(token.Value);

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

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

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

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

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

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

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

            var ticket = new AuthenticationTicket(oAuthIdentity, null);

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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


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

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

            var ticket = new AuthenticationTicket(oAuthIdentity, props);

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

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

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

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

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

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

                iAuthContext con = new AuthContext();

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

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

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

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


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


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


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

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

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

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


                    var ticket = new AuthenticationTicket(identity, props);
                    context.Validated(ticket);
                }
            }
            catch (Exception ex)
            {
                logger.Error("Unable to validate user {0}", context.UserName);
                logger.Error(ex.InnerException != null ? ex.InnerException.ToString() : ex.ToString());
            }
        }
Exemplo n.º 15
0
        public override async Task GrantResourceOwnerCredentials(OAuthGrantResourceOwnerCredentialsContext context)
        {
            //var allowedOrigin = context.OwinContext.Get<string>("as:clientAllowedOrigin");

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

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

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

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

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

            //    context.Validated(ticket);

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

            var allowedOrigin = "*";

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

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

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

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

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

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

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

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

            var ticket = new AuthenticationTicket(oAuthIdentity, props);

            context.Validated(ticket);

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

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

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

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

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



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


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

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

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

            //context.Validated(ticket);
            //context.Validated(oAuthIdentity);
        }