public static byte[] FromBase64Url(this string str) { if (string.IsNullOrWhiteSpace(str)) { return(new byte[0]); } return(BASE64URL.Decode(Encoding.UTF8.GetBytes(str))); }
public string ReadJwt(string jwt, string payloadKey = "") { var result = string.Empty; if (jwt.Split('.').Count() != 3) { return(result); } var tokenType = Base64UrlEncoder.Decode(jwt.Split('.').FirstOrDefault()); var typeElement = new JsonElement(); if (JsonDocument.Parse(tokenType).RootElement.TryGetProperty("typ", out typeElement)) { if (typeElement.GetString() == "JWT") { var token = new JwtSecurityTokenHandler().ReadJwtToken(jwt); if (string.IsNullOrEmpty(payloadKey)) { if (token.Payload.Iss.Contains("sts.windows.net")) { result = "microsoft"; } } else { result = token.Payload[payloadKey].ToString(); } } } return(result); }
public ActionResult Callback( string encodedRedirect, [FromQuery(Name = "code")] string code, [FromQuery(Name = "state")] string state, [FromQuery(Name = "session_state")] string sessionState, [FromQuery(Name = "error")] string error, [FromQuery(Name = "error_description")] string errorDescription) { Uri redirectUrl = new Uri(Base64UrlEncoder.Decode(encodedRedirect)); if (!string.IsNullOrEmpty(error)) { return(Redirect($"{redirectUrl.ToString()}?error={error}&error_description={errorDescription}")); } string compoundCode; string newState; try { JObject launchStateParameters = JObject.Parse(Base64UrlEncoder.Decode(state)); JObject launchParameters = JObject.Parse(Base64UrlEncoder.Decode(launchStateParameters["l"].ToString())); launchParameters.Add("code", code); newState = launchStateParameters["s"].ToString(); compoundCode = Base64UrlEncoder.Encode(launchParameters.ToString(Newtonsoft.Json.Formatting.None)); } catch { _logger.LogError("Error parsing launch parameters."); return(BadRequest("Invalid launch context parameters")); } return(Redirect($"{redirectUrl.ToString()}?code={compoundCode}&state={newState}&session_state={sessionState}")); }
public async Task <ConfirmEmailQueryResult> Handle(ConfirmEmailQuery request, CancellationToken cancellationToken) { var user = await _userManager.FindByIdAsync(request.UserId); if (user == null) { throw new DomainException($"User {request.UserId} is not found"); } var decodedToken = Base64UrlEncoder.Decode(request.Token); var result = await _userManager.ConfirmEmailAsync(user, decodedToken); var token = await _userManager.GeneratePasswordResetTokenAsync(user); var encodedToken = Base64UrlEncoder.Encode(token); return(new ConfirmEmailQueryResult { IsSuccess = result.Succeeded, Errors = result.Errors.Select(e => e.Description), ReturnUrl = request.ReturnUrl, ResetPasswordToken = encodedToken }); }
public void Data_of_various_length___roundtrips_correclty_as_string() { var sut = new Base64UrlEncoder(); var bytes = new byte[byte.MaxValue + 1]; for (int i = 0; i < bytes.Length; ++i) { bytes[i] = (byte)(255 - i); } for (int i = 0; i < 256; ++i) { Span <byte> source = bytes.AsSpan(0, i + 1); string encoded = sut.Encode(source); #if NETCOREAPP string encodedExpected = Convert.ToBase64String(source); #else string encodedExpected = Convert.ToBase64String(source.ToArray()); #endif Assert.AreEqual(encodedExpected.ToBase64Url(), encoded); Span <byte> decoded = sut.Decode(encoded.AsSpan()); CollectionAssert.AreEqual(source.ToArray(), decoded.ToArray()); } }
/// <summary> /// 验证身份 验证签名的有效性,(TODO:待优化,需要重构) /// </summary> /// <param name="encodeJwt">转码之后的jwt信息</param> /// <param name="validatePayLoad"></param> /// <returns></returns> public static bool ValidateToken(string encodeJwt, Func <Dictionary <string, object>, bool> validatePayLoad) { var jwtOptions = AppSettingManager.Get <ESoftorJwtOption>("ESoftor:Jwt"); var success = true; var jwtArr = encodeJwt.Split('.'); var header = Base64UrlEncoder.Decode(jwtArr[0]).FromJsonString <Dictionary <string, object> >(); var payLoad = Base64UrlEncoder.Decode(jwtArr[1]).FromJsonString <Dictionary <string, object> >(); var hs256 = new HMACSHA256(Encoding.ASCII.GetBytes(jwtOptions.Secret)); //首先验证签名是否正确(必须的) success = success && string.Equals(jwtArr[2], Base64UrlEncoder.Encode(hs256.ComputeHash(Encoding.UTF8.GetBytes(string.Concat(jwtArr[0], ".", jwtArr[1]))))); if (!success) { return(success);//签名不正确直接返回 } //其次验证是否在有效期内(也应该必须) var now = Convert.ToInt64(DateTime.UtcNow.ToJsGetTime()); success = success && (now >= long.Parse(payLoad["nbf"].ToString()) && now < long.Parse(payLoad["exp"].ToString())); //再其次 进行自定义的验证 success = success && validatePayLoad(payLoad); return(success); }
public async Task <IActionResult> Resetpassword([FromBody] ResetPassword model) { SensateUser user; PasswordResetToken token; user = await this._users.GetByEmailAsync(model.Email).AwaitBackground(); token = this._passwd_tokens.GetById(model.Token); if (user == null) { return(this.NotFound()); } if (token == null) { return(InvalidInputResult("Security token invalid!")); } token.IdentityToken = Base64UrlEncoder.Decode(token.IdentityToken); var result = await this._manager.ResetPasswordAsync(user, token.IdentityToken, model.Password).AwaitBackground(); if (result.Succeeded) { return(this.Ok()); } var error = result.Errors.First(); return(error != null?InvalidInputResult(error.Description) : new NotFoundObjectResult(new { Message = result.Errors })); }
public JWTAuthenticationToken GetNewAccessTokenFromRefreshToken(string refreshToken, ApplicationDbContext ctx) { JwtSecurityToken token = ValidateToken(refreshToken); if (token == null) { throw new BlogException("tokenInvalid", new string[] { token.ToString() }); } string hashedUserId = token.Claims.First((c) => c.Type == ClaimTypes.NameIdentifier).Value; string UserId = Base64UrlEncoder.Decode(hashedUserId); var query = (from a in ctx.User where a.UserId == UserId select a); if (query.Count() == 0) { throw new BlogException("userNotFound", new string[] { UserId }); } else { User u = query.First(); string newToken = CreateAccessToken(u.UserName, UserId, u.UserRole); string newRefreshToken = CreateRefreshToken(UserId); JWTAuthenticationToken newAuthToken = new JWTAuthenticationToken(); newAuthToken.Token = newToken; newAuthToken.RefreshToken = newRefreshToken; newAuthToken.User = u; return(newAuthToken); } }
public PasetoToken(string token) { if (string.IsNullOrWhiteSpace(token)) { throw new ArgumentNullException(nameof(token)); } var tokenParts = token.Split(new[] { '.' }, PasetoConstants.MaxPasetoSegmentCount + 1); if (tokenParts.Length != 3 && tokenParts.Length != 4) { throw new ArgumentException("Invalid number of token segments"); } RawToken = token; Version = tokenParts[0]; Purpose = tokenParts[1]; EncodedPayload = tokenParts[2]; if (tokenParts.Length == 4) { EncodedFooter = tokenParts[3]; Footer = Base64UrlEncoder.Decode(EncodedFooter); } }
private async Task <User> LoginViaFacebook(string auth) { using (AppDBContext _context = new AppDBContext()) { User user = null; string secret = "7d94069605af1505a9f71c57fed00868"; HMACSHA256 sha256 = new HMACSHA256(Encoding.ASCII.GetBytes(secret)); dynamic obj = JsonConvert.DeserializeObject(auth); string email = obj.email; string social = obj.facebook; string encodedSignature = social.Split('.')[0]; string payload = social.Split('.')[1]; string signature = Base64UrlEncoder.Decode(encodedSignature); string expectedSignature = Encoding.UTF8.GetString(sha256.ComputeHash(Encoding.ASCII.GetBytes(payload))); if (signature == expectedSignature) { user = await _context.Users.Include(u => u.Information) .ThenInclude(i => i.Rating) .SingleOrDefaultAsync(u => u.Email == email); user.GradeRating = user.Information.Rating.Grade; user.CountRating = user.Information.Rating.Count; user.Online = true; user.Reason = User.AUTHORIZATION_SUCCESS; await _context.SaveChangesAsync(); } return(user); } }
// Проверить токен public string checkToken(string token) { string json = Base64UrlEncoder.Decode(token); // Дессериализация из JSON в объект MyToken tok; try{ tok = ser.Deserialize <MyToken>(json); } catch { tok = null; } if (tok == null) { return("Неверный токен"); } // Если токен провалидировался, создаём сессию и вернём его на просмотр (для отладки) if (tok.checkSumm(tokenKey)) { setUserSession(true, tok.userId, tok.login); return(json); } else { return(""); // Иначе вернём пустую строку } }
public async Task <ActionResult> ResetPassword( [FromRoute] long id, [FromBody] ResetPasswordModel model ) { try { model.Password = Base64UrlEncoder.Decode(model.Password); model.ConfirmPassword = Base64UrlEncoder.Decode(model.ConfirmPassword); var user = await userMgr.FindByIdAsync(id.ToString()); if (user == null) { return(NotFound()); } var token = await userMgr.GeneratePasswordResetTokenAsync(user); var result = await userMgr.ResetPasswordAsync( user, token, model.Password ); if (result.Succeeded) { return(Ok()); } return(BadRequest(result.GetErrorsString())); } catch (Exception ex) { logger.LogError(ex, $"Can not reset password for user {id} with {model.ToJson()}"); return(this.InternalServerError(ex)); } }
/// <summary> /// Extracts a JWT from the supplied Http headers and creates a token object from it. /// </summary> /// <param name="headerDictionary">The Http headers</param> /// <param name="headerName">The header key name used. Default: "Authorization"</param> /// <returns>The deserialised Token or null</returns> /// <exception cref="System.ArgumentNullException">If the headerDictionary is null, or the header name is empty.</exception> public Token Create(IHeaderDictionary headerDictionary, string headerName = ITokenFactory.DefaultHeaderName) { if (headerDictionary is null) { throw new ArgumentNullException(nameof(headerDictionary)); } if (string.IsNullOrEmpty(headerName)) { throw new ArgumentNullException(headerName); } var encodedStringValueToken = headerDictionary[headerName]; if (encodedStringValueToken.Count == 0) { return(null); } var encodedString = encodedStringValueToken.ToArray().First().Replace("Bearer ", "", StringComparison.CurrentCultureIgnoreCase); var handler = new JwtSecurityTokenHandler(); var jwtToken = handler.ReadJwtToken(encodedString); var decodedPayload = Base64UrlEncoder.Decode(jwtToken.EncodedPayload); return(JsonConvert.DeserializeObject <Token>(decodedPayload)); }
private object GetGameOrError(string token) { string decodedToken = ""; try { decodedToken = Base64UrlEncoder.Decode(token); } catch { return(StatusCode(404, "Game not found")); } Speler authenticatedUser = _authService.Get(); Spel game = _spelService.GetSpel(decodedToken); if (game == null) { return(StatusCode(404, "Game not found")); } if (authenticatedUser == null || (game.Speler1Token == decodedToken && game.Speler1.Id != authenticatedUser.Id) || (game.Speler2Token == decodedToken && game.Speler2.Id != authenticatedUser.Id)) { return(StatusCode(401, "You do not have access to this game.")); } return(game); }
public override void OnActionExecuting(ActionExecutingContext context) { try { string token = context.HttpContext.Request.Headers["Authorization"]; if (JwtManager.Verify(token)) { // get email var body = JsonConvert.DeserializeAnonymousType ( Base64UrlEncoder.Decode(token.Split('.')[1]), new { email = String.Empty } ); context.ActionArguments.Add("email", body.email); } else { Reject(context); } } catch (Exception e) { Reject(context); } }
public async Task <ActionResult> ChangePassword([FromBody] ChangePasswordModel model) { var userId = User.GetUserId(); var user = await userMgr.FindByIdAsync(userId); if (user == null) { return(Forbid()); } try { model.CurrentPassword = Base64UrlEncoder.Decode(model.CurrentPassword); model.NewPassword = Base64UrlEncoder.Decode(model.NewPassword); model.ConfirmPassword = Base64UrlEncoder.Decode(model.ConfirmPassword); var isValid = await userMgr.CheckPasswordAsync(user, model.CurrentPassword); if (!isValid) { return(BadRequest("Invalid current password!")); } var result = await userMgr.ChangePasswordAsync(user, model.CurrentPassword, model.NewPassword); if (result.Succeeded) { return(Ok()); } return(BadRequest(result.Errors)); } catch (Exception ex) { logger.LogError(ex, $"Can not change password for user {user.UserName} with {model.ToJson()} ."); return(this.InternalServerError(ex)); } }
public IActionResult Move(string token, [FromBody] Coordinate coordinate) { var spelOrError = GetGameOrError(token); if (!(spelOrError is Spel)) { return((IActionResult)spelOrError); } Spel spel = (Spel)spelOrError; string decodedToken = Base64UrlEncoder.Decode(token); bool isPlayer1 = spel.Speler1Token == decodedToken; bool isTurn = (spel.Speler1Beurt && isPlayer1) || (!spel.Speler1Beurt && !isPlayer1); if (!isTurn) { return(StatusCode(401, "Not your turn.")); } if (!spel.Afgelopen()) { spel.DoeZet(coordinate.X, coordinate.Y); } _spelService.UpdateSpel(spel); return(Ok()); }
/// <summary> /// Decodes the string into the header, payload and signature. /// </summary> /// <param name="tokenParts">the tokenized string.</param> /// <param name="rawData">the original token.</param> private void Decode(string[] tokenParts, string rawData) { LogHelper.LogInformation(LogMessages.IDX14106, rawData); if (!JsonWebTokenManager.RawHeaderToJObjectCache.TryGetValue(tokenParts[0], out var header)) { try { Header = JObject.Parse(Base64UrlEncoder.Decode(tokenParts[0])); JsonWebTokenManager.RawHeaderToJObjectCache.TryAdd(tokenParts[0], Header); } catch (Exception ex) { throw LogHelper.LogExceptionMessage(new ArgumentException(LogHelper.FormatInvariant(LogMessages.IDX14102, tokenParts[0], rawData), ex)); } } else { Header = header; } if (tokenParts.Length == JwtConstants.JweSegmentCount) { DecodeJwe(tokenParts); } else { DecodeJws(tokenParts); } EncodedToken = rawData; }
/// <summary> /// 校验 /// </summary> /// <param name="encodeJwt">加密后的Jwt令牌</param> /// <param name="options">Jwt选项配置</param> /// <param name="validatePayload">校验负载</param> public bool Validate(string encodeJwt, JwtOptions options, Func <IDictionary <string, string>, JwtOptions, bool> validatePayload) { if (string.IsNullOrWhiteSpace(options.Secret)) { throw new ArgumentNullException(nameof(options.Secret), $@"{nameof(options.Secret)}为Null或空字符串。请在""appsettings.json""配置""{nameof(JwtOptions)}""节点及其子节点""{nameof(JwtOptions.Secret)}"""); } var jwtArray = encodeJwt.Split('.'); if (jwtArray.Length < 3) { return(false); } var header = JsonHelper.ToObject <Dictionary <string, string> >(Base64UrlEncoder.Decode(jwtArray[0])); var payload = JsonHelper.ToObject <Dictionary <string, string> >(Base64UrlEncoder.Decode(jwtArray[1])); // 首先验证签名是否正确 var hs256 = new HMACSHA256(Encoding.UTF8.GetBytes(options.Secret)); var sign = Base64UrlEncoder.Encode( hs256.ComputeHash(Encoding.UTF8.GetBytes(string.Concat(jwtArray[0], ".", jwtArray[1])))); // 签名不正确直接返回 if (!string.Equals(jwtArray[2], sign)) { return(false); } // 其次验证是否在有效期内 //var now = ToUnixEpochDate(DateTime.UtcNow); //if (!(now >= long.Parse(payload["nbf"].ToString()) && now < long.Parse(payload["exp"].ToString()))) // return false; // 进行自定义验证 return(validatePayload(payload, options)); }
public static string DecryptString(string cipherText, string keyString = DefaultEncryptionKey) { var fullCipher = Convert.FromBase64String(Base64UrlEncoder.Decode(cipherText)); var iv = new byte[16]; var cipher = new byte[16]; Buffer.BlockCopy(fullCipher, 0, iv, 0, iv.Length); Buffer.BlockCopy(fullCipher, iv.Length, cipher, 0, iv.Length); var key = Encoding.UTF8.GetBytes(keyString); using (var aesAlg = Aes.Create()) { using (var decryptor = aesAlg.CreateDecryptor(key, iv)) { string result; aesAlg.Padding = PaddingMode.Zeros; using (var msDecrypt = new MemoryStream(cipher)) { using (var csDecrypt = new CryptoStream(msDecrypt, decryptor, CryptoStreamMode.Read)) { using (var srDecrypt = new StreamReader(csDecrypt)) { result = srDecrypt.ReadToEnd(); } } } return(result); } } }
/// <summary> /// 每次请求更新Token /// </summary> /// <param name="headeAuthorization"></param> /// <returns></returns> public string RefreshJWTToken(string headeAuthorization) { try { if (string.IsNullOrEmpty(headeAuthorization)) { return(string.Empty); } if (headeAuthorization.Split("Bearer ").Length < 2) { return(string.Empty); } var tokens = headeAuthorization.Split("Bearer ")[1].Trim().Split('.'); // 获取JWT段 if (tokens.Length < 3) { return(string.Empty); } var payLoad = Base64UrlEncoder.Decode(tokens[1]); var dict = JsonConvert.DeserializeObject <Dictionary <string, string> >(payLoad); var userId = int.TryParse(dict[ClaimTypes.UserData], out _) ? int.Parse(dict[ClaimTypes.UserData]) : 0; if (userId <= 0) { return(string.Empty); } return(GetToken(new UserInfo { UserId = userId })); } catch (Exception ex) { throw ex; } }
public async Task <IActionResult> CallbackLink() { // read external identity from the temporary cookie var result = await HttpContext.AuthenticateAsync(IdentityServerConstants.ExternalCookieAuthenticationScheme); if (result?.Succeeded != true) { throw new Exception("External authentication error"); } if (_logger.IsEnabled(LogLevel.Debug)) { var externalClaims = result.Principal.Claims.Select(c => $"{c.Type}: {c.Value}"); _logger.LogDebug("External claims: {@claims}", externalClaims); } // lookup our user and external provider info var(provider, providerUserId, claims) = await FindFromExternalProvider(result); if (HttpContext.User.Identity.IsAuthenticated) { var subject = HttpContext.User.Claims.FirstOrDefault(x => x.Type == JwtClaimTypes.Subject); try { await _localUserService.AddExternalProviderToUser( subject.Value, provider, providerUserId); await _localUserService.SaveChangesAsync(); } catch (DbUpdateException e) { Debug.WriteLine(e.Message); } } // delete temporary cookie used during external authentication await HttpContext.SignOutAsync(IdentityServerConstants.ExternalCookieAuthenticationScheme); // retrieve return URL var returnUrl = Base64UrlEncoder.Decode(result.Properties.Items["returnUrl"]) ?? "~/"; // check if external login is in the context of an OIDC request var context = await _interaction.GetAuthorizationContextAsync(returnUrl); if (context != null) { if (context.IsNativeClient()) { // The client is native, so this change in how to // return the response is for better UX for the end user. return(this.LoadingPage("Redirect", returnUrl)); } } return(Redirect(returnUrl)); }
private static Token GetToken(string jwt) { var handler = new JwtSecurityTokenHandler(); var jwtToken = handler.ReadJwtToken(jwt); var decodedPayload = Base64UrlEncoder.Decode(jwtToken.EncodedPayload); return(JsonConvert.DeserializeObject <Token>(decodedPayload)); }
T IAuthTokenService <T> .GetData(string jwtTokenBase64) { string[] jwt = jwtTokenBase64.Split('.'); string json = Base64UrlEncoder.Decode(jwt[1]); Console.WriteLine("JSon: " + json); return(JsonConvert.DeserializeObject <T>(json)); }
private Guid GetParsedToken(string token) { var base64Token = Base64UrlEncoder.Decode(token); var decodedToken = WebUtility.UrlDecode(base64Token); var parsedToken = Guid.Parse(decodedToken); return(parsedToken); }
public static TokenRequestState ParseFrom(string serialized) { //ToDo(RD-2410): Remove WebUtility.UrlEncode call. It's only for backward compatibility with the old Token Request Flow. var urlDecoded = WebUtility.UrlDecode(serialized); var json = Base64UrlEncoder.Decode(urlDecoded); return(JsonConvert.DeserializeObject <TokenRequestState>(json)); }
private static JObject ExtractJoseBody(Task <AzureOperationResponse <object> > serviceCallResult) { string[] joseParts = (serviceCallResult.Result.Body as string).Split('.'); var decodedBody = Base64UrlEncoder.Decode(joseParts[1]); JObject jsonBody = JObject.Parse(decodedBody); return(jsonBody); }
/// <summary> /// Decodes the Base64 pagination token. /// </summary> /// <param name="rawToken">The Base64 token value</param> /// <returns>The decoded token</returns> public static string DecodeToken(string token) { if (string.IsNullOrWhiteSpace(token)) { return(null); } return(Base64UrlEncoder.Decode(token)); }
public void Empty_input_decode_from_string___empty_array() { var sut = new Base64UrlEncoder(); string encoded = string.Empty; byte[] actual = sut.Decode(encoded.AsSpan()); Assert.AreEqual(Array.Empty <byte>(), actual); }
/// <summary> /// Parses a JWT. /// </summary> /// <param name="jwt">JWT string</param> /// <returns>The parsed JWTPayload</returns> public static JWTPayload Parse(string jwt) { var splitted = jwt.Split('.'); var payload = splitted[1]; var plainPayload = Base64UrlEncoder.Decode(payload); return(JWTPayload.Parse(plainPayload)); }