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


C# JwtSecurityTokenHandler.CanReadToken方法代码示例

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


在下文中一共展示了JwtSecurityTokenHandler.CanReadToken方法的7个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的C#代码示例。

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

示例2: GetCurrentUserID

        public static string GetCurrentUserID(string token)
        {
            JwtSecurityTokenHandler handler = new JwtSecurityTokenHandler();

            var canReadToken = handler.CanReadToken(token);

            if (canReadToken)
            {
                var tempToken = handler.ReadToken(token) as JwtSecurityToken;
                ///TODO: this could be used to HTTP request the metadata...
                //issuer = tt.Issuer;

                var claims = new List<Claim>();
                foreach (var claim in tempToken.Claims)
                {
                    claims.Add(claim);
                }
                var principal = new ClaimsPrincipal(new ClaimsIdentity(claims));

                Thread.CurrentPrincipal = principal;

            }

            return GetCurrentUserID();

            ///TODO: wire up real token validate...
            ///
            /*
            TokenValidationParameters validationParameters =
               new TokenValidationParameters()
               {
                   ValidAudience = ConfigurationManager.AppSettings["ida:Audience"],
                   ValidateIssuer = false,
                   ValidateActor = false,
                   ValidateIssuerSigningKey = false,
                   CertificateValidator = X509CertificateValidator.None

               };

            SecurityToken jwtToken = null;
            var p = handler.ValidateToken(token, validationParameters, out jwtToken);
            */

        }
开发者ID:MicrosoftDX,项目名称:AzureLens,代码行数:44,代码来源:UserHelper.cs

示例3: ValidateJWT

        private IPrincipal ValidateJWT(string jwt)
        {
            var handler = new JwtSecurityTokenHandler { CertificateValidator = X509CertificateValidator.None };
            if (!handler.CanReadToken(jwt))
            {
                return null;
            }

            var parameters = new TokenValidationParameters
            {
                ValidAudience = GetValidAudiance(),
                ValidateIssuer = false,
                IssuerSigningTokens = OpenIdConfiguration.GetIssuerSigningKeys(jwt)
            };

            try
            {
                var user = handler.ValidateToken(jwt, parameters);
                var upnClaim = user.Claims.Where(c => c.Type == upnClaimType).Select(c => c.Value).FirstOrDefault();
                var emailClaim = user.Claims.Where(c => c.Type == emailClaimType).Select(c => c.Value).FirstOrDefault();
                var nameClaim = user.Claims.Where(c => c.Type == nameClaimType).Select(c => c.Value).FirstOrDefault();
                var issuerClaim = user.Claims.Where(c => c.Type == issuerClaimType).Select(c => c.Value).FirstOrDefault();
                var puidClaim = user.Claims.Where(c => c.Type == puidClaimType ).Select(c => c.Value).FirstOrDefault();
                var altSecId = user.Claims.Where(c => c.Type == altSecIdClaimType).Select(c => c.Value).FirstOrDefault();
                var principal = new TryWebsitesPrincipal(new TryWebsitesIdentity(upnClaim ?? emailClaim ?? user.Identity.Name, altSecId ?? puidClaim, GetIssuerName(altSecId ?? puidClaim)));

                return principal;
            }
            catch (Exception e)
            {
                //failed validating
                SimpleTrace.Diagnostics.Error(e, "Error reading claims {jwt}", jwt);
            }

            return null;
        }
开发者ID:davidlai-msft,项目名称:SimpleWAWS,代码行数:36,代码来源:BaseOpenIdConnectAuthProvider.cs

示例4: GetHlsKeyDeliveryUrlAndFetchKeyWithADJWTAuthUsingADOpenConnectDiscovery

        public void GetHlsKeyDeliveryUrlAndFetchKeyWithADJWTAuthUsingADOpenConnectDiscovery()
        {
            //
            // The Client ID is used by the application to uniquely identify itself to Azure AD.
            // The App Key is a credential used by the application to authenticate to Azure AD.
            // The Tenant is the name of the Azure AD tenant in which this application is registered.
            // The AAD Instance is the instance of Azure, for example public Azure or Azure China.
            // The Authority is the sign-in URL of the tenant.
            //
            string aadInstance = ConfigurationManager.AppSettings["ida:AADInstance"];
            string tenant = ConfigurationManager.AppSettings["ida:Tenant"];
            string clientId = ConfigurationManager.AppSettings["ida:ClientId"];
            string appKey = ConfigurationManager.AppSettings["ida:AppKey"];

            string authority = String.Format(CultureInfo.InvariantCulture, aadInstance, tenant);

            //
            // To authenticate to the To Do list service, the client needs to know the service's App ID URI.
            // To contact the To Do list service we need it's URL as well.
            //
            string appResourceId = ConfigurationManager.AppSettings["app:AppResourceId"];

            IContentKey contentKey = null;
            IContentKeyAuthorizationPolicy contentKeyAuthorizationPolicy = null;
            IContentKeyAuthorizationPolicyOption policyOption = null;

            var authContext = new AuthenticationContext(authority);
            var clientCredential = new ClientCredential(clientId, appKey);

            try
            {
                byte[] expectedKey = null;
                contentKey = CreateTestKey(_mediaContext, ContentKeyType.EnvelopeEncryption, out expectedKey, "GetHlsKeyDeliveryUrlAndFetchKeyWithADJWTAuthUsingADOpenConnectDiscovery"+Guid.NewGuid().ToString());

                TokenRestrictionTemplate tokenRestrictionTemplate = new TokenRestrictionTemplate(TokenType.JWT);
                tokenRestrictionTemplate.OpenIdConnectDiscoveryDocument = new OpenIdConnectDiscoveryDocument("https://login.windows.net/common/.well-known/openid-configuration");
                var result = authContext.AcquireToken(appResourceId, clientCredential);
                string jwtTokenString = result.AccessToken;

                JwtSecurityTokenHandler handler = new JwtSecurityTokenHandler();
                Assert.IsTrue(handler.CanReadToken(jwtTokenString));
                JwtSecurityToken token = handler.ReadToken(jwtTokenString) as JwtSecurityToken;
                Assert.IsNotNull(token);

                tokenRestrictionTemplate.Audience =  token.Audiences.First();
                tokenRestrictionTemplate.Issuer = token.Issuer;

                string optionName = "GetHlsKeyDeliveryUrlAndFetchKeyWithJWTAuthentication";
                string requirements = TokenRestrictionTemplateSerializer.Serialize(tokenRestrictionTemplate);
                policyOption = ContentKeyAuthorizationPolicyOptionTests.CreateOption(_mediaContext, optionName, ContentKeyDeliveryType.BaselineHttp, requirements, null, ContentKeyRestrictionType.TokenRestricted);

                List<IContentKeyAuthorizationPolicyOption> options = new List<IContentKeyAuthorizationPolicyOption>
                {
                    policyOption
                };

                contentKeyAuthorizationPolicy = CreateTestPolicy(_mediaContext, String.Empty, options, ref contentKey);

                Uri keyDeliveryServiceUri = contentKey.GetKeyDeliveryUrl(ContentKeyDeliveryType.BaselineHttp);
                Assert.IsNotNull(keyDeliveryServiceUri);

                // Enable once all accounts are enabled for per customer Key Delivery Urls
                //Assert.IsTrue(keyDeliveryServiceUri.Host.StartsWith(_mediaContext.Credentials.ClientId));

                KeyDeliveryServiceClient keyClient = new KeyDeliveryServiceClient(RetryPolicy.DefaultFixed);
                byte[] key = keyClient.AcquireHlsKeyWithBearerHeader(keyDeliveryServiceUri, jwtTokenString);

                string expectedString = GetString(expectedKey);
                string fetchedString = GetString(key);
                Assert.AreEqual(expectedString, fetchedString);
            }
            finally
            {
                CleanupKeyAndPolicy(contentKey, contentKeyAuthorizationPolicy, policyOption);
            }
        }
开发者ID:chayu,项目名称:azure-sdk-for-media-services,代码行数:76,代码来源:GetKeyDeliveryUrlTests.cs

示例5: JwtSecurityTokenHandler_ReadToken

        public void JwtSecurityTokenHandler_ReadToken()
        {
            JwtSecurityTokenHandler handler = new JwtSecurityTokenHandler();
            ExpectedException expectedException = ExpectedException.ArgumentOutOfRangeException();
            try
            {
                handler.MaximumTokenSizeInBytes = 0;
                expectedException.ProcessNoException();
            }
            catch (Exception ex)
            {
                expectedException.ProcessException(ex);
            }

            Assert.IsFalse(handler.CanReadToken("1"), string.Format("Expected JWTSecurityTokenHandler.CanReadToken to be false"));

            expectedException = ExpectedException.ArgumentException(substringExpected: "IDX10708:");
            try
            {
                handler.ReadToken("1");
                expectedException.ProcessNoException();
            }
            catch (Exception ex)
            {
                expectedException.ProcessException(ex);
            }
        }
开发者ID:vebin,项目名称:azure-activedirectory-identitymodel-extensions-for-dotnet,代码行数:27,代码来源:JwtSecurityTokenHandlerTests.cs

示例6: RunCanReadStringVariation

        private bool RunCanReadStringVariation(string securityToken, JwtSecurityTokenHandler tokenHandler, ExpectedException expectedException)
        {
            bool retVal = false;
            try
            {
                retVal = tokenHandler.CanReadToken(securityToken);
                expectedException.ProcessNoException();
            }
            catch (Exception ex)
            {
                expectedException.ProcessException(ex);
            }

            return retVal;
        }
开发者ID:vebin,项目名称:azure-activedirectory-identitymodel-extensions-for-dotnet,代码行数:15,代码来源:JwtSecurityTokenHandlerTests.cs

示例7: RunCanReadXmlVariation

        private bool RunCanReadXmlVariation(XmlReader reader, JwtSecurityTokenHandler tokenHandler,ExpectedException expectedException)
        {
            bool retVal = false;
            try
            {
                retVal = tokenHandler.CanReadToken(reader);
                expectedException.ProcessNoException();
            }
            catch(Exception ex)
            {
                expectedException.ProcessException(ex);
            }

            return retVal;
        }
开发者ID:vebin,项目名称:azure-activedirectory-identitymodel-extensions-for-dotnet,代码行数:15,代码来源:JwtSecurityTokenHandlerTests.cs


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