public async Task <IActionResult> OnGetAsync(string userId, string email, string code)
        {
            if (userId == null || email == null || code == null)
            {
                return(RedirectToPage("/Index"));
            }

            var user = await _userManager.FindByIdAsync(userId);

            if (user == null)
            {
                return(NotFound($"Unable to load user with ID '{userId}'."));
            }

            code = Encoding.UTF8.GetString(WebEncoders.Base64UrlDecode(code));
            var result = await _userManager.ChangeEmailAsync(user, email, code);

            if (!result.Succeeded)
            {
                StatusMessage = "Error changing email.";
                return(Page());
            }

            // In our UI email and user name are one and the same, so when we update the email
            // we need to update the user name.
            var setUserNameResult = await _userManager.SetUserNameAsync(user, email);

            if (!setUserNameResult.Succeeded)
            {
                StatusMessage = "Error changing user name.";
                return(Page());
            }

            await _signInManager.RefreshSignInAsync(user);

            StatusMessage = "Thank you for confirming your email change.";
            return(Page());
        }
Example #2
0
        public async Task <IActionResult> OnGetAsync(string userId, string email, string code)
        {
            if (userId == null || email == null || code == null)
            {
                return(RedirectToPage("/Index"));
            }

            var user = await _userManager.FindByIdAsync(userId);

            if (user == null)
            {
                return(NotFound($"Невозможно загрузить пользователя с идентификатором '{userId}'."));
            }

            code = Encoding.UTF8.GetString(WebEncoders.Base64UrlDecode(code));
            var result = await _userManager.ChangeEmailAsync(user, email, code);

            if (!result.Succeeded)
            {
                StatusMessage = "Ошибка изменения email.";
                return(Page());
            }

            // In our UI email and user name are one and the same, so when we update the email
            // we need to update the user name.
            var setUserNameResult = await _userManager.SetUserNameAsync(user, email);

            if (!setUserNameResult.Succeeded)
            {
                StatusMessage = "Ошибка изменения имени пользователя.";
                return(Page());
            }

            await _signInManager.RefreshSignInAsync(user);

            StatusMessage = "Благодарим Вас за подтверждение изменения email.";
            return(Page());
        }
        public async Task <IActionResult> OnGetAsync(string userId, string email, string code)
        {
            if (userId == null || email == null || code == null)
            {
                return(RedirectToPage("/Index"));
            }

            var user = await _userManager.FindByIdAsync(userId);

            if (user == null)
            {
                return(NotFound($"No se puede cargar el usuario con ID '{userId}'."));
            }

            code = Encoding.UTF8.GetString(WebEncoders.Base64UrlDecode(code));
            var result = await _userManager.ChangeEmailAsync(user, email, code);

            if (!result.Succeeded)
            {
                StatusMessage = "Error al cambiar email.";
                return(Page());
            }

            // In our UI email and user name are one and the same, so when we update the email
            // we need to update the user name.
            var setUserNameResult = await _userManager.SetUserNameAsync(user, email);

            if (!setUserNameResult.Succeeded)
            {
                StatusMessage = "Error al cambiar nombre de usuario.";
                return(Page());
            }

            await _signInManager.RefreshSignInAsync(user);

            StatusMessage = "Gracias por confirmar el cambio de email.";
            return(Page());
        }
        public async Task <IActionResult> OnGetAsync(string userId, string email, string code)
        {
            if (userId == null || email == null || code == null)
            {
                return(RedirectToPage("/Index"));
            }

            var user = await _userManager.FindByIdAsync(userId);

            if (user == null)
            {
                return(NotFound($"Kullanıcı Bulunamadı #'{_userManager.GetUserId(User)}'.\n Bu kodu destek birimimize bildirerek yardım alabilirsiniz."));
            }

            code = Encoding.UTF8.GetString(WebEncoders.Base64UrlDecode(code));
            var result = await _userManager.ChangeEmailAsync(user, email, code);

            if (!result.Succeeded)
            {
                StatusMessage = "Eposta değişirken HATA.";
                return(Page());
            }

            // In our UI email and user name are one and the same, so when we update the email
            // we need to update the user name.
            var setUserNameResult = await _userManager.SetUserNameAsync(user, email);

            if (!setUserNameResult.Succeeded)
            {
                StatusMessage = "Kullanıcı Adı Değişirken HATA.";
                return(Page());
            }

            await _signInManager.RefreshSignInAsync(user);

            StatusMessage = "Eposta değişimini kabul ettin.";
            return(Page());
        }
Example #5
0
        public async Task <IActionResult> OnGetAsync(string userId, string email, string code)
        {
            if (userId == null || email == null || code == null)
            {
                return(RedirectToPage("/Index"));
            }

            var user = await userManager.FindByIdAsync(userId);

            if (user == null)
            {
                return(NotFound($"Unable to load user with ID '{userId}'."));
            }

            code = Encoding.UTF8.GetString(WebEncoders.Base64UrlDecode(code));
            var result = await userManager.ChangeEmailAsync(user, email, code);

            if (!result.Succeeded)
            {
                StatusMessage = identityLocalizationService.GetLocalizedHtmlString("CONFIRM_EMAIL_CHANGE_ERROR");
                return(Page());
            }

            // // In our UI email and user name are one and the same, so when we update the email
            // // we need to update the user name.
            // var setUserNameResult = await userManager.SetUserNameAsync(user, email);
            // if (!setUserNameResult.Succeeded)
            // {
            //   StatusMessage = "Error changing user name.";
            //   return Page();
            // }

            await signInManager.RefreshSignInAsync(user);

            StatusMessage = identityLocalizationService.GetLocalizedHtmlString("CONFIRM_EMAIL_CHANGE_TEXT");

            return(Page());
        }
        public async Task <IActionResult> OnGetAsync(string userId, string email, string code)
        {
            if (userId == null || email == null || code == null)
            {
                return(RedirectToPage("/Index"));
            }

            var user = await _userManager.FindByIdAsync(userId);

            if (user == null)
            {
                return(NotFound($"Nepavyksta įkelti vartotojo, kurio ID '{userId}'."));
            }

            code = Encoding.UTF8.GetString(WebEncoders.Base64UrlDecode(code));
            var result = await _userManager.ChangeEmailAsync(user, email, code);

            if (!result.Succeeded)
            {
                StatusMessage = "Elektroninio pašto pakeisti nepavyko.";
                return(Page());
            }

            // In our UI email and user name are one and the same, so when we update the email
            // we need to update the user name.
            var setUserNameResult = await _userManager.SetUserNameAsync(user, email);

            if (!setUserNameResult.Succeeded)
            {
                StatusMessage = "Vartotojo vardo pakeisti nepavyko.";
                return(Page());
            }

            await _signInManager.RefreshSignInAsync(user);

            StatusMessage = "Elektroninis paštas pakeistas sėkmingai.";
            return(Page());
        }
        public async Task <IActionResult> OnGetAsync(string userId, string email, string code)
        {
            if (userId == null || email == null || code == null)
            {
                return(RedirectToPage("/Index"));
            }

            var user = await _userManager.FindByIdAsync(userId);

            if (user == null)
            {
                return(NotFound($"Non è stato possibile trovare l'utente con ID '{userId}'."));
            }

            code = Encoding.UTF8.GetString(WebEncoders.Base64UrlDecode(code));
            var result = await _userManager.ChangeEmailAsync(user, email, code);

            if (!result.Succeeded)
            {
                StatusMessage = "Errore nel cambio email.";
                return(Page());
            }

            // In our UI email and user name are one and the same, so when we update the email
            // we need to update the user name.
            var setUserNameResult = await _userManager.SetUserNameAsync(user, email);

            if (!setUserNameResult.Succeeded)
            {
                StatusMessage = "Errore nel cambio del nome utente.";
                return(Page());
            }

            await _signInManager.RefreshSignInAsync(user);

            StatusMessage = "Grazie per aver confermato il cambio email.";
            return(Page());
        }
        public async Task <Result> ConfirmEmailAsync(string userId, string token)
        {
            var user = await _userManager.FindByIdAsync(userId);

            if (user == null)
            {
                return(Result.GeneralFailure("User Not Found"));
            }
            if (user.EmailConfirmed)
            {
                return(Result.GeneralFailure("This Email Has Confirmed Already"));
            }

            var    decodedToken = WebEncoders.Base64UrlDecode(token);
            string normalToken  = Encoding.UTF8.GetString(decodedToken);
            var    result       = await _userManager.ConfirmEmailAsync(user, normalToken);

            if (result.Succeeded)
            {
                return(Result.Success("Email Confirmed Successfully"));
            }
            return(Result.Failure(result.Errors.Select(x => x.Description)));
        }
Example #9
0
        public async Task <IActionResult> VerifyEmail(string userId, string code)
        {
            if (string.IsNullOrEmpty(userId) || string.IsNullOrEmpty(code))
            {
                return(RedirectToAction("Index"));
            }

            var user = await _userManager.FindByIdAsync(userId);

            if (user != null)
            {
                code = Encoding.UTF8.GetString(WebEncoders.Base64UrlDecode(code));

                var result = await _userManager.ConfirmEmailAsync(user, code);

                if (result.Succeeded)
                {
                    return(View());
                }
            }

            return(BadRequest());
        }
Example #10
0
        public async Task <ApiResponse> ConfirmEmailAddress(EmailConfirmationVm model)
        {
            var user = await _userManager.FindByEmailAsync(model.Email);

            if (user == null)
            {
                throw new MyNotFoundException(ApiResponseDescription.USER_NOT_FOUND);
            }

            var codeDecodedBytes = WebEncoders.Base64UrlDecode(model.Token);
            var codeDecoded      = Encoding.UTF8.GetString(codeDecodedBytes);

            var result = await _userManager.ConfirmEmailAsync(user, codeDecoded);

            if (result.Succeeded)
            {
                return(new ApiResponse(true));
            }
            else
            {
                throw new MyException(ApiResponseDescription.EMAIL_ADDRESS_COULD_NOT_BE_CONFIRMED);
            }
        }
Example #11
0
        /// <summary>
        /// 解密JWT
        /// </summary>
        /// <param name="jwt">jwt</param>
        /// <returns></returns>
        public IActionResult Decode(string jwt)
        {
            string[] arrayJwt = jwt.Split('.');

            string decodeJwt = "";

            for (int i = 0; i < arrayJwt.Length; i++)
            {
                if (i == arrayJwt.Length - 1)
                {
                    decodeJwt += "加密签名无法解密";
                }
                else
                {
                    // 不能直接用Convert.FromBase64String,会报错,微软二逼,必须对base64加密字符串按照规则整理一下,具体怎么整理看这个方法的内容
                    var decodeBytes = WebEncoders.Base64UrlDecode(arrayJwt[i]);
                    //var decodeBytes = ConvertFromBase64String(arrayJwt[i]);
                    decodeJwt += Encoding.UTF8.GetString(decodeBytes);
                }
            }

            return(Ok(decodeJwt));
        }
Example #12
0
        public async Task <IActionResult> OnGetAsync(string userId, string code)
        {
            ViewData["HeaderImage"] = "/Img/nemuel-sereti-unsplash.jpg";
            ViewData["HeaderText"]  = "Welcome to Code Cache";

            if (userId == null || code == null)
            {
                return(RedirectToPage("/Index"));
            }

            var user = await _userManager.FindByIdAsync(userId);

            if (user == null)
            {
                return(NotFound($"Unable to load user with ID '{userId}'."));
            }

            code = Encoding.UTF8.GetString(WebEncoders.Base64UrlDecode(code));
            var result = await _userManager.ConfirmEmailAsync(user, code);

            StatusMessage = result.Succeeded ? "Thank you for confirming your email." : "Error confirming your email.";
            return(Page());
        }
        public async Task <IActionResult> OnGetAsync(string userId, string code)
        {
            if (code == null || userId == null)
            {
                return(BadRequest("A code must be supplied for authenticator reset."));
            }
            else
            {
                var token  = Encoding.UTF8.GetString(WebEncoders.Base64UrlDecode(code));
                var result = await _identityService.ResetAuthenticatorAsync(userId, token);

                if (result.Succeeded)
                {
                    _logger.LogInformation("User with ID {UserId} reseted his authenticator", userId);
                    return(RedirectToPage("/Login"));
                }
                else
                {
                    _logger.LogError("Error occured resetting authenticator of user with Id {UserId}", userId);
                    return(Page());
                }
            }
        }
Example #14
0
        public async Task <ActionResult <UserDto> > VerifyEmail(string emailVerificationToken, string email)
        {
            var user = await this._userManager.FindByEmailAsync(email);

            if (user == null)
            {
                return(Unauthorized());
            }

            var decodedTokenBytes = WebEncoders.Base64UrlDecode(emailVerificationToken);
            var decodedToken      = Encoding.UTF8.GetString(decodedTokenBytes);

            var result = await this._userManager.ConfirmEmailAsync(user, decodedToken);

            if (result.Succeeded)
            {
                return(Ok("Email Confirmed! You can now login"));
            }
            else
            {
                return(BadRequest("Error verifying email"));
            }
        }
Example #15
0
        public async Task <IActionResult> ResetPassword(ResetPasswordViewModel model)
        {
            if (!ModelState.IsValid)
            {
                return(View(model));
            }
            var user = await _userManager.FindByNameAsync(model.Email);

            if (user == null)
            {
                // Don't reveal that the user does not exist
                return(RedirectToAction(nameof(AccountController.ResetPasswordConfirmation), "Account"));
            }
            var code   = Encoding.UTF8.GetString(WebEncoders.Base64UrlDecode(model.Code));
            var result = await _userManager.ResetPasswordAsync(user, code, model.Password);

            if (result.Succeeded)
            {
                return(RedirectToAction(nameof(AccountController.ResetPasswordConfirmation), "Account"));
            }
            AddErrors(result);
            return(View());
        }
Example #16
0
        public async Task <IActionResult> OnGetAsync(string userId, string code)
        {
            if (userId == null || code == null)
            {
                return(RedirectToPage("/Index"));
            }

            var user = await _userManager.FindByIdAsync(userId);

            if (user == null)
            {
                return(NotFound($"Unable to load user with ID '{userId}'."));
            }

            code = Encoding.UTF8.GetString(WebEncoders.Base64UrlDecode(code));
            var result = await _userManager.ConfirmEmailAsync(user, code);

            StatusMessage = result.Succeeded ? "Udało się zaakceptować konto." : "Nie udało się zaakceptować konta.";

            TempData["CheckConfirm"] = StatusMessage.ToString();

            return(RedirectToPage("/Account/Login", new { area = "Identity" }));
        }
        public async Task <IActionResult> SignUpConfirmEmail(string userId, string code)
        {
            AccountSignUpConfirmEmailViewModel model = new AccountSignUpConfirmEmailViewModel();

            if (userId == null || code == null)
            {
                return(RedirectToAction("Index", "Home"));
            }

            var user = await UserManager.FindByIdAsync(userId);

            if (user == null)
            {
                return(NotFound($"Unable to load user with ID '{userId}'."));
            }

            code = Encoding.UTF8.GetString(WebEncoders.Base64UrlDecode(code));
            var result = await UserManager.ConfirmEmailAsync(user, code);

            model.StatusMessage = result.Succeeded ? "Thank you for confirming your email." : "Error confirming your email.";

            return(View(model));
        }
Example #18
0
        public async Task <IActionResult> OnGetAsync(string userId, string code)
        {
            if (userId == null || code == null)
            {
                return(RedirectToPage("/Index"));
            }

            var user = await _userManager.FindByIdAsync(userId);

            if (user == null)
            {
                return(NotFound($"Unable to load user with ID '{userId}'."));
            }

            UserId = userId;

            //confirm user (workshop) email
            code = Encoding.UTF8.GetString(WebEncoders.Base64UrlDecode(code));
            var result = await _userManager.ConfirmEmailAsync(user, code);

            StatusMessage = result.Succeeded ? "Thank you for confirming your email." : "Error confirming your email.";
            return(Page());
        }
Example #19
0
        public async Task <IActionResult> ResetPassword(ResetPasswordModel model)
        {
            if (ModelState.IsValid)
            {
                var user = await _manager.FindByIdAsync(model.Id);

                if (user == null)
                {
                    return(NotFound());
                }

                var newToken    = WebEncoders.Base64UrlDecode(model.Token);
                var encodeToken = Encoding.UTF8.GetString(newToken);

                var result = await _manager.ResetPasswordAsync(user, encodeToken, model.Password);

                if (result.Succeeded)
                {
                    return(Ok());
                }
            }
            return(BadRequest());
        }
Example #20
0
        public async Task <IActionResult> ResetPassword([FromBody] ResetPasswordModel resetPasswordModel)
        {
            if (ModelState.IsValid)
            {
                var user = await UserManager.FindByNameAsync(resetPasswordModel.Username);

                var token          = System.Text.Encoding.ASCII.GetString(WebEncoders.Base64UrlDecode(resetPasswordModel.Token));
                var identityResult = await this.UserManager.ResetPasswordAsync(user, token, resetPasswordModel.Password);

                if (identityResult.Succeeded)
                {
                    this.CacheManager.ClearRegion(EntityControllerBase.ControllerCacheRegionUrn);
                    await SignInManager.SignInAsync(user, isPersistent : false);

                    var avatarUrl = $"{ this.RoadieHttpContext.ImageBaseUrl }/user/{ user.RoadieId }/{ this.RoadieSettings.ThumbnailImageSize.Width }/{ this.RoadieSettings.ThumbnailImageSize.Height }";
                    var t         = await this.TokenService.GenerateToken(user, this.UserManager);

                    return(Ok(new
                    {
                        Username = user.UserName,
                        RecentLimit = user.RecentlyPlayedLimit,
                        user.RemoveTrackFromQueAfterPlayed,
                        user.Email,
                        user.LastLogin,
                        avatarUrl,
                        Token = t,
                        user.Timeformat,
                        user.Timezone
                    }));
                }
                else
                {
                    return(BadRequest(identityResult.Errors));
                }
            }
            return(BadRequest(ModelState));
        }
Example #21
0
        public async Task <IActionResult> ConfirmEmail([FromBody] EmailConfirmationDTO emailConfirmation)
        {
            try
            {
                if (!ModelState.IsValid)
                {
                    _logger.LogTrace("Email confirmation failed due to missing parameters.", emailConfirmation);
                    return(BadRequest("Confirmation details required."));
                }

                var user = await _unitOfWork.UserManager.FindByIdAsync(emailConfirmation.UserId).ConfigureAwait(false);

                if (user == null)
                {
                    _logger.LogWarning("Email confirmation attempted with bad user ID.");
                    return(StatusCode(500, "Email confirmation unsuccessful."));
                }

                emailConfirmation.Token = Encoding.UTF8.GetString(WebEncoders.Base64UrlDecode(emailConfirmation.Token));
                var result = await _unitOfWork.UserManager.ConfirmEmailAsync(user, emailConfirmation.Token).ConfigureAwait(false);

                if (!result.Succeeded)
                {
                    _logger.LogInformation("Email confirmation failed due to invalid code.");
                    return(BadRequest("Email confirmation failed: validation code invalid."));
                }

                _logger.LogInformation($"Email confirmation succeeded for {user.UserName}.");

                return(NoContent());
            }
            catch (Exception ex)
            {
                _logger.LogError(ex, "Exception thrown attempting to confirm email.");
                return(StatusCode(500, "Email confirmation unsuccessful."));
            }
        }
Example #22
0
        public async Task <RespostaViewModel> ConfirmarEmailAsync(string userId, string token)
        {
            var usuario = await userManager.FindByIdAsync(userId);

            if (usuario == null)
            {
                return(new RespostaViewModel
                {
                    Mensagem = "Não foi possível confirmar o email.",
                    Objeto = null,
                    Success = false
                });
            }

            var decodedToken = WebEncoders.Base64UrlDecode(token);

            string normalToken = Encoding.UTF8.GetString(decodedToken);

            var result = await userManager.ConfirmEmailAsync(usuario, normalToken);

            if (result.Succeeded)
            {
                return(new RespostaViewModel
                {
                    Mensagem = "E-mail confirmado com sucesso!",
                    Objeto = null,
                    Success = true
                });
            }

            return(new RespostaViewModel
            {
                Mensagem = "Erro! O e-mail não foi confirmado.",
                Objeto = null,
                Success = false
            });
        }
Example #23
0
        public async Task <UserManagerResponse> ConfirmEmailAsync(string userId, string token)
        {
            var user = await _userManger.FindByIdAsync(userId);

            if (user == null)
            {
                return new UserManagerResponse
                       {
                           IsSuccess = false,
                           Message   = "User not found"
                       }
            }
            ;

            var    decodedToken = WebEncoders.Base64UrlDecode(token);
            string normalToken  = Encoding.UTF8.GetString(decodedToken);

            var result = await _userManger.ConfirmEmailAsync(user, normalToken);

            if (result.Succeeded)
            {
                return new UserManagerResponse
                       {
                           Message   = "Email confirmed successfully!",
                           IsSuccess = true,
                       }
            }
            ;

            return(new UserManagerResponse
            {
                IsSuccess = false,
                Message = "Email did not confirm",
                Errors = result.Errors.Select(e => e.Description)
            });
        }
        public IActionResult Get(string id, string parameters)
        {
            if (string.IsNullOrEmpty(id))
            {
                throw new ArgumentNullException("id");
            }

#pragma warning disable CS1701 // Assuming assembly reference matches identity
            var documentUrl        = Encoding.UTF8.GetString(WebEncoders.Base64UrlDecode(id));
            var providerParameters = string.IsNullOrEmpty(parameters) ? string.Empty : Encoding.UTF8.GetString(WebEncoders.Base64UrlDecode(parameters));

            var documentBytes = System.IO.File.ReadAllBytes(@"d:\test\sample.pdf");
#pragma warning restore CS1701 // Assuming assembly reference matches identity

            GetSigningDocumentResponse response = new GetSigningDocumentResponse();

            response.DettachedSignature = null;
            response.Document           = documentBytes;
            response.HashAlgorithm      = HashAlgorithm.Default;
            response.Options            = SignatureFlags.PDFAdESUseParametersInWidget | SignatureFlags.PDFAdESIncludeFontInWidget;
            response.Parameters         = new SignatureParameters();

            response.Parameters.header           = "ÑEÉâññsE(E)EE";
            response.Parameters.signerCaption    = "This \u03C0";
            response.Parameters.signerInfo       = "ÑñÑñÑñÑñ";
            response.Parameters.algorithmCaption = "ÑñÑñÑñÑ";
            response.Parameters.algorithmInfo    = "Ñañañañañañañ";

            response.SignatureProfile = SignatureProfile.PDF;
            response.SignatureType    = SignatureType.Default;

#pragma warning disable CS1701 // Assuming assembly reference matches identity
            return(Ok(response));

#pragma warning restore CS1701 // Assuming assembly reference matches identity
        }
    /// <summary>
    /// Cryptographically unprotects a piece of protected data.
    /// </summary>
    /// <param name="protector">The data protector to use for this operation.</param>
    /// <param name="protectedData">The protected data to unprotect.</param>
    /// <returns>The plaintext form of the protected data.</returns>
    /// <exception cref="System.Security.Cryptography.CryptographicException">
    /// Thrown if <paramref name="protectedData"/> is invalid or malformed.
    /// </exception>
    public static string Unprotect(this IDataProtector protector, string protectedData)
    {
        if (protector == null)
        {
            throw new ArgumentNullException(nameof(protector));
        }

        if (protectedData == null)
        {
            throw new ArgumentNullException(nameof(protectedData));
        }

        try
        {
            byte[] protectedDataAsBytes = WebEncoders.Base64UrlDecode(protectedData);
            byte[] plaintextAsBytes     = protector.Unprotect(protectedDataAsBytes);
            return(EncodingUtil.SecureUtf8Encoding.GetString(plaintextAsBytes));
        }
        catch (Exception ex) when(ex.RequiresHomogenization())
        {
            // Homogenize exceptions to CryptographicException
            throw Error.CryptCommon_GenericError(ex);
        }
    }
Example #26
0
        public void RejectsDamagedTokens(AccessToken accessToken)
        {
            // Arrange
            var factory = CreateFactory();
            var target  = factory.Create(CreateSettings());

            // Act
            var tokenStr      = target.Issue(accessToken);
            var tokenSplitted = tokenStr.Split(".");

            for (int i = 0; i < tokenSplitted.Length; i++)
            {
                var item = tokenSplitted[i];
                var tokenSplittedCopy = tokenSplitted.Clone() as string[];

                var bits = new BitArray(WebEncoders.Base64UrlDecode(item));

                Parallel.For(
                    0,
                    bits.Count,
                    (j) =>
                {
                    var bitsCopy = new BitArray(bits);
                    bitsCopy[j]  = !bitsCopy[j];

                    tokenSplittedCopy[i] = WebEncoders.Base64UrlEncode(bitsCopy.ToByteArray());
                    var invalidToken     = string.Join(".", tokenSplittedCopy);

                    var result = target.TryVerify(invalidToken, out AccessToken actual);

                    // Assert
                    Assert.False(result);
                    Assert.Null(actual);
                });
            }
        }
Example #27
0
        public async Task <ActionResult> ConfirmEmail(string userId, string code)
        {
            if (userId == null || code == null)
            {
                return(BadRequest());
            }

            var user = await _userManager.FindByIdAsync(userId);

            if (user == null)
            {
                return(BadRequest("User Não Existe!"));
            }

            code = Encoding.UTF8.GetString(WebEncoders.Base64UrlDecode(code));
            var result = await _userManager.ConfirmEmailAsync(user, code);

            if (result.Succeeded)
            {
                return(Ok());
            }

            return(BadRequest("Erro"));
        }
            public async Task <UserDto> Handle(Command request, CancellationToken cancellationToken)
            {
                var user = await userManager.FindByIdAsync(userAccessor.GetCurrentUserId());

                if (user == null)
                {
                    return(null);
                }

                var role = await roleAccessor.GetUserRoleAsync(user);

                var tokenBytes   = WebEncoders.Base64UrlDecode(request.RefreshToken);
                var decodedToken = Encoding.UTF8.GetString(tokenBytes);
                var result       = await userAccessor.ConfirmRefreshTokenAsync(user, userManager, decodedToken);

                if (!result.Succeeded)
                {
                    throw new RestException(HttpStatusCode.Unauthorized);
                }

                var newRefreshToken = await userManager.GenerateUserTokenAsync(user, TokenOptions.DefaultProvider, "RefreshToken");

                return(new UserDto(user, role, tokenGenerator, newRefreshToken));
            }
Example #29
0
        /// <summary>
        /// Decrypts the message
        /// </summary>
        public string?Decrypt(string inputText, string key)
        {
            if (string.IsNullOrWhiteSpace(inputText))
            {
                throw new ArgumentNullException(nameof(inputText));
            }

            try
            {
                var inputBytes = WebEncoders.Base64UrlDecode(inputText);
                var bytes      = decrypt(inputBytes, key);
                return(Encoding.UTF8.GetString(bytes));
            }
            catch (FormatException ex)
            {
                _logger.LogError(ex.Demystify(), "Invalid base 64 string. Fall through.");
            }
            catch (CryptographicException ex)
            {
                _logger.LogError(ex.Demystify(), "Invalid protected payload. Fall through.");
            }

            return(null);
        }
        /// <summary>
        /// Decrypts the message
        /// </summary>
        public string Decrypt(string inputText)
        {
            if (inputText == null)
            {
                throw new ArgumentNullException(nameof(inputText));
            }

            try
            {
                var inputBytes = WebEncoders.Base64UrlDecode(inputText);
                var bytes      = _dataProtector.Unprotect(inputBytes);
                return(Encoding.UTF8.GetString(bytes));
            }
            catch (FormatException ex)
            {
                _logger.LogError(ex.Message, "Invalid base 64 string. Fall through.");
            }
            catch (CryptographicException ex)
            {
                _logger.LogError(ex.Message, "Invalid protected payload. Fall through.");
            }

            return(null);
        }