本文整理汇总了C#中System.IdentityModel.Tokens.JwtSecurityTokenHandler类的典型用法代码示例。如果您正苦于以下问题:C# JwtSecurityTokenHandler类的具体用法?C# JwtSecurityTokenHandler怎么用?C# JwtSecurityTokenHandler使用的例子?那么恭喜您, 这里精选的类代码示例或许可以为您提供帮助。
JwtSecurityTokenHandler类属于System.IdentityModel.Tokens命名空间,在下文中一共展示了JwtSecurityTokenHandler类的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: CreateTokenButton_Click
private void CreateTokenButton_Click(object sender, RoutedEventArgs e)
{
var principal = Principal.Create(AuthenticationTypes.Password, new Claim(ClaimTypes.Name, UserName.Text));
var sts = new Thinktecture.IdentityServer.Protocols.STS();
SecurityToken token;
var success = sts.TryIssueToken(
new EndpointReference("https://booking.oceanicairlines.com/"),
principal,
TokenTypes.JsonWebToken,
out token);
if (success)
{
var tokenString = new JwtSecurityTokenHandler().WriteToken(token);
Output.Text = "Encoded JWT token:" + Environment.NewLine + tokenString + Environment.NewLine + Environment.NewLine;
var tokenParts = tokenString.Split('.');
Output.Text += "JWT header:" + Environment.NewLine + DecodeBase64(tokenParts[0]) + Environment.NewLine + Environment.NewLine;
Output.Text += "JWT body:" + Environment.NewLine + DecodeBase64(tokenParts[1]) + Environment.NewLine + Environment.NewLine;
Output.Text += "JWT signature:" + Environment.NewLine + tokenParts[2];
}
else
{
Output.Text = "Could not issue token.";
}
}
示例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;
}
示例4: 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);
}
示例5: 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;
}
示例6: 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;
}
示例7: 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;
}
示例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
});
}
示例9: CreateTokenString
public static string CreateTokenString(JwtSecurityToken token)
{
JwtSecurityTokenHandler.OutboundClaimTypeMap = new Dictionary<string, string>();
var handler = new JwtSecurityTokenHandler();
return handler.WriteToken(token);
}
示例10: 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();
}
示例11: 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;
}
}
示例12: 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;
}
示例13: 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);
}
示例14: 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);
}
示例15: CreateAndValidateTokens_DuplicateClaims
public void CreateAndValidateTokens_DuplicateClaims()
{
SecurityToken validatedToken;
string encodedJwt = IdentityUtilities.CreateJwtToken(
new SecurityTokenDescriptor
{
AppliesToAddress = IdentityUtilities.DefaultAudience,
SigningCredentials = IdentityUtilities.DefaultSymmetricSigningCredentials,
Subject = new ClaimsIdentity(ClaimSets.DuplicateTypes(IdentityUtilities.DefaultIssuer, IdentityUtilities.DefaultIssuer)),
TokenIssuerName = IdentityUtilities.DefaultIssuer,
});
JwtSecurityTokenHandler tokenHandler = new JwtSecurityTokenHandler();
JwtSecurityTokenHandler.InboundClaimFilter.Add("aud");
JwtSecurityTokenHandler.InboundClaimFilter.Add("exp");
JwtSecurityTokenHandler.InboundClaimFilter.Add("iat");
JwtSecurityTokenHandler.InboundClaimFilter.Add("iss");
JwtSecurityTokenHandler.InboundClaimFilter.Add("nbf");
ClaimsPrincipal claimsPrincipal = tokenHandler.ValidateToken(encodedJwt, IdentityUtilities.DefaultSymmetricTokenValidationParameters, out validatedToken);
Assert.IsTrue(IdentityComparer.AreEqual<IEnumerable<Claim>>(claimsPrincipal.Claims, ClaimSets.DuplicateTypes(IdentityUtilities.DefaultIssuer, IdentityUtilities.DefaultIssuer), new CompareContext { IgnoreProperties = true, IgnoreSubject = true }));
JwtSecurityTokenHandler.InboundClaimFilter.Clear();
}
开发者ID:richardschneider,项目名称:azure-activedirectory-identitymodel-extensions-for-dotnet,代码行数:25,代码来源:CreateAndValidateTokens.cs