public DiagnosticsViewModel(AuthenticateResult result) { AuthenticateResult = result; if (result.Properties.Items.ContainsKey("client_list")) { var encoded = result.Properties.Items["client_list"]; var bytes = Base64Url.Decode(encoded); var value = Encoding.UTF8.GetString(bytes); Clients = JsonConvert.DeserializeObject <string[]>(value); } }
/// <summary> /// Initializes a new instance of the <see cref="DiagnosticsViewModel"/> class. /// </summary> /// <param name="result">The result.</param> public DiagnosticsViewModel(AuthenticateResult result) { AuthenticateResult = result; if (result?.Properties.Items.ContainsKey(_clientList) == true) { string?encoded = result?.Properties.Items[_clientList]; byte[]? bytes = Base64Url.Decode(encoded); string?value = Encoding.UTF8.GetString(bytes); Clients = JsonConvert.DeserializeObject <string[]>(value); } }
public async Task TestFido2AssertionWithExistingU2fRegistrationWithAppId() { // u2f registration with appId var appId = "https://localhost:44336"; var keyHandleData = Base64Url.Decode("2uzGTqu9XGoDQpRBhkv3qDYWzEEZrDjOHT94fHe3J9VXl6KpaY6jL1C4gCAVSBCWZejOn-EYSyXfiG7RDQqgKw"); var publicKeyData = Base64Url.Decode("BEKJkJiDzo8wlrYbAHmyz5a5vShbkStO58ZO7F-hy4fvBp6TowCZoV2dNGcxIN1yT18799bb_WuP0Yq_DSv5a-U"); //key as cbor var publicKey = CreatePublicKeyFromU2fRegistrationData(keyHandleData, publicKeyData); var options = new AssertionOptions { Challenge = Base64Url.Decode("mNxQVDWI8+ahBXeQJ8iS4jk5pDUd5KetZGVOwSkw2X0"), RpId = "localhost", AllowCredentials = new[] { new PublicKeyCredentialDescriptor { Id = keyHandleData, Type = PublicKeyCredentialType.PublicKey } }, Extensions = new AuthenticationExtensionsClientInputs { AppID = appId } }; var authResponse = new AuthenticatorAssertionRawResponse { Id = keyHandleData, RawId = keyHandleData, Type = PublicKeyCredentialType.PublicKey, Extensions = new AuthenticationExtensionsClientOutputs { AppID = true }, Response = new AuthenticatorAssertionRawResponse.AssertionResponse { AuthenticatorData = Base64Url.Decode("B6_fPoU4uitIYRHXuNfpbqt5mrDWz8cp7d1noAUrAucBAAABTQ"), ClientDataJson = Base64Url.Decode("eyJjaGFsbGVuZ2UiOiJtTnhRVkRXSTgtYWhCWGVRSjhpUzRqazVwRFVkNUtldFpHVk93U2t3MlgwIiwib3JpZ2luIjoiaHR0cHM6Ly9sb2NhbGhvc3Q6NDQzMzYiLCJ0eXBlIjoid2ViYXV0aG4uZ2V0In0"), Signature = Base64Url.Decode("MEQCICHV36RVY9DdFmKZgxF5Z_yScpPPsKcj__8KcPmngtGHAiAq_SzmTY8rZz4-5uNNiz3h6xO9osNTh7O7Mjqtoxul8w") } }; var fido2 = new Fido2(new Fido2Configuration()); var res = await fido2.MakeAssertionAsync(authResponse, options, "https://localhost:44336", publicKey.EncodeToBytes(), 0, null); Assert.Equal("ok", res.Status); }
public async Task logout_should_invoke_back_channel_logout() { _mockPipeline.BackChannelMessageHandler.OnInvoke = async req => { req.RequestUri.ToString().Should().StartWith("https://client3/signout"); var form = await req.Content.ReadAsStringAsync(); form.Should().Contain(OidcConstants.BackChannelLogoutRequest.LogoutToken); var token = form.Split('=')[1]; var parts = token.Split('.'); parts.Length.Should().Be(3); var bytes = Base64Url.Decode(parts[1]); var json = Encoding.UTF8.GetString(bytes); var payload = JObject.Parse(json); payload["iss"].ToString().Should().Be("https://server"); payload["sub"].ToString().Should().Be("bob"); payload["aud"].ToString().Should().Be("client3"); payload["iat"].Should().NotBeNull(); payload["jti"].Should().NotBeNull(); payload["sid"].Should().NotBeNull(); payload["events"].Type.Should().Be(JTokenType.Object); var events = (JObject)payload["events"]; events.Count.Should().Be(1); events["http://schemas.openid.net/event/backchannel-logout"].Should().NotBeNull(); events["http://schemas.openid.net/event/backchannel-logout"].Type.Should().Be(JTokenType.Object); var evt = (JObject)events["http://schemas.openid.net/event/backchannel-logout"]; evt.Count.Should().Be(0); }; await _mockPipeline.LoginAsync("bob"); var response = await _mockPipeline.RequestAuthorizationEndpointAsync( clientId : "client3", responseType : "id_token", scope : "openid", redirectUri : "https://client3/callback", state : "123_state", nonce : "123_nonce"); response.Should().NotBeNull(); await _mockPipeline.BrowserClient.GetAsync(IdentityServerPipeline.EndSessionEndpoint); var signoutFrameUrl = _mockPipeline.LogoutRequest.SignOutIFrameUrl; await _mockPipeline.BrowserClient.GetAsync(signoutFrameUrl); }
private async Task BuildViewModelAsync() { var result = await this.HttpContext.AuthenticateAsync(); this.AuthenticateResult = result; if (result.Properties.Items.ContainsKey("client_list")) { var encoded = result.Properties.Items["client_list"]; var bytes = Base64Url.Decode(encoded); var value = Encoding.UTF8.GetString(bytes); this.Clients = JsonConvert.DeserializeObject <string[]>(value); } }
public void Retrieve() { string value; _httpContextAccessor.HttpContext.Request.Cookies.TryGetValue(CookieName, out value); if (!string.IsNullOrEmpty(value)) { var bytes = Base64Url.Decode(value); bytes = _protector.Unprotect(bytes); var json = Encoding.UTF8.GetString(bytes); var dict = JsonConvert.DeserializeObject <Dictionary <string, bool> >(json); _challengeQuestions = dict; } }
public static string ParseAccessToken(string token) { if (token == null) { return(null); } var parts = token.Split('.'); return(string.Join("\n", parts.Take(2) .Select(x => Base64Url.Decode(x)) .Select(x => JObject.Parse(Encoding.UTF8.GetString(x, 0, x.Length)).ToString(Formatting.Indented)) )); }
private string ParseJwt(string token) { if (!token.Contains(".")) { return(token); } var parts = token.Split('.'); var part = Encoding.UTF8.GetString(Base64Url.Decode(parts[1])); var jwt = JObject.Parse(part); return(jwt.ToString()); }
private string RenderClaims(IHeaderDictionary dictionary) { string result = ""; if (dictionary.ContainsKey("X-Amzn-Oidc-Accesstoken")) { JsonWebTokenHandler handler = new JsonWebTokenHandler(); string unformattedToken = dictionary["X-Amzn-Oidc-Accesstoken"]; var e = Base64Url.Decode("AQAB"); var n = Base64Url.Decode("n7ESj7VfHUenYOlolv-WJeYwByj5_PM5oeO3dL8V9zjvlQWn_UVR5iks76_eRutv4ZbgC2X73ZYO697eYnU4aQ0_qwW-kh8yoRGObxpQgCfky3UpeegLhiLrUlpN40u755rn4IERvyIHe1ifjk-li-O6DEVj9C3Q7ZH0TrWFnpi8MHhHKuN-3QC_TxKxQk8MOGxVZHhfQQkVE9BQVV79d56DBdlCd19XGJGajuGsJlUIcNj-mKeYvHIpQwpDkxSe8gNmBnR4KSdQRxv8cjYEbRVx6LToSVw3x5GmukqRpKKRwkx8oGBPiMG8-N9wm265GTFi9czyu4K594sg6BzpFw"); var rsaKey = new RsaSecurityKey(new RSAParameters { Exponent = e, Modulus = n }) { KeyId = "e87b6d98a03df7a9e44551a18308c24a" }; TokenValidationParameters parameters = new TokenValidationParameters { ValidIssuer = "https://auth.yrudakova.name", ValidAudiences = new List <string> { "https://auth.yrudakova.name/resources" }, ValidateIssuerSigningKey = true, ValidateIssuer = true, ValidateLifetime = true, ValidateAudience = true, IssuerSigningKeys = new List <SecurityKey> { rsaKey } }; SecurityToken token; var rslt = handler.ValidateToken(unformattedToken, parameters); if (!rslt.IsValid) { throw rslt.Exception; } var jwt = handler.ReadJsonWebToken(unformattedToken); result += RenderClaims(jwt.Claims); } return(result); }
/// <summary> /// Used to create a CngKey that can be used to verify JWT content. /// </summary> /// <param name="clientPubKeyString"></param> /// <returns></returns> public static CngKey ImportECDsaCngKeyFromString(string clientPubKeyString) { byte[] clientPublicKeyBlob = Base64Url.Decode(clientPubKeyString); byte[] key = clientPublicKeyBlob.Skip(23).ToArray(); var keyType = new byte[] { 0x45, 0x43, 0x53, 0x33 }; var keyLength = new byte[] { 0x30, 0x00, 0x00, 0x00 }; var keyImport = keyType.Concat(keyLength).Concat(key.Skip(1)).ToArray(); var cngKey = CngKey.Import(keyImport, CngKeyBlobFormat.EccPublicBlob); var crypto = new ECDsaCng(cngKey); return(crypto.Key); }
private static RSA GetPublicRsaKeyFromJwk(JsonWebKey jwk) { var e = Base64Url.Decode(jwk.E); var n = Base64Url.Decode(jwk.N); var rsaKey = RSA.Create(); var keyParams = new RSAParameters { Exponent = e, Modulus = n, }; rsaKey.ImportParameters(keyParams); return(rsaKey); }
public string Get(string token) { string json = JWT.Decode(token, Base64Url.Decode("secert"), JwsAlgorithm.HS256); var headers = Jose.JWT.Headers(token); var payload = Jose.JWT.Payload(token); //step 1b: lookup validation key based on header info JObject Robj = JObject.Parse(json); var aa = Robj["sub"]; //ActionExecutingContext return("value"); }
/// <inheritdoc/> public void RevokeCertificate(JsonWebKey key, RevokeCertificate @params) { var x509 = new X509Certificate2(Base64Url.Decode(@params.Certificate)); throw new NotImplementedException($"Not implemented method {nameof(RevokeCertificate)}"); // todo see https://tools.ietf.org/html/rfc8555#section-7.6 // The server MUST also consider a revocation request valid if it is // signed with the private key corresponding to the public key in the // certificate. //var order = GetByCertificate(accountId, x509); //RevokeCertificate(order, @params.Reason); }
public ClaimsViewModel(AuthenticateResult authenticateResult, bool isLocallyRequested) { AuthenticateResult = authenticateResult; if (authenticateResult.Properties.Items.ContainsKey("client_list")) { var encoded = authenticateResult.Properties.Items["client_list"]; var bytes = Base64Url.Decode(encoded); var value = Encoding.UTF8.GetString(bytes); Clients = JsonConvert.DeserializeObject <string[]>(value); } IsLocallyRequested = isLocallyRequested; }
/// <summary> /// Initializes a new instance of the <see cref="AttestationToken"/> class. /// </summary> /// <param name="token">string JWT to initialize.</param> internal AttestationToken(string token) { _token = token; string[] decomposedToken = token.Split('.'); if (decomposedToken.Length != 3) { throw new ArgumentException("JSON Web Tokens must have 3 components delimited by '.' characters."); } TokenHeaderBytes = Base64Url.Decode(decomposedToken[0]); TokenBodyBytes = Base64Url.Decode(decomposedToken[1]); TokenSignatureBytes = Base64Url.Decode(decomposedToken[2]); _options.Converters.Add(new PolicyResultConverter()); _options.Converters.Add(new AttestationResultConverter()); }
public bool TryRead(string cookieName, out string value) { string storedValue; _httpContextAccessor.HttpContext.Request.Cookies.TryGetValue(cookieName, out storedValue); if (!string.IsNullOrEmpty(storedValue)) { var bytes = Base64Url.Decode(storedValue); bytes = _protector.Unprotect(bytes); value = Encoding.UTF8.GetString(bytes); return(true); } value = null; return(false); }
void IJsonDeserializable.ReadProperties(JsonElement json) { foreach (JsonProperty prop in json.EnumerateObject()) { switch (prop.Name) { case KeyIdPropertyName: KeyId = prop.Value.GetString(); break; case KeyPropertyName: Key = Base64Url.Decode(prop.Value.GetString()); break; } } }
public void FromJson(string crvName, string json) { // https://tools.ietf.org/html/rfc7517#appendix-A.1 var key = Jwk.FromJson(json); Assert.NotNull(key); var jwk = Assert.IsType <ECJwk>(key); Assert.Equal("1", jwk.Kid.ToString()); Assert.True(JwkUseValues.Enc.Equals(jwk.Use)); Assert.Equal(crvName, jwk.Crv.Name.ToString()); Assert.Equal(jwk.X.ToArray(), Base64Url.Decode("MKBCTNIcKUSDii11ySs3526iDZ8AiTo7Tu6KPAqv7D4")); Assert.Equal(jwk.Y.ToArray(), Base64Url.Decode("4Etl6SRW2YiLUrN5vfvVHuhp7x8PxltmWWlbbM4IFyM")); }
public override void FromJson(string json) { // https://tools.ietf.org/html/rfc7517#appendix-A.1 var key = Jwk.FromJson(json); Assert.NotNull(key); var jwk = Assert.IsType <ECJwk>(key); Assert.Equal("1", jwk.Kid); Assert.True(JwkUseNames.Enc.SequenceEqual(jwk.Use)); Assert.Equal(Encoding.UTF8.GetBytes("P-256"), jwk.Crv.Name); Assert.Equal(jwk.X, Base64Url.Decode("MKBCTNIcKUSDii11ySs3526iDZ8AiTo7Tu6KPAqv7D4")); Assert.Equal(jwk.Y, Base64Url.Decode("4Etl6SRW2YiLUrN5vfvVHuhp7x8PxltmWWlbbM4IFyM")); }
private static async Task <ClaimsPrincipal> ValidateJwt(string jwt, string resource) { var disco = await discoveryDocument; var keys = new List <SecurityKey>(); foreach (var webKey in disco.KeySet.Keys) { var e = Base64Url.Decode(webKey.E); var n = Base64Url.Decode(webKey.N); var key = new RsaSecurityKey(new RSAParameters { Exponent = e, Modulus = n }) { KeyId = webKey.Kid }; keys.Add(key); } var parameters = new TokenValidationParameters { ValidIssuer = disco.Issuer, ValidAudience = resource, IssuerSigningKeys = keys, NameClaimType = "sub", RoleClaimType = JwtClaimTypes.Role }; var handler = new JwtSecurityTokenHandler(); handler.InboundClaimTypeMap.Clear(); ClaimsPrincipal user = null; try { user = handler.ValidateToken(jwt, parameters, out var _); } catch { } Thread.CurrentPrincipal = user; return(user); }
internal static void VerifyTokenSignature(string JwsJson, JObject jwk) { if ("EC".Equals(jwk["kty"].ToString())) { byte[] x = Base64Url.Decode(jwk["x"].ToString()); byte[] y = Base64Url.Decode(jwk["y"].ToString()); #if (NETCOREAPP2_1 || NETSTANDARD2_0) var publicKey = ECDsa.Create(new ECParameters { Curve = ECCurve.NamedCurves.nistP256, Q = new ECPoint { X = x, Y = y }, D = null }); var decoded = JWT.Decode(JwsJson, publicKey); #else CngKey cngKey = EccKey.New(x, y); var decoded = JWT.Decode(JwsJson, cngKey); #endif return; } else if ("RSA".Equals(jwk["kty"].ToString())) { byte[] n = Base64Url.Decode(jwk["n"].ToString()); byte[] e = Base64Url.Decode(jwk["e"].ToString()); using (RSACryptoServiceProvider RSA = new RSACryptoServiceProvider()) { RSAParameters rsaParameters = new RSAParameters { Exponent = e, Modulus = n }; RSA.ImportParameters(rsaParameters); JWT.Decode(JwsJson, RSA); return; } /*var publicKey = RsaKey.New(e, n); * var decoded = JWT.Decode(JwsJson, publicKey); * return;*/ } }
private static async Task FrontChannel(string scope, IEnumerable <string> resource) { // create a redirect URI using an available port on the loopback address. // requires the OP to allow random ports on 127.0.0.1 - otherwise set a static port var browser = new SystemBrowser(); string redirectUri = string.Format($"http://127.0.0.1:{browser.Port}"); var options = new OidcClientOptions { Authority = Constants.Authority, ClientId = "console.resource.indicators", RedirectUri = redirectUri, Scope = scope + " offline_access", Resource = resource.ToList(), FilterClaims = false, LoadProfile = false, Browser = browser, Policy = { RequireIdentityTokenSignature = false } }; var serilog = new LoggerConfiguration() .MinimumLevel.Warning() .Enrich.FromLogContext() .WriteTo.Console(outputTemplate: "[{Timestamp:HH:mm:ss} {Level}] {SourceContext}{NewLine}{Message}{NewLine}{Exception}{NewLine}") .CreateLogger(); options.LoggerFactory.AddSerilog(serilog); _oidcClient = new OidcClient(options); var result = await _oidcClient.LoginAsync(); var parts = result.AccessToken.Split('.'); var header = parts[0]; var payload = parts[1]; Console.WriteLine(); Console.WriteLine("Standard access token:"); Console.WriteLine(Encoding.UTF8.GetString(Base64Url.Decode(header)).PrettyPrintJson()); Console.WriteLine(Encoding.UTF8.GetString(Base64Url.Decode(payload)).PrettyPrintJson()); await BackChannel(result); }
async Task <byte[]> GetHiddenInputTokenAsync() { var form = await context.ReadRequestFormAsync(); var token = form[TokenName]; if (token == null) { return(null); } var tokenBytes = Base64Url.Decode(token); var unprotectedTokenBytes = options.DataProtector.Unprotect(tokenBytes, HiddenInputEntropy); return(unprotectedTokenBytes); }
public override void FromJson_WithProperties(string json) { var key = Jwk.FromJson(json); Assert.NotNull(key); var jwk = Assert.IsType <ECJwk>(key); Assert.NotNull(jwk.X509CertificateChain); Assert.NotEmpty(jwk.X509CertificateChain); Assert.NotEmpty(jwk.X5c); Assert.Equal(Base64Url.Decode("dGhpcyBpcyBhIFNIQTEgdGVzdCE"), jwk.X5t); Assert.Equal(Base64Url.Decode("dGhpcyBpcyBhIFNIQTI1NiB0ZXN0ISAgICAgICAgICAgIA"), jwk.X5tS256); Assert.Equal(JwkKeyOpsValues.Sign, jwk.KeyOps[0]); Assert.Equal("https://example.com", jwk.X5u); }
void Read() { if (String.IsNullOrWhiteSpace(Jwk.K)) { Logger.Error("Missing " + HttpSigningConstants.Jwk.Symmetric.KeyProperty); throw new ArgumentException("Missing " + HttpSigningConstants.Jwk.Symmetric.KeyProperty); } if (!HttpSigningConstants.Jwk.Symmetric.Algorithms.Contains(Jwk.Alg)) { Logger.Error("Invalid " + HttpSigningConstants.Jwk.AlgorithmProperty); throw new ArgumentException("Invalid " + HttpSigningConstants.Jwk.AlgorithmProperty); } KeyBytes = Base64Url.Decode(Jwk.K); }
// This method gets called by the runtime. Use this method to configure the HTTP request pipeline. public void Configure(IApplicationBuilder app, IHostingEnvironment env, ILoggerFactory loggerFactory) { loggerFactory.AddConsole(Configuration.GetSection("Logging")); loggerFactory.AddDebug(); #region ======net core 1.1===== //var secretKey = new byte[] { 164, 60, 194, 0, 161, 189, 41, 38, 130, 89, 141, 164, 45, 170, 159, 209, 69, 137, 243, 216, 191, 131, 47, 250, 32, 107, 231, 117, 37, 158, 225, 234 }; var secretKey = Base64Url.Decode("secertKey123123123123123");//[177,231,30,174] //var tokenSecretKey1 = Base64Url.Decode("secert"); //var keyByteArry = Base64UrlEncoder.DecodeBytes(base64); //var tokenSecretKey = Encoding.UTF8.GetBytes("O1eLcx5Re1Y3nrLwqwonYaiHnsg7KZWvBvjiTnTDy4A"); var tokenValidationParameters = new TokenValidationParameters { // Token signature will be verified using a private key. ValidateIssuerSigningKey = true, RequireSignedTokens = true, IssuerSigningKey = new SymmetricSecurityKey(secretKey), // Token will only be valid if contains "accelist.com" for "iss" claim. ValidateIssuer = true,//false不验证 ValidIssuer = "GuanHua", // Token will only be valid if contains "accelist.com" for "aud" claim. ValidateAudience = true,//false不验证 ValidAudience = "ab7ce2d75193492f9be8fd10ae3e32ff", // Token will only be valid if not expired yet, with 5 minutes clock skew. ValidateLifetime = true, RequireExpirationTime = true, ClockSkew = new TimeSpan(24, 0, 0), ValidateActor = false, }; app.UseJwtBearerAuthentication(new JwtBearerOptions { AutomaticAuthenticate = true, TokenValidationParameters = tokenValidationParameters, }); #endregion app.UseMvc(); }
internal static byte[] GetCookieToken(IDictionary <string, object> env) { var options = env.ResolveDependency <IdentityServerOptions>(); var ctx = new OwinContext(env); var cookieName = options.AuthenticationOptions.CookieOptions.Prefix + TokenName; var cookie = ctx.Request.Cookies[cookieName]; if (cookie != null) { try { var protectedCookieBytes = Base64Url.Decode(cookie); var tokenBytes = options.DataProtector.Unprotect(protectedCookieBytes, CookieEntropy); return(tokenBytes); } catch (Exception ex) { // if there's an exception we fall thru the catch block to reissue a new cookie Logger.WarnFormat("Problem unprotecting cookie; Issuing new cookie. Error message: {0}", ex.Message); } } var bytes = CryptoRandom.CreateRandomKey(16); var protectedTokenBytes = options.DataProtector.Protect(bytes, CookieEntropy); var token = Base64Url.Encode(protectedTokenBytes); var secure = ctx.Request.Scheme == Uri.UriSchemeHttps; var path = ctx.Request.Environment.GetIdentityServerBasePath(); if (path.EndsWith("/")) { path = path.Substring(0, path.Length - 1); } if (String.IsNullOrWhiteSpace(path)) { path = "/"; } ctx.Response.Cookies.Append(cookieName, token, new Microsoft.Owin.CookieOptions { HttpOnly = true, Secure = secure, Path = path }); return(bytes); }
private async Task <ClaimsPrincipal> ValidateIdentityToken(string idToken) { // read discovery document to find issuer and key material var disco = await DiscoveryClient.GetAsync(Constants.Authority); var keys = new List <SecurityKey>(); foreach (var webKey in disco.KeySet.Keys) { var e = Base64Url.Decode(webKey.E); var n = Base64Url.Decode(webKey.N); var key = new RsaSecurityKey(new RSAParameters { Exponent = e, Modulus = n }) { KeyId = webKey.Kid }; keys.Add(key); } var parameters = new TokenValidationParameters { ValidIssuer = disco.Issuer, ValidAudience = "mvc.manual", IssuerSigningKeys = keys, NameClaimType = JwtClaimTypes.Name, RoleClaimType = JwtClaimTypes.Role }; var handler = new JwtSecurityTokenHandler(); handler.InboundClaimTypeMap.Clear(); var user = handler.ValidateToken(idToken, parameters, out var _); var nonce = user.FindFirst("nonce")?.Value ?? ""; if (!string.Equals(nonce, "random_nonce")) { throw new Exception("invalid nonce"); } return(user); }
public IEnumerable <string> Get() { //生成token //var identity = new ClaimsIdentity("JWT"); //identity.AddClaim(new Claim(ClaimTypes.Name,"朱境生")); //identity.AddClaim(new Claim("sub", "朱境生")); //identity.AddClaim(new Claim("subId", "23517")); //identity.AddClaim(new Claim(ClaimTypes.Role, "AppClient")); //var props = new AuthenticationProperties(new Dictionary<string, string> //{ // {"audience","ab7ce2d75193492f9be8fd10ae3e32ff" }, // {"userName","朱境生" }, // {"userId","23517"} //}); //var ticket = new AuthenticationTicket(identity, props); TimeSpan ts = DateTime.UtcNow - new DateTime(1970, 1, 1, 0, 0, 0, 0); var payload = new Dictionary <string, object>() { { "sub", "*****@*****.**" }, { "exp", Convert.ToInt64(ts.TotalSeconds).ToString() }, { "subId", "" }, { "iss", "GuanHua" }, { "aud", "ab7ce2d75193492f9be8fd10ae3e32ff" }, { "user", "123" }, { "name", "zhu" }, { "password", "11111" } }; string strKey = Convert.ToBase64String(System.Text.Encoding.UTF8.GetBytes("secert")); var key = System.Text.Encoding.UTF8.GetBytes(Convert.ToBase64String(System.Text.Encoding.UTF8.GetBytes("secert"))); var secretKey = Base64Url.Decode("secertKey123123123123123"); //var secretKey = System.Text.Encoding.UTF8.GetBytes(Convert.ToBase64String(System.Text.Encoding.UTF8.GetBytes("secert"))); //secretKey = new byte[] { 164, 60, 194, 0, 161, 189, 41, 38, 130, 89, 141, 164, 45, 170, 159, 209, 69, 137, 243, 216, 191, 131, 47, 250, 32, 107, 231, 117, 37, 158, 225, 234 }; //string aa = "O1eLcx5Re1Y3nrLwqwonYaiHnsg7KZWvBvjiTnTDy4A"; // byte[] byteArray = System.Text.Encoding.UTF8.GetBytes(aa); string token = Jose.JWT.Encode(payload, secretKey, JwsAlgorithm.HS256); return(new string[] { "value1", token }); }
public async Task <bool> ValidateTokenAsync(string token) { var endpoints = await GetDiscoveryDocumentAsync(); var keys = new List <SecurityKey>(); foreach (var webKey in endpoints.KeySet.Keys) { var e = Base64Url.Decode(webKey.E); var n = Base64Url.Decode(webKey.N); var key = new RsaSecurityKey(new RSAParameters { Exponent = e, Modulus = n }) { KeyId = webKey.Kid }; keys.Add(key); } var parameters = new TokenValidationParameters { ValidIssuer = endpoints.Issuer, ValidAudience = "identity", IssuerSigningKeys = keys, ValidateIssuerSigningKey = true, ValidateIssuer = true, ValidateAudience = true, RequireSignedTokens = true }; var handler = new JwtSecurityTokenHandler(); try { handler.ValidateToken(token, parameters, out var _); } catch (Exception ex) { _logger.LogError(ex.Message); return(false); } return(true); }