当前位置: 首页>>代码示例>>C#>>正文


C# Tokens.JwtSecurityTokenHandler类代码示例

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


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


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