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


C# Tokens.JwtSecurityToken类代码示例

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


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

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

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

示例3: CanCreateReportEmbedToken

        public void CanCreateReportEmbedToken()
        {
            var workspaceId = Guid.NewGuid().ToString();
            var reportId = Guid.NewGuid().ToString();

            var token = PowerBIToken.CreateReportEmbedToken("Contoso", workspaceId, reportId, "TestUser", new []{ "TestRole" });

            Assert.IsNotNull(token);
            var jwt = token.Generate(this.accessKey);
            Assert.IsFalse(string.IsNullOrEmpty(jwt));

            var decodedToken = new JwtSecurityToken(jwt);

            var versionClaim = decodedToken.Claims.FirstOrDefault(c => c.Type == PowerBIToken.ClaimTypes.Version);
            var wcnClaim = decodedToken.Claims.FirstOrDefault(c => c.Type == PowerBIToken.ClaimTypes.WorkspaceCollectionName);
            var widClaim = decodedToken.Claims.FirstOrDefault(c => c.Type == PowerBIToken.ClaimTypes.WorkspaceId);
            var ridCliam = decodedToken.Claims.FirstOrDefault(c => c.Type == PowerBIToken.ClaimTypes.ReportId);
            var usernameClaim = decodedToken.Claims.FirstOrDefault(c => c.Type == PowerBIToken.ClaimTypes.Username);
            var rolesClaim = decodedToken.Claims.FirstOrDefault(c => c.Type == PowerBIToken.ClaimTypes.Roles);

            Assert.AreEqual("PowerBISDK", decodedToken.Issuer);
            Assert.IsTrue(decodedToken.Audiences.Contains("https://analysis.windows.net/powerbi/api"));
            Assert.IsTrue(decodedToken.ValidTo >= DateTime.UtcNow);
            Assert.IsTrue(decodedToken.ValidTo <= DateTime.UtcNow.AddHours(1));
            Assert.AreEqual("0.2.0", versionClaim.Value);
            Assert.AreEqual("Contoso", wcnClaim.Value);
            Assert.AreEqual(workspaceId, widClaim.Value);
            Assert.AreEqual(reportId, ridCliam.Value);
            Assert.AreEqual("TestUser", usernameClaim.Value);
            Assert.AreEqual("TestRole", rolesClaim.Value);
        }
开发者ID:ChrisMBenson,项目名称:PowerBI-CSharp,代码行数:31,代码来源:PowerBITokenTests.cs

示例4: CreateToken

        public static JwtSecurityToken CreateToken(
            string issuer = null,
            string audience = null,
            IEnumerable<string> scope = null,
            int ttl = 360,
            List<Claim> additionalClaims = null,
            X509Certificate2 signingCertificate = null)
        {
            if (additionalClaims == null)
            {
                additionalClaims = new List<Claim>();
            }

            if (scope != null && scope.Any())
            {
                scope.ToList().ForEach(s => additionalClaims.Add(new Claim("scope", s)));
            }

            var credential = new X509SigningCredentials(signingCertificate ?? DefaultSigningCertificate);

            var token = new JwtSecurityToken(
                issuer ?? DefaultIssuer,
                audience ?? DefaultAudience,
                additionalClaims,
                DateTime.UtcNow,
                DateTime.UtcNow.AddSeconds(ttl),
                credential);

            token.Header.Add(
                "kid", Base64Url.Encode(credential.Certificate.GetCertHash()));

            return token;
        }
开发者ID:ryanmar,项目名称:IdentityServer3.AccessTokenValidation,代码行数:33,代码来源:TokenFactory.cs

示例5: Get

        // GET api/profileapi?accesstoken=
        public UserProfile Get(string accesstoken)
        {
            JwtSecurityToken jwToken = new JwtSecurityToken(accesstoken);
            var Issuer = ConfigurationRepository.Global.IssuerUri;

            if (jwToken.Issuer.ToLower().Equals(Issuer.ToLower()))
            {
                RelyingParty rp;
                if (RelyingPartyRepository.TryGet(jwToken.Audience, out rp))
                {                    
                    try
                    {
                        var claims = ValidateJwtToken(jwToken, rp);
                        return UserManagementRepository.GetByUsername(claims.Name);
                    }

                    catch (SecurityTokenValidationException ex)
                    {
                        throw new UnauthorizedAccessException();
                    }
                    catch (Exception e)
                    {
                        throw new UnauthorizedAccessException();
                    }
                }
                else
                {
                    throw new Exception("RP is false");
                }
            }
            else
            {
                throw new Exception("Issuer is false");
            }
        }
开发者ID:gotshoo,项目名称:Thinktecture.IdentityServer.v2,代码行数:36,代码来源:ProfileApiController.cs

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

示例7: JwtSecurityTokenHandler_Extensibility

        public void JwtSecurityTokenHandler_Extensibility()
        {
            DerivedJwtSecurityTokenHandler handler = new DerivedJwtSecurityTokenHandler()
            {
                DerivedTokenType = typeof(DerivedJwtSecurityToken)
            };

            JwtSecurityToken jwt =
                new JwtSecurityToken
                (
                    issuer: Issuers.GotJwt,
                    audience: Audiences.AuthFactors,
                    claims: ClaimSets.Simple(Issuers.GotJwt, Issuers.GotJwt),
                    signingCredentials: KeyingMaterial.DefaultSymmetricSigningCreds_256_Sha2,
                    expires: DateTime.UtcNow + TimeSpan.FromHours(10),
                    notBefore: DateTime.UtcNow
                );

            string encodedJwt = handler.WriteToken(jwt);
            TokenValidationParameters tvp = new TokenValidationParameters()
            {
                IssuerSigningKey = KeyingMaterial.DefaultSymmetricSecurityKey_256,
                ValidateAudience = false,
                ValidIssuer = Issuers.GotJwt,
            };

            ValidateDerived(encodedJwt, handler, tvp, ExpectedException.NoExceptionExpected);
        }
开发者ID:vebin,项目名称:azure-activedirectory-identitymodel-extensions-for-dotnet,代码行数:28,代码来源:ExtensibilityTests.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: DecodeToken

        public IHttpActionResult DecodeToken(string access_token)
        {
            var tokenReceived = new JwtSecurityToken(access_token);

            var publicOnly = new RSACryptoServiceProvider();
            publicOnly.FromXmlString(_configuration.PublicKey.FromBase64String());
            var validationParameters = new TokenValidationParameters
            {
                ValidIssuer = _configuration.Issuer
               ,ValidAudience = "http://mysite.com"
               ,IssuerSigningToken = new RsaSecurityToken(publicOnly)
               ,ValidateLifetime = true
            };

            var recipientTokenHandler = new JwtSecurityTokenHandler();
            SecurityToken securityToken;
            var claimsPrincipal = recipientTokenHandler.ValidateToken(access_token, validationParameters, out securityToken);

            var currentTime = (long) (DateTime.UtcNow - new DateTime(1970, 1, 1)).TotalSeconds;

            if (tokenReceived.Payload.Exp < currentTime)
            {
                throw new SecurityTokenValidationException(string.Format("Lifetime validation failed. The token is expired. ValidTo: '{0}' Current time: '{1}'.", tokenReceived.ValidTo, DateTime.UtcNow));
            }
          
            return Ok(new
            {
                header = tokenReceived.Header,
                payload = tokenReceived.Payload,
                current = currentTime
            });
        }
开发者ID:girmateshe,项目名称:OAuth,代码行数:32,代码来源:JwtController.cs

示例10: CreateJsonWebToken

        /// <summary>
        /// Creates the json web token.
        /// </summary>
        /// <param name="token">The token.</param>
        /// <param name="credentials">The credentials.</param>
        /// <returns></returns>
        protected virtual string CreateJsonWebToken(Token token, SigningCredentials credentials)
        {
            var jwt = new JwtSecurityToken(
                token.Issuer,
                token.Audience,
                token.Claims,
                DateTimeHelper.UtcNow,
                DateTimeHelper.UtcNow.AddSeconds(token.Lifetime),
                credentials);

            // amr is an array - if there is only a single value turn it into an array
            if (jwt.Payload.ContainsKey("amr"))
            {
                var amrValue = jwt.Payload["amr"] as string;
                if (amrValue != null)
                {
                    jwt.Payload["amr"] = new string[] { amrValue };
                }
            }

            var x509credential = credentials as X509SigningCredentials;
            if (x509credential != null)
            {
                jwt.Header.Add("kid", Base64Url.Encode(x509credential.Certificate.GetCertHash()));
            }

            var handler = new JwtSecurityTokenHandler();
            return handler.WriteToken(jwt);
        }
开发者ID:0mn1bu5,项目名称:IdentityServer3,代码行数:35,代码来源:DefaultTokenSigningService.cs

示例11: ValidateToken

        private static bool ValidateToken(string encodedToken, string userEmail, User.AppType appType)
        {
            JwtSecurityToken token = new JwtSecurityToken(encodedToken);

            if (token.Claims == null)
            {
                return false;
            }

            Dictionary<string, string> claimVals = token.Claims.ToDictionary(x => x.Type, x => x.Value);

            if (claimVals["iss"] != "accounts.google.com" ||
                claimVals["azp"] != ConfidentialData.GoogleClientIdDictionary[appType] ||
                claimVals["aud"] != ConfidentialData.GoogleWebAppClientId ||
                claimVals["email"] != userEmail)
            {
                return false;
            }

            // Check token hasn't expired
            DateTime expirationDate = new DateTime(1970, 1, 1, 0, 0, 0, DateTimeKind.Utc);
            expirationDate = expirationDate.AddSeconds(int.Parse(claimVals["exp"]));

            // This is a valid token for this app if it's still in date!
            return expirationDate.ToLocalTime() >= DateTime.Now;
        }
开发者ID:GSDan,项目名称:Speeching_Server,代码行数:26,代码来源:AccountController.cs

示例12: CreateSecurityToken

        protected virtual SecurityToken CreateSecurityToken(ProtocolResponse oauthResponse)
        {
            string tokenType = oauthResponse.BodyParameters["token_type"];
            string accessTokenString = oauthResponse.BodyParameters["access_token"];

            var token = new JwtSecurityToken(accessTokenString);
            return token;
        }
开发者ID:gauravsri,项目名称:TokenClient,代码行数:8,代码来源:ClientCredentialsFlowBase.cs

示例13: Callback

        public async Task<ActionResult> Callback(string code, string state)
        {
            CheckState(state);

            using (var client = new HttpClient())
            {
                var resp = await client.PostAsync("https://accounts.google.com/o/oauth2/token",
                                 new FormUrlEncodedContent(new Dictionary<string, string>
                                                               {
                                                                   {"code", code},
                                                                   {"redirect_uri", RedirectUri},
                                                                   {"grant_type", "authorization_code"},
                                                                   {"client_id", ClientId},
                                                                   {"client_secret", ClientSecret}
                                                               }));
                resp.EnsureSuccessStatusCode();
                var tokenResp = await resp.Content.ReadAsAsync<TokenResponse>();

                var certs = await GoogleCertificates.GetCertificates();

                var tokenHandler = new JwtSecurityTokenHandler
                {
                    CertificateValidator = new GoogleCertificateValidator(certs.ToDictionary(t => t.Value.GetCertHashString(), t => t.Value))
                };

                var validationParameters = new TokenValidationParameters()
                {
                    AllowedAudience = ClientId,
                    ValidIssuer = "accounts.google.com",
                    SigningTokens = certs.Select(p => new X509SecurityToken(p.Value))
                };
                var principal = tokenHandler.ValidateToken(tokenResp.id_token, validationParameters);

                var jwt = new JwtSecurityToken(tokenResp.id_token);

                var viewModel = new ViewModel
                                    {
                                        JwtHeader = jwt.Header,
                                        JwtPayload = jwt.Payload,
                                        Principal = principal
                                    };

                client.DefaultRequestHeaders.Authorization = new AuthenticationHeaderValue("Bearer", tokenResp.access_token);
                resp = await client.GetAsync("https://www.googleapis.com/tasks/v1/users/@me/lists");
                resp.EnsureSuccessStatusCode();
                var taskLists = await resp.Content.ReadAsAsync<TaskLists>();
                foreach(var list in taskLists.items)
                {
                    resp = await client.GetAsync(string.Format("https://www.googleapis.com/tasks/v1/lists/{0}/tasks",list.id));
                    resp.EnsureSuccessStatusCode();
                    var taskList = await resp.Content.ReadAsAsync<TaskList>();
                    viewModel.Tasks.AddRange(taskList.items.Select(item => item.title));
                }
                
                return View(viewModel);
            }
        }
开发者ID:pmhsfelix,项目名称:NDC13-OIDC,代码行数:57,代码来源:OidcController.cs

示例14: CreateClaimsIdentity

 protected override ClaimsIdentity CreateClaimsIdentity(JwtSecurityToken jwt, string issuer, TokenValidationParameters validationParameters)
 {
     OrganisationIdentity result = null;
     ClaimsIdentity claimsIdentity = base.CreateClaimsIdentity(jwt, issuer, validationParameters);
     if (claimsIdentity != null)
         result = new OrganisationIdentity(claimsIdentity);
     Threading.Thread.CurrentPrincipal = new ClaimsPrincipal(result);
     return result;
 }
开发者ID:CreatorDev,项目名称:DeviceServer,代码行数:9,代码来源:OrganisationSecurityTokenHandler.cs

示例15: Index

        //
        // GET: /UserProfile/
        public async Task<ActionResult> Index()
        {
            //
            // Retrieve the user's name, tenantID, and access token since they are parameters used to query the Graph API.
            //
            UserProfile profile;
            string jwtToken = ClaimsPrincipal.Current.FindFirst(Configuration.ClaimsJwtToken).Value;
            JwtSecurityToken token = new JwtSecurityToken(jwtToken);
            string userObjectID = ClaimsPrincipal.Current.FindFirst(Configuration.ClaimsObjectidentifier).Value;
            
            AuthenticationContext authContext = new AuthenticationContext(Configuration.Authority, new NaiveSessionCache(userObjectID));
            try
            {
                ActiveDirectoryClient activeDirectoryClient = Factory.GetActiveDirectoryClientAsApplication(jwtToken);
                User userProfile = (User)await activeDirectoryClient.Users.GetByObjectId(userObjectID).ExecuteAsync();
                List<string> membergroups = (await userProfile.GetMemberGroupsAsync(false)).ToList();
                var groups = await activeDirectoryClient.Groups.ExecuteAsync();
                profile = new UserProfile();
                profile.Token = token;
                profile.MemberGroups = membergroups;
                profile.AllGroups = groups.CurrentPage;
                profile.User = userProfile;
                return View(profile);
            }
            catch (Exception)
            {
                //
                // If the call failed, then drop the current access token and show the user an error indicating they might need to sign-in again.
                //
                var todoTokens = authContext.TokenCache.ReadItems().Where(a => a.Resource == Configuration.GraphResourceId);
                foreach (TokenCacheItem tci in todoTokens)
                    authContext.TokenCache.DeleteItem(tci);

                //
                // If refresh is set to true, the user has clicked the link to be authorized again.
                //
                if (Request.QueryString["reauth"] == "True")
                {
                    //
                    // Send an OpenID Connect sign-in request to get a new set of tokens.
                    // If the user still has a valid session with Azure AD, they will not be prompted for their credentials.
                    // The OpenID Connect middleware will return to this controller after the sign-in response has been handled.
                    //
                    HttpContext.GetOwinContext().Authentication.Challenge(OpenIdConnectAuthenticationDefaults.AuthenticationType);
                }

                //
                // The user needs to re-authorize.  Show them a message to that effect.
                //
                profile = new UserProfile();
                ViewBag.ErrorMessage = "AuthorizationRequired";
                return View(profile);

            }
        }
开发者ID:rhlbenjamin,项目名称:azure-media-services-samples,代码行数:57,代码来源:UserProfileController.cs


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