本文整理汇总了C#中System.IdentityModel.Tokens.JwtSecurityTokenHandler.ValidateToken方法的典型用法代码示例。如果您正苦于以下问题:C# JwtSecurityTokenHandler.ValidateToken方法的具体用法?C# JwtSecurityTokenHandler.ValidateToken怎么用?C# JwtSecurityTokenHandler.ValidateToken使用的例子?那么恭喜您, 这里精选的方法代码示例或许可以为您提供帮助。您也可以进一步了解该方法所在类System.IdentityModel.Tokens.JwtSecurityTokenHandler
的用法示例。
在下文中一共展示了JwtSecurityTokenHandler.ValidateToken方法的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");
}
}
示例2: 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;
}
示例3: Validate
public ClaimsPrincipal Validate(string jwtTokenAsBase64, JwtOptions options)
{
var tokenHandler = new JwtSecurityTokenHandler();
string keyAsUtf8 = options.JwtSigningKeyAsUtf8;
byte[] keyAsBytes = Encoding.UTF8.GetBytes(keyAsUtf8);
SecurityToken signingToken = new BinarySecretSecurityToken(keyAsBytes);
var tokenValidationParameters = new TokenValidationParameters
{
IssuerSigningToken = signingToken,
ValidAudience = options.Audience,
ValidIssuer = options.Issuer
};
ClaimsPrincipal principal;
try
{
SecurityToken validatedToken;
principal = tokenHandler.ValidateToken(jwtTokenAsBase64, tokenValidationParameters,
out validatedToken);
}
catch (Exception ex)
{
Debug.Write(ex, "error");
principal = new ClaimsPrincipal(new ClaimsIdentity(authenticationType:""));
}
return principal;
}
示例4: ValidateJwtAccessTokenAsync
protected virtual Task<TokenValidationResult> ValidateJwtAccessTokenAsync(string jwt)
{
var handler = new JwtSecurityTokenHandler();
handler.Configuration = new SecurityTokenHandlerConfiguration();
handler.Configuration.CertificateValidationMode = X509CertificateValidationMode.None;
handler.Configuration.CertificateValidator = X509CertificateValidator.None;
var parameters = new TokenValidationParameters
{
ValidIssuer = _settings.GetIssuerUri(),
SigningToken = new X509SecurityToken(_settings.GetSigningCertificate()),
AllowedAudience = string.Format(Constants.AccessTokenAudience, _settings.GetIssuerUri())
};
try
{
var id = handler.ValidateToken(jwt, parameters);
return Task.FromResult(new TokenValidationResult
{
Claims = id.Claims
});
}
catch (Exception ex)
{
_logger.ErrorFormat("JWT token validation error: {0}", ex.ToString());
return Task.FromResult(new TokenValidationResult
{
IsError = true,
Error = Constants.ProtectedResourceErrors.InvalidToken
});
}
}
示例5: 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
});
}
示例6: 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;
}
示例7: 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);
}
}
示例8: 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;
}
示例9: ReadToken
public static ClaimsPrincipal ReadToken(string token, out SecurityToken _token)
{
TokenValidationParameters _params = new TokenValidationParameters()
{
ValidateIssuer = true,
ValidIssuer = TokenConstants.TokenIssuer,
ValidAudience = TokenConstants.TokenAudience,
IssuerSigningToken = new BinarySecretSecurityToken(TokenConstants.TokenKey),
};
_token = null;
var jwt = new JwtSecurityTokenHandler() { TokenLifetimeInMinutes = TokenConstants.TokenLifetimeInMinutes };
return jwt.ValidateToken(token, _params, out _token);
}
示例10: Can_create_and_consume_jwt_tokens
public void Can_create_and_consume_jwt_tokens()
{
const string issuer = "http://issuer.webapibook.net";
const string audience = "[email protected]";
const int lifetimeInMinutes = 5;
var tokenHandler = new JwtSecurityTokenHandler();
var symmetricKey = GetRandomBytes(256 / 8);
var signingCredentials = new SigningCredentials(
new InMemorySymmetricSecurityKey(symmetricKey),
"http://www.w3.org/2001/04/xmldsig-more#hmac-sha256",
"http://www.w3.org/2001/04/xmlenc#sha256");
var now = DateTime.UtcNow;
var claims = new[]
{
new Claim("sub", "[email protected]"),
new Claim("email", "[email protected]"),
new Claim("name", "Alice"),
};
var token = new JwtSecurityToken(issuer, audience, claims,
new Lifetime(now, now.AddMinutes(lifetimeInMinutes)), signingCredentials);
var tokenString = tokenHandler.WriteToken(token);
var parts = tokenString.Split('.');
Assert.Equal(3, parts.Length);
var validationParameters = new TokenValidationParameters()
{
AllowedAudience = audience,
SigningToken = new BinarySecretSecurityToken(symmetricKey),
ValidIssuer = issuer,
};
tokenHandler.NameClaimType = ClaimTypes.NameIdentifier;
var principal = tokenHandler.ValidateToken(tokenString, validationParameters);
var identity = principal.Identities.First();
Assert.Equal("[email protected]", identity.Name);
Assert.Equal("[email protected]", identity.Claims.First(c => c.Type == ClaimTypes.NameIdentifier).Value);
Assert.Equal("[email protected]", identity.Claims.First(c => c.Type == ClaimTypes.Email).Value);
Assert.Equal("Alice", identity.Claims.First(c => c.Type == "name").Value);
Assert.Equal(issuer, identity.Claims.First().Issuer);
}
示例11: consume_JSONWebTokenString
public void consume_JSONWebTokenString()
{
string tokenString = "";//produce_JSONWebTokenString(); //get from somewhere
var token = new JwtSecurityToken(tokenString);
var validationParams = new TokenValidationParameters
{
ValidIssuer = "http://myIssuer",
ValidAudiences = new List<String>() { "HttpStyleUriParser://myResource" },
IssuerSigningToken = GetSigningKey()
};
var handler = new JwtSecurityTokenHandler();
SecurityToken securityToken;
var principat = handler.ValidateToken(tokenString, validationParams, out securityToken);
}
示例12: ValidateIdentityTokenAsync
private static IEnumerable<Claim> ValidateIdentityTokenAsync(string token, string audience, X509Certificate2 certificate)
{
var parameters = new TokenValidationParameters
{
ValidAudience = audience,
ValidIssuer = "http://localhost:22530",
IssuerSigningToken = new X509SecurityToken(certificate)
};
var handler = new JwtSecurityTokenHandler();
SecurityToken jwt;
var id = handler.ValidateToken(token, parameters, out jwt);
return id.Claims;
}
示例13: ValidateIdentityTokenAsync
private async Task<IEnumerable<Claim>> ValidateIdentityTokenAsync(string token, string state)
{
var result = await Request
.GetOwinContext()
.Authentication
.AuthenticateAsync("TempCookie");
if (result == null)
{
throw new InvalidOperationException("No temp cookie");
}
if (state != result.Identity.FindFirst("state").Value)
{
throw new InvalidOperationException("invalid state");
}
var parameters = new TokenValidationParameters
{
ValidAudience = "implicitclient",
ValidIssuer = "https://idsrv3.com",
IssuerSigningToken = new X509SecurityToken(
X509
.LocalMachine
.TrustedPeople
.SubjectDistinguishedName
.Find("CN=idsrv3test", false)
.First())
};
var handler = new JwtSecurityTokenHandler();
SecurityToken jwt;
var id = handler.ValidateToken(token, parameters, out jwt);
if (id.FindFirst("nonce").Value !=
result.Identity.FindFirst("nonce").Value)
{
throw new InvalidOperationException("Invalid nonce");
}
Request
.GetOwinContext()
.Authentication
.SignOut("TempCookie");
return id.Claims;
}
示例14: ReadJwtToken
public static ClaimsPrincipal ReadJwtToken(this string token, SecurityTokenDescriptor tokenDescriptor )
{
var tokenHandler = new JwtSecurityTokenHandler();
var certificate = (tokenDescriptor.SigningCredentials as X509SigningCredentials).Certificate;
var validationParameters = new TokenValidationParameters
{
ValidAudience = tokenDescriptor.AppliesToAddress,
ValidIssuer = tokenDescriptor.TokenIssuerName,
IssuerSigningToken = new X509SecurityToken(certificate)
};
var validatedToken = new JwtSecurityToken() as SecurityToken;
var principal = tokenHandler.ValidateToken(token, validationParameters, out validatedToken);
return principal;
}
示例15: GenerateAccessToken
public Task<string> GenerateAccessToken(SecurityTokenDescriptor tokenDescriptor, TokenValidationParameters validationParameters)
{
return Task.Run(() =>
{
tokenDescriptor.SigningCredentials = new X509SigningCredentials(this.cert);
var tokenHandler = new JwtSecurityTokenHandler();
var securityToken = tokenHandler.CreateToken(tokenDescriptor);
var accessToken = tokenHandler.WriteToken(securityToken);
validationParameters.IssuerSigningToken = new X509SecurityToken(this.cert);
SecurityToken validatedToken;
tokenHandler.ValidateToken(accessToken, validationParameters, out validatedToken);
return accessToken;
});
}