• 设为首页
  • 点击收藏
  • 手机版
    手机扫一扫访问
    迪恩网络手机版
  • 关注官方公众号
    微信扫一扫关注
    迪恩网络公众号

C# Tokens.JwtSecurityTokenHandler类代码示例

原作者: [db:作者] 来自: [db:来源] 收藏 邀请

本文整理汇总了C#中System.IdentityModel.Tokens.JwtSecurityTokenHandler的典型用法代码示例。如果您正苦于以下问题:C# JwtSecurityTokenHandler类的具体用法?C# JwtSecurityTokenHandler怎么用?C# JwtSecurityTokenHandler使用的例子?那么恭喜您, 这里精选的类代码示例或许可以为您提供帮助。



JwtSecurityTokenHandler类属于System.IdentityModel.Tokens命名空间,在下文中一共展示了JwtSecurityTokenHandler类的20个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于我们的系统推荐出更棒的C#代码示例。

示例1: Index

        public ActionResult Index(string token)
        {
            try
            {
                var validationParameters = new TokenValidationParameters
                {
                    IssuerSigningToken = new BinarySecretSecurityToken(
                            TextEncodings.Base64Url.Decode(ConfigurationManager.AppSettings["auth0:ClientSecret"])),
                    ValidIssuer = ConfigurationManager.AppSettings["auth0:Domain"],
                    ValidAudience = ConfigurationManager.AppSettings["auth0:ClientId"]
                };

                var handler = new JwtSecurityTokenHandler();
                SecurityToken securityToken;
                ClaimsPrincipal principal = handler.ValidateToken(token, validationParameters, out securityToken);
                ClaimsIdentity identity = principal.Identity as ClaimsIdentity;
                identity.AddClaim(new Claim("http://schemas.microsoft.com/accesscontrolservice/2010/07/claims/identityprovider", "Auth0"));
                identity.AddClaim(new Claim(ClaimTypes.Name, identity.FindFirst(ClaimTypes.Email).Value));

                var sessionToken = new SessionSecurityToken(principal, TimeSpan.FromMinutes(15));
                FederatedAuthentication.SessionAuthenticationModule.WriteSessionTokenToCookie(sessionToken);

                return RedirectToAction("Change");
            }
            catch (Exception ex)
            {
                return RedirectToAction("Unauthorized");
            }
        }
开发者ID:aguerere,项目名称:rules,代码行数:29,代码来源:HomeController.cs


示例2: CreateTokenButton_Click

        private void CreateTokenButton_Click(object sender, RoutedEventArgs e)
        {
            var principal = Principal.Create(AuthenticationTypes.Password, new Claim(ClaimTypes.Name, UserName.Text));

            var sts = new Thinktecture.IdentityServer.Protocols.STS();
            SecurityToken token;

            var success = sts.TryIssueToken(
                new EndpointReference("https://booking.oceanicairlines.com/"),
                principal,
                TokenTypes.JsonWebToken,
                out token);

            if (success)
            {
                var tokenString = new JwtSecurityTokenHandler().WriteToken(token);
                Output.Text = "Encoded JWT token:" + Environment.NewLine + tokenString + Environment.NewLine + Environment.NewLine;
                var tokenParts = tokenString.Split('.');
                Output.Text += "JWT header:" + Environment.NewLine + DecodeBase64(tokenParts[0]) + Environment.NewLine + Environment.NewLine;
                Output.Text += "JWT body:" + Environment.NewLine + DecodeBase64(tokenParts[1]) + Environment.NewLine + Environment.NewLine;
                Output.Text += "JWT signature:" + Environment.NewLine + tokenParts[2];
            }
            else
            {
                Output.Text = "Could not issue token.";
            }
        }
开发者ID:hansarnevartdal,项目名称:BlogExamples,代码行数:27,代码来源:MainWindow.xaml.cs


示例3: GetToken

        //http://blog.asteropesystems.com/securing-web-api-requests-with-json-web-tokens/
        public string GetToken(string username, List<ActivityClaim> activityClaims)
        {
            var tokenHandler = new JwtSecurityTokenHandler();
            var now = DateTime.UtcNow;
            var claims = new ClaimsIdentity(new[]
                {
                    new Claim( ClaimTypes.UserData, "IsValid", ClaimValueTypes.String ),
                    new Claim( ClaimTypes.Name, username, ClaimValueTypes.String )
                });
            claims.AddClaims(activityClaims.Select(c => new Claim(ClaimTypes.UserData, c.ToString(), ClaimValueTypes.String)));

            var tokenDescriptor = new SecurityTokenDescriptor
            {
                Subject = claims,
                TokenIssuerName = "self",
                AppliesToAddress = "https://api.knowthyshelf.com",
                Lifetime = new Lifetime(now, now.AddYears(10)),
                SigningCredentials = new SigningCredentials(new InMemorySymmetricSecurityKey(TOKEN_SECURITY_KEY),
                  "http://www.w3.org/2001/04/xmldsig-more#hmac-sha256",
                  "http://www.w3.org/2001/04/xmlenc#sha256"),
            };

            var token = tokenHandler.CreateToken(tokenDescriptor);
            var tokenString = tokenHandler.WriteToken(token);

            return tokenString;
        }
开发者ID:swebgit,项目名称:know-thy-shelf,代码行数:28,代码来源:JwtProvider.cs


示例4: SendAsync

        protected override Task<HttpResponseMessage> SendAsync(HttpRequestMessage request, CancellationToken cancellationToken)
        {
            string tokenRaw = string.Empty;

            try
            {
                if (!TryRetrieveToken(request, out tokenRaw)) { return base.SendAsync(request, cancellationToken); }

                var validationParameters = new TokenValidationParameters()
                {

                    ValidIssuer = SecurityHelper.CertificateValidIssuer,
                    ValidAudience = SecurityHelper.CertificateValidAudience,
                    IssuerSigningToken = new X509SecurityToken(SecurityHelper.GetCertificate()),
                    ValidateLifetime = false,
                    ValidateAudience = true,
                    ValidateIssuer = true,
                    ValidateIssuerSigningKey = true,
                    //ClockSkew = new TimeSpan(40, 0, 0)
                };

                SecurityToken token = new JwtSecurityToken();
                ClaimsPrincipal principal = new JwtSecurityTokenHandler().ValidateToken(tokenRaw, validationParameters, out token);

                Thread.CurrentPrincipal = principal;
                if (HttpContext.Current != null) { HttpContext.Current.User = Thread.CurrentPrincipal; }

            }
            catch (Exception ex)
            {
                Trace.Write(ex);
            }

            return base.SendAsync(request, cancellationToken);
        }
开发者ID:Inmeta,项目名称:aspc2016,代码行数:35,代码来源:WebAPIConfig.cs


示例5: PostSignIn

        public LoginResult PostSignIn([FromBody] LoginCredential credentials)
        {
            var auth = new LoginResult() { Authenticated = false };

            var userRoles = QueryableDependencies.GetLoginUserRoles(credentials.UserName, credentials.Password);
            if (userRoles.Count > 0)
            //if (userRoles.Where(r => r == "CredentialSystem").Any())
            {
                auth.Authenticated = true;

                var allClaims = userRoles.Select(r => new Claim(ClaimTypes.Role, r.ToString())).ToList();
                allClaims.Add(new Claim(ClaimTypes.Name, credentials.UserName));
                allClaims.Add(new Claim(ClaimTypes.Role, userRoles[0].ToString()));

                var tokenDescriptor = new SecurityTokenDescriptor
                {
                    Subject = new ClaimsIdentity(allClaims),

                    AppliesToAddress = ConfigurationManager.AppSettings["JwtAllowedAudience"],
                    TokenIssuerName = ConfigurationManager.AppSettings["JwtValidIssuer"],
                    SigningCredentials = new SigningCredentials(new InMemorySymmetricSecurityKey(JwtTokenValidationHandler.SymmetricKey), "http://www.w3.org/2001/04/xmldsig-more#hmac-sha256", "http://www.w3.org/2001/04/xmlenc#sha256")
                };

                var tokenHandler = new JwtSecurityTokenHandler();
                var token = tokenHandler.CreateToken(tokenDescriptor);
                var tokenString = tokenHandler.WriteToken(token);

                auth.Token = tokenString;
            }

            return auth;
        }
开发者ID:JDO11709,项目名称:BadgeAPI,代码行数:32,代码来源:SigninController.cs


示例6: AuthenticateIdToken

        public static ClaimsPrincipal AuthenticateIdToken(HttpApplication application, string id_token)
        {
            var config = OpenIdConfiguration.Current;
            var handler = new JwtSecurityTokenHandler();
            handler.CertificateValidator = X509CertificateValidator.None;
            if (!handler.CanReadToken(id_token))
            {
                throw new InvalidOperationException("No SecurityTokenHandler can authenticate this id_token!");
            }

            var parameters = new TokenValidationParameters();
            parameters.AllowedAudience = AADClientId;
            // this is just for Saml
            // paramaters.AudienceUriMode = AudienceUriMode.Always;
            parameters.ValidateIssuer = false;

            var tokens = new List<SecurityToken>();
            foreach (var key in config.IssuerKeys.Keys)
            {
                tokens.AddRange(key.GetSecurityTokens());
            }
            parameters.SigningTokens = tokens;

            // validate
            var principal = (ClaimsPrincipal)handler.ValidateToken(id_token, parameters);

            // verify nonce
            VerifyNonce(principal.FindFirst(NonceClaimType).Value);

            return principal;
        }
开发者ID:cyl3392207,项目名称:policydemo2,代码行数:31,代码来源:ARMOAuthModule.cs


示例7: CreateTokenWithInMemorySymmetricSecurityKey

        static string CreateTokenWithInMemorySymmetricSecurityKey()
        {
            var now = DateTime.UtcNow;
            var tokenHandler = new JwtSecurityTokenHandler();
            var symmetricKey = new RandomBufferGenerator(256 / 8).GenerateBufferFromSeed(256 / 8);
            var tokenDescriptor = new SecurityTokenDescriptor
            {
                Subject = new ClaimsIdentity(new Claim[]
                        {
                            new Claim(ClaimTypes.Name, "Tugberk"),
                            new Claim(ClaimTypes.Role, "Sales"),
                        }),
                TokenIssuerName = "self",
                AppliesToAddress = "http://www.example.com",
                Lifetime = new Lifetime(now, now.AddMinutes(2)),
                SigningCredentials = new SigningCredentials(
                        new InMemorySymmetricSecurityKey(symmetricKey),
                        "http://www.w3.org/2001/04/xmldsig-more#hmac-sha256",
                        "http://www.w3.org/2001/04/xmlenc#sha256")
            };

            SecurityToken token = tokenHandler.CreateToken(tokenDescriptor);
            string tokenString = tokenHandler.WriteToken(token);

            return tokenString;
        }
开发者ID:shcheahgmail,项目名称:DotNetSamples,代码行数:26,代码来源:Program.cs


示例8: CreateToken

        public async Task<IHttpActionResult> CreateToken(Token token)
        {
            var publicAndPrivate = new RSACryptoServiceProvider();
            
            publicAndPrivate.FromXmlString(_configuration.PrivateKey.FromBase64String());
            var jwtToken = new JwtSecurityToken(
                                issuer: _configuration.Issuer, 
                                audience: "http://mysite.com"
                                , claims: new List<Claim>() { new Claim(ClaimTypes.Name, token.username) }
                                , notBefore: DateTime.UtcNow
                                , expires: DateTime.UtcNow.AddMinutes(1)
                                , signingCredentials: new SigningCredentials(
                                    new RsaSecurityKey(publicAndPrivate)
                                       ,SecurityAlgorithms.RsaSha256Signature
                                       ,SecurityAlgorithms.Sha256Digest)
                           );

            var tokenHandler = new JwtSecurityTokenHandler();
            var tokenString = tokenHandler.WriteToken(jwtToken);

            return Ok(new
            {
                access_token = tokenString,
                expires_in = new TimeSpan(0,0, 1,0).TotalSeconds,
                expires_on = (long)(DateTime.UtcNow.AddMinutes(1) - new DateTime(1970, 1, 1)).TotalSeconds
            });
        }
开发者ID:girmateshe,项目名称:OAuth,代码行数:27,代码来源:JwtController.cs


示例9: CreateTokenString

        public static string CreateTokenString(JwtSecurityToken token)
        {
            JwtSecurityTokenHandler.OutboundClaimTypeMap = new Dictionary<string, string>();

            var handler = new JwtSecurityTokenHandler();
            return handler.WriteToken(token);
        }
开发者ID:ryanmar,项目名称:IdentityServer3.AccessTokenValidation,代码行数:7,代码来源:TokenFactory.cs


示例10: Main

        private static void Main(string[] args)
        {
            var key = Convert.FromBase64String(SymmetricKey);
            var credentials = new SigningCredentials(
                new InMemorySymmetricSecurityKey(key),
                "http://www.w3.org/2001/04/xmldsig-more#hmac-sha256",
                "http://www.w3.org/2001/04/xmlenc#sha256");

            var tokenDescriptor = new SecurityTokenDescriptor
            {
                Subject = new ClaimsIdentity(new[]
                {
                    new Claim(ClaimTypes.Name, "bhogg"),
                    new Claim(ClaimTypes.GivenName, "Boss"),
                    new Claim(ClaimTypes.Surname, "Hogg"),
                    new Claim(ClaimTypes.Role, "Manager"),
                    new Claim(ClaimTypes.Role, "SeniorWorker"),
                }),
                TokenIssuerName = "corp",
                AppliesToAddress = "http://www.example.com",
                SigningCredentials = credentials,
                Lifetime = new Lifetime(DateTime.UtcNow, DateTime.UtcNow.AddYears(10))
            };

            var tokenHandler = new JwtSecurityTokenHandler();
            var token = tokenHandler.CreateToken(tokenDescriptor);
            var tokenString = tokenHandler.WriteToken(token);

            Console.WriteLine(tokenString);
            Debug.WriteLine(tokenString);

            Console.ReadLine();
        }
开发者ID:SHassona,项目名称:Personal-Repository,代码行数:33,代码来源:Program.cs


示例11: Post

        public string Post(Credential credential)
        {
            if (credential.username == "admin" && credential.password == "123")
            {
                var tokenHandler = new JwtSecurityTokenHandler();
                var securityKey = Authorization.GetBytes("anyoldrandomtext");
                var now = DateTime.UtcNow;
                var tokenDescriptor = new SecurityTokenDescriptor
                {
                    Subject = new ClaimsIdentity(new[]
                    {
                     new Claim( ClaimTypes.UserData,"IsValid", ClaimValueTypes.String, "(local)" )
                     }),
                    TokenIssuerName = "self",
                    AppliesToAddress = "https://www.mywebsite.com",
                    Lifetime = new Lifetime(now, now.AddMinutes(60)),
                    SigningCredentials = new SigningCredentials(new InMemorySymmetricSecurityKey(securityKey),
                      "http://www.w3.org/2001/04/xmldsig-more#hmac-sha256",
                      "http://www.w3.org/2001/04/xmlenc#sha256"),
                };

                var token = tokenHandler.CreateToken(tokenDescriptor);
                var tokenString = tokenHandler.WriteToken(token);

                return tokenString;
            }
            else
            {
                return string.Empty;
            }
        }
开发者ID:santoshkushwah,项目名称:ABC,代码行数:31,代码来源:AuthenticateController.cs


示例12: ParseToken

        public Result<List<Claim>> ParseToken(string token)
        {
            var result = new Result<List<Claim>>();

            if (String.IsNullOrEmpty(token))
                return result;

            var tokenHandler = new JwtSecurityTokenHandler();
            var validationParameters = new TokenValidationParameters()
            {
                ValidAudience = "https://api.knowthyshelf.com",
                IssuerSigningToken = new BinarySecretSecurityToken(TOKEN_SECURITY_KEY),
                ValidIssuer = "self"
            };

            SecurityToken securityToken;
            var principal = tokenHandler.ValidateToken(token, validationParameters, out securityToken);
            var isValidClaim = principal.Claims.FirstOrDefault();
            if (isValidClaim?.Value == "IsValid" && securityToken.ValidFrom <= DateTime.UtcNow && securityToken.ValidTo >= DateTime.UtcNow)
            {
                result.ResultCode = Enums.ResultCode.Ok;
                result.Data = principal.Claims.ToList();
            }
            return result;
        }
开发者ID:swebgit,项目名称:know-thy-shelf,代码行数:25,代码来源:JwtProvider.cs


示例13: JwtAuthenticationOwinMiddlewareTests

        public JwtAuthenticationOwinMiddlewareTests()
        {
            var signingCredentials = new SigningCredentials(
                new InMemorySymmetricSecurityKey(Convert.FromBase64String(Key)),
                "http://www.w3.org/2001/04/xmldsig-more#hmac-sha256",
                "http://www.w3.org/2001/04/xmlenc#sha256");

            var now = DateTime.UtcNow;

            var tokenDescriptor = new SecurityTokenDescriptor
            {
                Subject = new ClaimsIdentity(new []
                        {
                            new Claim("sub", "Alice"),
                            new Claim("email", "[email protected]"), 
                        }),
                TokenIssuerName = Issuer,
                AppliesToAddress = Audience,
                Lifetime = new Lifetime(now, now.AddMinutes(LifetimeInMinutes)),
                SigningCredentials = signingCredentials,
            };

            var tokenHandler = new JwtSecurityTokenHandler();
            var token = tokenHandler.CreateToken(tokenDescriptor);
            _tokenString = tokenHandler.WriteToken(token);
        }
开发者ID:wukaixian,项目名称:WebApiBook.Security,代码行数:26,代码来源:JwtAuthenticationOwinMiddlewareTests.cs


示例14: CreateAssertionToken

        public string CreateAssertionToken()
        {
            var now = DateTime.Now.ToUniversalTime();

            var jwt = new JwtSecurityToken(_clientId,
                                           _audience,
                                           new List<Claim>()
                                           {
                                               new Claim(JwtClaimTypes.JwtId, Guid.NewGuid().ToString()),
                                               new Claim(JwtClaimTypes.Subject, _clientId),
                                               new Claim(JwtClaimTypes.IssuedAt, EpochTime.GetIntDate(now).ToString(), ClaimValueTypes.Integer64)
                                           },
                                           now,
                                           now.AddMinutes(1),
                                           new X509SigningCredentials(_certificate,
                                               SecurityAlgorithms.RsaSha256Signature,
                                               SecurityAlgorithms.Sha256Digest
                                            )
                        );

            if (_embedCertificate)
            {
                var rawCertificate = Convert.ToBase64String(_certificate.Export(X509ContentType.Cert));
                jwt.Header.Add(JwtHeaderParameterNames.X5c, new[] {rawCertificate});
            }

            var tokenHandler = new JwtSecurityTokenHandler();
            return tokenHandler.WriteToken(jwt);
        }
开发者ID:Scalepoint,项目名称:OAuthJwtAssertionTokenClient,代码行数:29,代码来源:JwtAssertionFactory.cs


示例15: CreateAndValidateTokens_DuplicateClaims

        public void CreateAndValidateTokens_DuplicateClaims()
        {
            SecurityToken validatedToken;
            string encodedJwt = IdentityUtilities.CreateJwtToken(
                new SecurityTokenDescriptor
                {
                    AppliesToAddress = IdentityUtilities.DefaultAudience,
                    SigningCredentials = IdentityUtilities.DefaultSymmetricSigningCredentials,
                    Subject = new ClaimsIdentity(ClaimSets.DuplicateTypes(IdentityUtilities.DefaultIssuer, IdentityUtilities.DefaultIssuer)),
                    TokenIssuerName = IdentityUtilities.DefaultIssuer,
                });

            JwtSecurityTokenHandler tokenHandler = new JwtSecurityTokenHandler();
            JwtSecurityTokenHandler.InboundClaimFilter.Add("aud");
            JwtSecurityTokenHandler.InboundClaimFilter.Add("exp");
            JwtSecurityTokenHandler.InboundClaimFilter.Add("iat");
            JwtSecurityTokenHandler.InboundClaimFilter.Add("iss");
            JwtSecurityTokenHandler.InboundClaimFilter.Add("nbf");

            ClaimsPrincipal claimsPrincipal = tokenHandler.ValidateToken(encodedJwt, IdentityUtilities.DefaultSymmetricTokenValidationParameters, out validatedToken);

            Assert.IsTrue(IdentityComparer.AreEqual<IEnumerable<Claim>>(claimsPrincipal.Claims, ClaimSets.DuplicateTypes(IdentityUtilities.DefaultIssuer, IdentityUtilities.DefaultIssuer), new CompareContext { IgnoreProperties = true, IgnoreSubject = true }));

            JwtSecurityTokenHandler.InboundClaimFilter.Clear();
        }
开发者ID:richardschneider,项目名称:azure-activedirectory-identitymodel-extensions-for-dotnet,代码行数:25,代码来源:CreateAndValidateTokens.cs


示例16: JwtSecurityTokenTestVariation

 public JwtSecurityTokenTestVariation() 
 {
     _notbefore = DateTime.UtcNow;
     _expires = DateTime.UtcNow + TimeSpan.FromHours( 1 );
     _jwtHandler = new JwtSecurityTokenHandler();
     _expectedException = ExpectedException.NoExceptionExpected;
 }
开发者ID:richardschneider,项目名称:azure-activedirectory-identitymodel-extensions-for-dotnet,代码行数:7,代码来源:JwtTestUtilities.cs


示例17: ValidateJwtAccessTokenAsync

        protected virtual Task<TokenValidationResult> ValidateJwtAccessTokenAsync(string jwt)
        {
            var handler = new JwtSecurityTokenHandler();
            handler.Configuration = new SecurityTokenHandlerConfiguration();
            handler.Configuration.CertificateValidationMode = X509CertificateValidationMode.None;
            handler.Configuration.CertificateValidator = X509CertificateValidator.None;
            
            var parameters = new TokenValidationParameters
            {
                ValidIssuer = _settings.GetIssuerUri(),
                SigningToken = new X509SecurityToken(_settings.GetSigningCertificate()),
                AllowedAudience = string.Format(Constants.AccessTokenAudience, _settings.GetIssuerUri())
            };

            try
            {
                var id = handler.ValidateToken(jwt, parameters);

                return Task.FromResult(new TokenValidationResult
                {
                    Claims = id.Claims
                });
            }
            catch (Exception ex)
            {
                _logger.ErrorFormat("JWT token validation error: {0}", ex.ToString());

                return Task.FromResult(new TokenValidationResult
                {
                    IsError = true,
                    Error = Constants.ProtectedResourceErrors.InvalidToken
                });                
            }
        }
开发者ID:Zoumaho,项目名称:Thinktecture.IdentityServer.v3,代码行数:34,代码来源:TokenValidator.cs


示例18: Validate

        public ClaimsPrincipal Validate(string jwtTokenAsBase64, JwtOptions options)
        {
            var tokenHandler = new JwtSecurityTokenHandler();

            string keyAsUtf8 = options.JwtSigningKeyAsUtf8;

            byte[] keyAsBytes = Encoding.UTF8.GetBytes(keyAsUtf8);

            SecurityToken signingToken = new BinarySecretSecurityToken(keyAsBytes);
            var tokenValidationParameters = new TokenValidationParameters
                                            {
                                                IssuerSigningToken = signingToken,
                                                ValidAudience = options.Audience,
                                                ValidIssuer = options.Issuer
                                            };
            ClaimsPrincipal principal;
            try
            {
                SecurityToken validatedToken;
                principal = tokenHandler.ValidateToken(jwtTokenAsBase64, tokenValidationParameters,
                    out validatedToken);
            }
            catch (Exception ex)
            {
                Debug.Write(ex, "error");
                principal = new ClaimsPrincipal(new ClaimsIdentity(authenticationType:""));
            }

            return principal;
        }
开发者ID:jayway,项目名称:JayLabs.Owin.OAuthAuthorization,代码行数:30,代码来源:TokenValidator.cs


示例19: SetJwtAuthorizationHeader

        /// <summary>
        /// Sets a JWT authorization header on the default request headers of an <see cref="HttpClient"/>.
        /// </summary>
        /// <param name="client">The client for which to set the authorization header.</param>
        /// <param name="signingCertificate">The signing certificate to sign the token.</param>
        /// <param name="appliesToAddress">The address for which the token is considered valid.</param>
        /// <param name="claims">The claims that define the user. Leave null for an anonymous user.</param>
        /// <param name="tokenIssuerName">Name of the token issuer. Defaults to "self".</param>
        /// <param name="tokenDuration">
        /// The token duration for which it's considered valid. Defaults to 2 hours.
        /// </param>
        /// <exception cref="ArgumentNullException">
        /// <paramref name="signingCertificate"/> is <see langword="null"/>.
        /// </exception>
        /// <exception cref="ArgumentException">
        /// <paramref name="appliesToAddress"/> is <see langword="null"/> or empty.
        /// </exception>
        /// <exception cref="ArgumentException">
        /// <paramref name="tokenIssuerName"/> is <see langword="null"/> or empty.
        /// </exception>
        public static void SetJwtAuthorizationHeader(
            this HttpClient client,
            X509Certificate2 signingCertificate,
            string appliesToAddress,
            IEnumerable<Claim> claims = null,
            string tokenIssuerName = "self",
            TimeSpan? tokenDuration = null)
        {
            signingCertificate.AssertNotNull("signingCertificate");
            appliesToAddress.AssertNotNullOrWhitespace("appliesToAddress");
            tokenIssuerName.AssertNotNullOrWhitespace("tokenIssuerName");

            var now = DateTime.UtcNow;
            var tokenHandler = new JwtSecurityTokenHandler();
            var tokenDescriptor = new SecurityTokenDescriptor
            {
                Subject = new ClaimsIdentity(claims),
                TokenIssuerName = tokenIssuerName,
                AppliesToAddress = appliesToAddress,
                Lifetime = new Lifetime(now, now.Add(tokenDuration ?? TimeSpan.FromHours(2))),
                SigningCredentials = new X509SigningCredentials(signingCertificate)
            };

            SecurityToken token = tokenHandler.CreateToken(tokenDescriptor);
            string tokenString = tokenHandler.WriteToken(token);

            client.DefaultRequestHeaders.Authorization = new AuthenticationHeaderValue("Bearer", tokenString);
        }
开发者ID:Georadix,项目名称:Georadix.NET,代码行数:48,代码来源:HttpClientExtensions.cs


示例20: End2End_OpenIdConnect

        public void End2End_OpenIdConnect()
        {
            SigningCredentials rsaSigningCredentials = 
                new SigningCredentials(
                    KeyingMaterial.RsaSecurityKey_Private2048, 
                    SecurityAlgorithms.RsaSha1Signature, 
                    SecurityAlgorithms.Sha256Digest, 
                    new SecurityKeyIdentifier(new NamedKeySecurityKeyIdentifierClause("kid", "NGTFvdK-fythEuLwjpwAJOM9n-A"))
                    );

            //"<RSAKeyValue><Modulus>rCz8Sn3GGXmikH2MdTeGY1D711EORX/lVXpr+ecGgqfUWF8MPB07XkYuJ54DAuYT318+2XrzMjOtqkT94VkXmxv6dFGhG8YZ8vNMPd4tdj9c0lpvWQdqXtL1TlFRpD/P6UMEigfN0c9oWDg9U7Ilymgei0UXtf1gtcQbc5sSQU0S4vr9YJp2gLFIGK11Iqg4XSGdcI0QWLLkkC6cBukhVnd6BCYbLjTYy3fNs4DzNdemJlxGl8sLexFytBF6YApvSdus3nFXaMCtBGx16HzkK9ne3lobAwL2o79bP4imEGqg+ibvyNmbrwFGnQrBc1jTF9LyQX9q+louxVfHs6ZiVw==</Modulus><Exponent>AQAB</Exponent></RSAKeyValue>"
            RSA rsa = KeyingMaterial.RsaSecurityKey_2048.GetAsymmetricAlgorithm(SecurityAlgorithms.RsaSha1Signature, false) as RSA;
            OpenIdConnectConfiguration configuration = OpenIdConnectConfigurationRetriever.GetAsync(OpenIdConfigData.OpenIdConnectMetadataFile, CancellationToken.None).Result;            
            JwtSecurityTokenHandler tokenHandler = new JwtSecurityTokenHandler();
            JwtSecurityToken jwt = tokenHandler.CreateToken(
                configuration.Issuer,
                IdentityUtilities.DefaultAudience,
                IdentityUtilities.DefaultClaimsIdentity,
                DateTime.UtcNow,
                DateTime.UtcNow + TimeSpan.FromHours(1),
                rsaSigningCredentials );

            TokenValidationParameters validationParameters =
                new TokenValidationParameters
                {
                    IssuerSigningTokens = configuration.SigningTokens,
                    ValidAudience = IdentityUtilities.DefaultAudience,
                    ValidIssuer = configuration.Issuer,
                };

            SecurityToken securityToken = null;
            tokenHandler.ValidateToken(jwt.RawData, validationParameters, out securityToken);
        }
开发者ID:vebin,项目名称:azure-activedirectory-identitymodel-extensions-for-dotnet,代码行数:33,代码来源:End2EndTests.cs



注:本文中的System.IdentityModel.Tokens.JwtSecurityTokenHandler类示例由纯净天空整理自Github/MSDocs等源码及文档管理平台,相关代码片段筛选自各路编程大神贡献的开源项目,源码版权归原作者所有,传播和使用请参考对应项目的License;未经允许,请勿转载。


鲜花

握手

雷人

路过

鸡蛋
该文章已有0人参与评论

请发表评论

全部评论

专题导读
上一篇:
C# Tokens.SamlSerializer类代码示例发布时间:2022-05-26
下一篇:
C# Tokens.JwtSecurityToken类代码示例发布时间:2022-05-26
热门推荐
阅读排行榜

扫描微信二维码

查看手机版网站

随时了解更新最新资讯

139-2527-9053

在线客服(服务时间 9:00~18:00)

在线QQ客服
地址:深圳市南山区西丽大学城创智工业园
电邮:jeky_zhao#qq.com
移动电话:139-2527-9053

Powered by 互联科技 X3.4© 2001-2213 极客世界.|Sitemap