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


C# Tokens.SecurityTokenDescriptor类代码示例

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


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

示例1: 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

示例2: 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

示例3: 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

示例4: GetResponse

        /// <summary>
        /// Creates the token response and invokes the logging callbacks.
        /// </summary>
        /// <param name="request">The request.</param>
        /// <param name="tokenDescriptor">The token descriptor.</param>
        /// <returns>A RequestSecurityTokenResponse</returns>
        protected override RequestSecurityTokenResponse GetResponse(RequestSecurityToken request, SecurityTokenDescriptor tokenDescriptor)
        {
            var response = base.GetResponse(request, tokenDescriptor);

            // see if token is encrypted
            EncryptedSecurityToken encryptedToken = tokenDescriptor.Token as EncryptedSecurityToken;
            SecurityToken token;

            if (encryptedToken != null)
            {
                // if so, use inner token
                token = encryptedToken.Token;
            }
            else
            {
                // if not, use the token directly
                token = tokenDescriptor.Token;
            }

            var sb = new StringBuilder(128);
            FederatedAuthentication.ServiceConfiguration.SecurityTokenHandlers.WriteToken(XmlWriter.Create(new StringWriter(sb)), token);

            try
            {
                // do logging callback
                OnTrace(
                    XElement.Parse(SerializeRequest(request)),
                    XElement.Parse(SerializeResponse(response)),
                    XElement.Parse(sb.ToString()));
            }
            catch
            { }

            return response;
        }
开发者ID:IdentityModel,项目名称:Thinktecture.IdentityModel.v1,代码行数:41,代码来源:TracingSecurityTokenService.cs

示例5: CreateToken

        public override SecurityToken CreateToken(SecurityTokenDescriptor tokenDescriptor)
        {
            var sb = new StringBuilder();

            CreateClaims(tokenDescriptor, sb);

            sb.AppendFormat("Issuer={0}&", HttpUtility.UrlEncode(tokenDescriptor.TokenIssuerName));
            sb.AppendFormat("Audience={0}&", HttpUtility.UrlEncode(tokenDescriptor.AppliesToAddress));

            var seconds = (tokenDescriptor.Lifetime.Expires - tokenDescriptor.Lifetime.Created);
            double lifeTimeInSeconds = 3600;
            if (seconds.HasValue)
                lifeTimeInSeconds = seconds.Value.TotalSeconds;

            sb.AppendFormat("ExpiresOn={0:0}", DateTime.UtcNow.ToEpochTime() + lifeTimeInSeconds);

            var unsignedToken = sb.ToString();

            var key = (InMemorySymmetricSecurityKey)tokenDescriptor.SigningCredentials.SigningKey;
            var hmac = new HMACSHA256(key.GetSymmetricKey());
            var sig = hmac.ComputeHash(Encoding.ASCII.GetBytes(unsignedToken));

            var signedToken = String.Format("{0}&HMACSHA256={1}",
                unsignedToken,
                HttpUtility.UrlEncode(Convert.ToBase64String(sig)));

            return new SimpleWebToken(signedToken);
        }
开发者ID:highwaychurch,项目名称:web,代码行数:28,代码来源:SwtSecurityTokenHandler.cs

示例6: 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

示例7: 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

示例8: WrapJwt

        static GenericXmlSecurityToken WrapJwt(string jwt)
        {
            var subject = new ClaimsIdentity("saml");
            subject.AddClaim(new Claim("jwt", jwt));

            var descriptor = new SecurityTokenDescriptor
            {
                TokenType = TokenTypes.Saml2TokenProfile11,
                TokenIssuerName = "urn:wrappedjwt",
                Subject = subject
            };

            var handler = new Saml2SecurityTokenHandler();
            var token = handler.CreateToken(descriptor);

            var xmlToken = new GenericXmlSecurityToken(
                XElement.Parse(token.ToTokenXmlString()).ToXmlElement(),
                null,
                DateTime.Now,
                DateTime.Now.AddHours(1),
                null,
                null,
                null);

            return xmlToken;
        }
开发者ID:camainc,项目名称:IdentityServer3.Samples,代码行数:26,代码来源:Program.cs

示例9: 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

示例10: MyToken

        public ActionResult MyToken()
        {
            var config = ConfigurationRepository.Configuration;
            var samlHandler = SecurityTokenHandlerCollection.CreateDefaultSecurityTokenHandlerCollection()[config.DefaultTokenType];
            
            var descriptor = new SecurityTokenDescriptor
            {
                AppliesToAddress = "http://self",
                Lifetime = new Lifetime(DateTime.UtcNow, DateTime.UtcNow.AddHours(config.DefaultTokenLifetime)),
                SigningCredentials = new X509SigningCredentials(ConfigurationRepository.SigningCertificate.Certificate),
                TokenIssuerName = config.IssuerUri,
                Subject = new ClaimsIdentity(GetClaims())
            };

            var token = samlHandler.CreateToken(descriptor);

            var sb = new StringBuilder(1024);
            samlHandler.WriteToken(XmlWriter.Create(new StringWriter(sb)), token);

            return new ContentResult
            {
                ContentType = "text/xml",
                Content = sb.ToString()
            };
        }
开发者ID:kievryan,项目名称:Thinktecture.IdentityServer.45,代码行数:25,代码来源:AdminController.cs

示例11: 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

示例12: HandlerCreateRoundtripSingleClaimTypes

        public void HandlerCreateRoundtripSingleClaimTypes()
        {
            var signinKey = SymmetricKeyGenerator.Create(32);

            var identity = new ClaimsIdentity(new List<Claim>
                {
                    new Claim(ClaimTypes.Name, "dominick"),
                    new Claim(ClaimTypes.Email, "[email protected]"),
                }, "Custom");

            var descriptor = new SecurityTokenDescriptor
            {
                Subject = identity,
                SigningCredentials = new HmacSigningCredentials(signinKey),
                TokenIssuerName = "dominick",
                Lifetime = new Lifetime(DateTime.UtcNow, DateTime.UtcNow.AddHours(8)),
                AppliesToAddress = "http://foo.com"
            };

            var handler = new JsonWebTokenHandler();
            var token = handler.CreateToken(descriptor);


            var tokenString = handler.WriteToken(token);
            Trace.WriteLine(tokenString);

            // token should not be empty
            Assert.IsTrue(!string.IsNullOrWhiteSpace(tokenString));

            // token with signature needs to be 3 parts
            var parts = tokenString.Split('.');
            Assert.IsTrue(parts.Length == 3, "JWT should have excactly 3 parts");

            // signature must be 256 bits
            var sig = Base64Url.Decode(parts[2]);
            Assert.IsTrue(sig.Length == 32, "Signature is not 32 bits");

            var jwtToken = handler.ReadToken(tokenString);


            var config = new SecurityTokenHandlerConfiguration();
            var registry = new WebTokenIssuerNameRegistry();
            registry.AddTrustedIssuer("dominick", "dominick");
            config.IssuerNameRegistry = registry;

            var issuerResolver = new WebTokenIssuerTokenResolver();
            issuerResolver.AddSigningKey("dominick", Convert.ToBase64String(signinKey));
            config.IssuerTokenResolver = issuerResolver;

            config.AudienceRestriction.AllowedAudienceUris.Add(new Uri("http://foo.com"));

            handler.Configuration = config;
            var identity2 = handler.ValidateToken(jwtToken).First();

            Assert.IsTrue(identity.Claims.Count() == 2);
            //Assert.IsTrue(identity.Claims.First().Issuer == "dominick");
        }
开发者ID:rmarinho,项目名称:Thinktecture.IdentityModel.45,代码行数:57,代码来源:HandlerCreate.cs

示例13: GenerateAccessToken

 public async Task<string> GenerateAccessToken(SecurityTokenDescriptor tokenDescriptor, TokenValidationParameters validationParameters)
 {
     if (tokenCache.ContainsKey(tokenDescriptor) && tokenDescriptor.Lifetime.Expires > DateTime.UtcNow.AddMinutes(-1))
     {
         return tokenCache[tokenDescriptor];
     }
     tokenDescriptor.Lifetime = new Lifetime(DateTime.UtcNow, DateTime.UtcNow.AddMinutes(10));
     var accessToken = await this.innerTokenProvider.GenerateAccessToken(tokenDescriptor, validationParameters);
     return tokenCache.AddOrUpdate(tokenDescriptor, accessToken, (d, t) => accessToken);
 }
开发者ID:ianlovell,项目名称:openidconnect,代码行数:10,代码来源:CachingTokenProvider.cs

示例14: GetJwtToken

        public static string GetJwtToken(this ClaimsIdentity identity, SecurityTokenDescriptor tokenDescriptor)
        {
            if (identity == null || tokenDescriptor == null) return null;
            tokenDescriptor.Subject = identity;
            var tokenHandler = new JwtSecurityTokenHandler();
            var token = tokenHandler.CreateToken(tokenDescriptor);
            var tokenString = tokenHandler.WriteToken(token);

            return tokenString;
        }
开发者ID:BikS2013,项目名称:bUtility,代码行数:10,代码来源:GenericExtensions.cs

示例15: FindClientByIdAsync

        public async Task<Client> FindClientByIdAsync(string clientId)
        {            
            var clientsUri = $"admin-api/api/clients/{clientId}";

            //var cert = Cert.Load(StoreName.My, StoreLocation.CurrentUser, "b512d01195667dbc7c4222ec6fd563ac64e3d450");
            //var handler = new WebRequestHandler();
            //handler.ClientCertificates.Add(cert);

            // Retrieve an access token from the IdentityAdmin /authorize OAuth endpoint
            using (var client = new HttpClient())
            {
                client.BaseAddress = new Uri(this.identityAdminUri);
                client.DefaultRequestHeaders.Accept.Clear();
                client.DefaultRequestHeaders.Accept.Add(new MediaTypeWithQualityHeaderValue("application/json"));

                var cert = Cert.Load(typeof(IOwinBootstrapper).Assembly, "Cert", "idsrv3test.pfx", "idsrv3test");

                var tokenDescriptor = new SecurityTokenDescriptor
                {
                    Subject = new ClaimsIdentity(new Claim[]
                    {
                        new Claim("name", "idServer"),
                        new Claim("role", "IdentityAdminManager"),
                        new Claim("scope", "idadmin-api")
                    }),
                    TokenIssuerName = "idServer",                    
                    AppliesToAddress = this.identityAdminUri,
                    Lifetime = new Lifetime(DateTime.Now, DateTime.Now.AddMinutes(10)),
                    SigningCredentials = new X509SigningCredentials(cert)
                };

                var tokenHandler = new JwtSecurityTokenHandler();
                var securityToken = tokenHandler.CreateToken(tokenDescriptor);
                var accessToken = tokenHandler.WriteToken(securityToken);

                var jwtParams = new TokenValidationParameters
                {
                    NameClaimType = "name",
                    RoleClaimType = "role",
                    ValidAudience = this.identityAdminUri,
                    ValidIssuer = "idServer",                    
                    IssuerSigningToken = new X509SecurityToken(cert)                    
                };

                SecurityToken validatedToken;
                tokenHandler.ValidateToken(accessToken, jwtParams, out validatedToken);                

                client.DefaultRequestHeaders.Authorization = new AuthenticationHeaderValue("Bearer", accessToken);

                var response = await client.GetAsync(clientsUri);
                var str = await response.Content.ReadAsStringAsync();
            }

            return null;
        }
开发者ID:ianlovell,项目名称:openidconnect,代码行数:55,代码来源:IdentityAdminClientStore.cs


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