/// <summary> /// Verifies if token from request has access to specified customer. /// </summary> /// <param name="customerId"></param> /// <returns></returns> private async Task <bool> HasAccess(int customerId) { var httpRequest = HttpContext.Current.Request; var action = HttpContext.Current.Request.HttpMethod; var controller = controllerName; var token = httpRequest.GetAuthToken(); if (string.IsNullOrEmpty(token)) { return(false); } var request = new VerifyTokenRequest { Service = HealthLibraryServiceName, Action = action, Controller = controller, Customer = customerId, Id = token }; var parts = token.Split('.'); if (parts.Length == 3) { return(VerifyJwtLocal(token, request)); } else { return(await this.tokenService.VerifyAccess(request)); } }
/// <summary> /// Returns info if token has access to specified service. /// </summary> /// <param name="request"></param> /// <returns></returns> public async Task <VerifyTokenResponse> VerifyToken(VerifyTokenRequest request) { try { return(await _apiClient.SendRequestAsync <VerifyTokenResponse>("api/tokens/{Id}", request, Method.GET)); } catch (ServiceNotFoundException) { return(null); } }
/// <summary> /// Returns true if token has access to specified service. /// </summary> /// <param name="request"></param> /// <returns></returns> public async Task <bool> VerifyAccess(VerifyTokenRequest request) { if (string.IsNullOrEmpty(request.Service)) { throw new ArgumentNullException("request.Service"); } VerifyTokenResponse result = await this.tokenDataProvider.VerifyToken(request); return(result != null && result.Allowed); }
private bool ValidarToken() { var verificaTokenRequest = new VerifyTokenRequest(this.CodigoParceiro, _token.token.idToken); var resposta = this.Cliente.VerifyTokenAsync(verificaTokenRequest).Result; if (DateTime.TryParse(resposta.token.infoToken.validadeToken, out var validadeToken)) { return(validadeToken > DateTime.Now); } return(!(resposta.erro?.Length > 0)); }
private static bool VerifyJwtLocal(string token, VerifyTokenRequest request) { var jwtCustomerKey = ConfigurationManager.AppSettings["JWT_KEY_" + request.Customer.Value] as string; if (jwtCustomerKey == null) { logger.Fatal("JSON Web Token (JWT) was used but [JWT_KEY_{0}] is not set.", request.Customer); return(false); } // Local JWT token var payload = new Dictionary <string, string>(); try { payload = JsonWebToken.DecodeToObject <Dictionary <string, string> >(token, jwtCustomerKey, true); } catch (Exception e) { logger.Error(e, "Error decoding JWT: {0}", token); } var customer = Convert.ToInt32(payload["customer"]); if (request.Customer.Value != customer) { logger.Error("Requested customer {0} does not match token customer {1}.", request.Customer, customer); return(false); } if (!request.Service.Equals(payload["service"], StringComparison.InvariantCultureIgnoreCase)) { logger.Error("Requested service {0} does not match token service {1}.", request.Service, payload["service"]); return(false); } if (!request.Controller.Equals(payload["controller"], StringComparison.InvariantCultureIgnoreCase)) { logger.Error("Requested controller {0} does not match token controller {1}.", request.Service, payload["controller"]); return(false); } if (!request.Action.Equals(payload["action"], StringComparison.InvariantCultureIgnoreCase)) { logger.Error("Requested action {0} does not match token action {1}.", request.Service, payload["action"]); return(false); } return(true); }
/// <inheritdoc /> public override async Task <BooleanReply> VerifyPasswordReset(VerifyTokenRequest request, ServerCallContext context) { var user = await m_userManager.FindByIdAsync(request.UserId).ConfigureAwait(false); if (user is null) { return new BooleanReply { Error = 0, Reply = false } } ; var result = await m_userManager.VerifyUserTokenAsync(user, m_userManager.Options.Tokens.PasswordResetTokenProvider, "ResetPassword", request.Code).ConfigureAwait(false); return(new BooleanReply { Error = 0, Reply = result }); }
/// <inheritdoc /> public override async Task <BooleanReply> VerifyEmail(VerifyTokenRequest request, ServerCallContext context) { m_logger.LogDebug("Received email verification request for {0}", request.UserId); var user = await m_userManager.FindByIdAsync(request.UserId).ConfigureAwait(false); if (user is null) { m_logger.LogWarning("Email verification failed as no user exists for {0}", request.UserId); return(new BooleanReply { Error = 404, Reply = false }); } var code = HttpUtility.UrlDecode(request.Code).Replace(' ', '+'); var result = await m_userManager.ConfirmEmailAsync(user, code).ConfigureAwait(false); if (!result.Succeeded) { m_logger.LogWarning("Email verification failed for {0} {1}. Errors: {2}", request.UserId, code, string.Join(", ", result.Errors.Select(err => err.Code))); return(new BooleanReply { Error = 404, Reply = false }); } m_logger.LogInformation("Email verified for {0}", request.UserId); return(new BooleanReply { Error = 0, Reply = true }); }
public async Task <object> VerifyToken([FromBody] VerifyTokenRequest requestBody) { var metadataUrl = $"https://login.microsoftonline.com/{config["Oidc:TenantId"]}/.well-known/openid-configuration"; var tokenParts = requestBody.token.Split("."); var(header, payload) = GetTokenParts(requestBody.token); // No need for verification if token not signed. if (string.IsNullOrEmpty(tokenParts.ElementAtOrDefault(2)) || (string)header["alg"] == "none") { return(MakeResult(true)); } var signedPart = string.Join('.', tokenParts.Take(2)); var signingInput = Encoding.ASCII.GetBytes(signedPart); var client = clientFactory.CreateClient(); var metadata = JObject.Parse(await client.GetStringAsync(metadataUrl)); var jwks = JObject.Parse(await client.GetStringAsync((string)metadata["jwks_uri"])); var x5c = ( from JObject key in jwks["keys"] as JArray where (key.ContainsKey("kid") && (string)key["kid"] == (string)header["kid"]) || (key.ContainsKey("x5t") && (string)key["x5t"] == (string)header["x5t"]) select(string) key["x5c"][0] ).FirstOrDefault(); var pem = $"-----BEGIN CERTIFICATE-----{Environment.NewLine}" + Regex.Replace(x5c, "(.{64})", $"$1{Environment.NewLine}") + $"{Environment.NewLine}-----END CERTIFICATE-----{Environment.NewLine}"; var cert = new X509Certificate2(rawData: Encoding.ASCII.GetBytes(pem)); var cng = cert.PublicKey.Key as RSACng; var signatureBytes = Convert.FromBase64String(Base64StringFromBase64UrlEncoded(tokenParts[2])); return(MakeResult(cng.VerifyData( data: signingInput, signature: signatureBytes, hashAlgorithm: HashAlgorithmName.SHA256, padding: RSASignaturePadding.Pkcs1 ))); }
public override Task <VerifyTokenReply> VerifyToken(VerifyTokenRequest request, ServerCallContext context) { VerifyTokenReply verifyTokenReply = new VerifyTokenReply(); try { var jwtSecurity2 = new JwtSecurityTokenHandler().ValidateToken(request.Token, tokenValidationParameters, out var securityToken); verifyTokenReply.ResultCode = JwtResultCode.Ok; verifyTokenReply.ResultReply = ResultReplyExtensions.Success(); foreach (var claim in jwtSecurity2.Claims) { verifyTokenReply.Claims.Add(claim.Type, claim.Value); } } catch (Microsoft.IdentityModel.Tokens.SecurityTokenInvalidSignatureException ex) { verifyTokenReply.ResultReply = ResultReplyExtensions.Success(); verifyTokenReply.ResultCode = JwtResultCode.TokenInvalidSignature; } catch (Microsoft.IdentityModel.Tokens.SecurityTokenNoExpirationException ex) { verifyTokenReply.ResultReply = ResultReplyExtensions.Success(); verifyTokenReply.ResultCode = JwtResultCode.TokenExpires; } catch (Exception ex) { verifyTokenReply.ResultReply = ResultReplyExtensions.InnerError(); verifyTokenReply.ResultCode = JwtResultCode.Error; } //await gPSIdentityServerDbContext.AddAsync(new GPS_VerifyToken //{ // Token = token, // ClaimsJson = JsonConvert.SerializeObject(jwtOptionsResultDto.Claims), // ResultCode = (int)jwtOptionsResultDto.ResultCode //}); //await gPSIdentityServerDbContext.SaveChangesAsync(); return(Task.FromResult(verifyTokenReply)); }
/// <summary> /// 验证verifyToken /// </summary> /// <param name="request">请求参数信息</param> /// <returns>请求结果信息</returns> public async Task <VerifyTokenResponse> VerifyToken(VerifyTokenRequest request) { return(await new VerifyTokenExecutor().Client(this).Execute <VerifyTokenResponse, VerifyTokenResult, VerifyTokenRequest>(request).ConfigureAwait(false)); }
/// <summary> /// 验证verifyToken /// </summary> /// <param name="request">请求参数信息</param> /// <returns>请求结果信息</returns> public VerifyTokenResponse VerifyToken(VerifyTokenRequest request) { return(new VerifyTokenExecutor().Client(this).Execute <VerifyTokenResponse, VerifyTokenResult, VerifyTokenRequest>(request)); }
public async Task <ActionResult> VerifyToken([FromBody] VerifyTokenRequest tokenRequest) { return(Ok(new VerifyTokenResponse { Valid = await _authenticationService.ValidateToken(tokenRequest.Token) })); }