Exemplo n.º 1
0
        public async Task <IActionResult> PostAsync([FromBody] AuthPost model)
        {
            var result = Unauthorized() as IActionResult;

            var user            = null as ApplicationUser;
            var isAuthenticated = false;

            switch (model.GrantType)
            {
            case GrantType.Password:
                ValidateModelForGrantTypePassword(model);

                user = await cachedUserManager.GetUserByUserNameAndFilterRoleAssignmentsByClientIdAsync(model.User, model.ClientId.Value);

                if (user != null)
                {
                    await ValidateUserStateAsync(user);

                    var checkPassword = await signInManager.CheckPasswordSignInAsync(user, model.Password);

                    if (checkPassword)
                    {
                        isAuthenticated = true;
                    }
                }

                break;

            case GrantType.RefreshToken:
                ValidateModelForGrantTypeRefreshToken(model);

                if (cacheHandler.TryGetValue <RefreshTokenData>(model.RefreshToken, out var refreshTokenData))
                {
                    await cacheHandler.RemoveAsync <RefreshTokenData>(model.RefreshToken);

                    user = await cachedUserManager.GetUserByUserNameAndFilterRoleAssignmentsByClientIdAsync(refreshTokenData.UserName, model.ClientId.Value);

                    isAuthenticated = true;
                }

                break;
            }

            if (isAuthenticated)
            {
                var authPostResult = new AuthPostResult(userPrincipalTokenizer.GenerateToken(user));
                await cacheHandler.SetAsync(authPostResult.RefreshToken, new RefreshTokenData()
                {
                    Token    = authPostResult.RefreshToken,
                    UserName = user.UserName
                });

                result = Ok(authPostResult);
            }

            return(result);
        }
        public async Task <IActionResult> GetAsync([FromRoute] string username)
        {
            var errors = new List <SecurityResourceNotFoundExceptionItem>();

            var user = await cachedUserManager.GetUserByUserNameAndFilterRoleAssignmentsByClientIdAsync(username, userPrincipalBuilder.GetCurrentClientId());

            if (user == null)
            {
                errors.Add(SecurityResourceNotFoundExceptionItem.User);
            }

            if (errors.Any())
            {
                throw new ResourceNotFoundException(errors);
            }

            var result = mapper.Map <ApplicationUser, UsersGetResult>(user);

            return(Ok(result));
        }