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


C# JwtSecurityTokenHandler.CreateToken方法代码示例

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


在下文中一共展示了JwtSecurityTokenHandler.CreateToken方法的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: 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

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

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

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

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

示例8: BearerToken

        static string BearerToken()
        {
            var signatureAlgorithm = "http://www.w3.org/2001/04/xmldsig-more#hmac-sha256";
            var digestAlgorithm = "http://www.w3.org/2001/04/xmlenc#sha256";

            var securityKey = Convert.FromBase64String(mainKey);
            var inMemKey = new InMemorySymmetricSecurityKey(securityKey);

            ClaimsIdentity identity = new ClaimsIdentity();
            identity.AddClaim(new Claim("scope", "Full"));

            JwtSecurityTokenHandler handler = new JwtSecurityTokenHandler();
            SecurityToken securityToken = handler.CreateToken(new SecurityTokenDescriptor()
            {
                TokenType = "Bearer",
                Lifetime = new Lifetime(DateTime.UtcNow, DateTime.UtcNow.AddHours(1)),
                SigningCredentials = new SigningCredentials(inMemKey, signatureAlgorithm, digestAlgorithm),
                //This data I would get by matching the jwtSecurityToken.Audience to database or something
                TokenIssuerName = "PaulsSite",
                AppliesToAddress = "http://JoshsSite",
                Subject = identity
            }
            );

            return handler.WriteToken(securityToken);
        }
开发者ID:pplavetzki,项目名称:generatekeys,代码行数:26,代码来源:Program.cs

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

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

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

示例12: Execute

#pragma warning disable 1998
        public override async Task<Result> Execute()
        {
            Result result = new Result();
            try
            {
                Console.Out.WriteLine("Generating access token...");

                // encryption key
                string key_s = ConfigurationManager.ConnectionStrings["JWTKey"].ConnectionString;
                byte[] key_b = new byte[key_s.Length * sizeof(char)];
                System.Buffer.BlockCopy(key_s.ToCharArray(), 0, key_b, 0, key_b.Length);

                // create the token
                JwtSecurityTokenHandler tokenHandler = new JwtSecurityTokenHandler();
                ClaimsIdentity subject = new ClaimsIdentity(new Claim[] { new Claim(ClaimTypes.Uri, SiteUrl, ClaimValueTypes.String) });
                SecurityTokenDescriptor tokenDescriptor = new SecurityTokenDescriptor
                {
                    Subject = subject,
                    TokenIssuerName = "SpSat",
                    Lifetime = new Lifetime(DateTime.UtcNow, DateTime.UtcNow.AddHours(4)),
                    SigningCredentials = new SigningCredentials(new InMemorySymmetricSecurityKey(key_b), "http://www.w3.org/2001/04/xmldsig-more#hmac-sha256", "http://www.w3.org/2001/04/xmlenc#sha256")
                };
                SecurityToken token = tokenHandler.CreateToken(tokenDescriptor);

                using (ClientContext context = new ClientContext(SiteUrl))
                {

                    // authenticate
                    string usernamePassword = ConfigurationManager.ConnectionStrings["SharePoint"].ConnectionString;
                    dynamic usernamePassword_j = Newtonsoft.Json.JsonConvert.DeserializeObject(usernamePassword);
                    string username = usernamePassword_j.username;
                    string password = usernamePassword_j.password;
                    SecureString password_s = new SecureString();
                    Array.ForEach(password.ToCharArray(), password_s.AppendChar);
                    context.Credentials = new SharePointOnlineCredentials(username, password_s);

                    // write the token to the property bag
                    PropertyValues webProperties = context.Web.AllProperties;
                    webProperties["accessToken"] = tokenHandler.WriteToken(token);
                    context.Web.Update();
                    context.ExecuteQuery();

                }

                Console.Out.WriteLine("Completed generating access token.");
                result.Status = Status.Success;
            }
            catch (Exception ex)
            {
                result.Status = Status.Failure;
                result.Log.Add(ex.Message);
            }
            return result;
        }
开发者ID:plasne,项目名称:SpSat,代码行数:55,代码来源:LandingJob.cs

示例13: CreateTokenAsBase64

        public static string CreateTokenAsBase64(this SecurityTokenDescriptor securityTokenDescriptor)
        {
            var tokenHandler = new JwtSecurityTokenHandler();

            SecurityToken securityToken = tokenHandler.CreateToken(securityTokenDescriptor);
            string token = tokenHandler.WriteToken(securityToken);

            string tokenAsBase64 = token;

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

示例14: GetClientAssertion

        static string GetClientAssertion(string tenantId, string clientId, X509Certificate2 cert)
        {
            var claims = new List<Claim>();
            claims.Add(new Claim("sub", clientId));

            var handler = new JwtSecurityTokenHandler();
            var credentials = new X509SigningCredentials(cert);
            return handler.CreateToken(
                issuer: clientId,
                audience: String.Format(TokenEndpoint, tenantId), 
                subject: new ClaimsIdentity(claims), 
                signingCredentials: credentials).RawData;
        }
开发者ID:vansonvinhuni,项目名称:ARMClient,代码行数:13,代码来源:AADHelper.cs

示例15: CreateJwtToken

        public static string CreateJwtToken(string userName, string role)
        {
            var claimList = new List<Claim>()
                {
                    new Claim(ClaimTypes.Name, userName),
                    new Claim(ClaimTypes.Role, role)     //Not sure what this is for
                };

            var tokenHandler = new JwtSecurityTokenHandler() { RequireExpirationTime = true };
            var sSKey = new InMemorySymmetricSecurityKey(SecurityConstants.KeyForHmacSha256);

            var jwtToken = tokenHandler.CreateToken(makeSecurityTokenDescriptor(sSKey, claimList));
            return tokenHandler.WriteToken(jwtToken);
        }
开发者ID:LuanNg,项目名称:JwtAuthWebApi,代码行数:14,代码来源:TokenManager.cs


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