本文整理汇总了C#中System.IdentityModel.Tokens.SigningCredentials类的典型用法代码示例。如果您正苦于以下问题:C# SigningCredentials类的具体用法?C# SigningCredentials怎么用?C# SigningCredentials使用的例子?那么恭喜您, 这里精选的类代码示例或许可以为您提供帮助。
SigningCredentials类属于System.IdentityModel.Tokens命名空间,在下文中一共展示了SigningCredentials类的15个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的C#代码示例。
示例1: 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);
}
示例2: 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
示例3: TokenController
public TokenController(
IOptions<OAuthBearerAuthenticationOptions> bearerOptions,
SigningCredentials signingCredentials)
{
_bearerOptions = bearerOptions.Options;
_signingCredentials = signingCredentials;
}
示例4: CreateJsonWebToken
/// <summary>
/// Creates the json web token.
/// </summary>
/// <param name="token">The token.</param>
/// <param name="credentials">The credentials.</param>
/// <returns>The signed JWT</returns>
protected virtual async Task<string> CreateJsonWebToken(Token token, SigningCredentials credentials)
{
var header = CreateHeader(token, credentials);
var payload = CreatePayload(token);
return await SignAsync(new JwtSecurityToken(header, payload));
}
示例5: 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);
}
示例6: 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();
}
示例7: SimpleWebToken
/// <summary>
///
/// </summary>
/// <param name="rawData">Token URL encoded.</param>
/// <param name="credentials">HMAC key.</param>
public SimpleWebToken(String rawData, SigningCredentials credentials)
{
if (null == rawData)
throw new ArgumentNullException("rawData");
if (null == credentials)
throw new ArgumentNullException("credentials");
this.id = SecurityUniqueId.Create().Value;
this.Values = GetNameValues(rawData);
this.SigningCredentials = credentials;
// Split hash from data
String[] rawParts = rawData.Split(new String[] { "&HMACSHA256=" }, StringSplitOptions.RemoveEmptyEntries);
if (2 != rawParts.Length)
throw new SecurityTokenException("Malformed Token");
this.rawData = rawParts[0];
this.hash = HttpUtility.UrlDecode(rawParts[1]);
// Calculate token expiration value
String expiresText = Values[WrapConstants.SimpleWebTokenParameters.ExpiresOn];
UInt64 expiresValue;
if (null == expires || false == UInt64.TryParse(expiresText, out expiresValue))
throw new SecurityTokenException("Malformed Token");
this.expires = new DateTime(1970, 1, 1, 0, 0, 0, 0).AddSeconds(expiresValue);
}
示例8: CreateSamlToken
/// <summary>
/// Creates a SAML Token with the input parameters
/// </summary>
/// <param name="stsName">Name of the STS issuing the SAML Token</param>
/// <param name="proofToken">Associated Proof Token</param>
/// <param name="issuerToken">Associated Issuer Token</param>
/// <param name="proofKeyEncryptionToken">Token to encrypt the proof key with</param>
/// <param name="samlConditions">The Saml Conditions to be used in the construction of the SAML Token</param>
/// <param name="samlAttributes">The Saml Attributes to be used in the construction of the SAML Token</param>
/// <returns>A SAML Token</returns>
public static SamlSecurityToken CreateSamlToken(string stsName,
BinarySecretSecurityToken proofToken,
SecurityToken issuerToken,
SecurityToken proofKeyEncryptionToken,
SamlConditions samlConditions,
IEnumerable<SamlAttribute> samlAttributes)
{
// Create a security token reference to the issuer certificate
SecurityKeyIdentifierClause skic = issuerToken.CreateKeyIdentifierClause<X509ThumbprintKeyIdentifierClause>();
SecurityKeyIdentifier issuerKeyIdentifier = new SecurityKeyIdentifier(skic);
// Create an encrypted key clause containing the encrypted proof key
byte[] wrappedKey = proofKeyEncryptionToken.SecurityKeys[0].EncryptKey(SecurityAlgorithms.RsaOaepKeyWrap, proofToken.GetKeyBytes());
SecurityKeyIdentifierClause encryptingTokenClause = proofKeyEncryptionToken.CreateKeyIdentifierClause<X509ThumbprintKeyIdentifierClause>();
EncryptedKeyIdentifierClause encryptedKeyClause = new EncryptedKeyIdentifierClause(wrappedKey, SecurityAlgorithms.RsaOaepKeyWrap, new SecurityKeyIdentifier(encryptingTokenClause) );
SecurityKeyIdentifier proofKeyIdentifier = new SecurityKeyIdentifier(encryptedKeyClause);
// Create a comfirmationMethod for HolderOfKey
List<string> confirmationMethods = new List<string>(1);
confirmationMethods.Add(SamlConstants.HolderOfKey);
// Create a SamlSubject with proof key and confirmation method from above
SamlSubject samlSubject = new SamlSubject(null,
null,
null,
confirmationMethods,
null,
proofKeyIdentifier);
// Create a SamlAttributeStatement from the passed in SamlAttribute collection and the SamlSubject from above
SamlAttributeStatement samlAttributeStatement = new SamlAttributeStatement(samlSubject, samlAttributes);
// Put the SamlAttributeStatement into a list of SamlStatements
List<SamlStatement> samlSubjectStatements = new List<SamlStatement>();
samlSubjectStatements.Add(samlAttributeStatement);
// Create a SigningCredentials instance from the key associated with the issuerToken.
SigningCredentials signingCredentials = new SigningCredentials(issuerToken.SecurityKeys[0],
SecurityAlgorithms.RsaSha1Signature,
SecurityAlgorithms.Sha1Digest,
issuerKeyIdentifier);
// Create a SamlAssertion from the list of SamlStatements created above and the passed in
// SamlConditions.
SamlAssertion samlAssertion = new SamlAssertion("_" + Guid.NewGuid().ToString(),
stsName,
DateTime.UtcNow,
samlConditions,
new SamlAdvice(),
samlSubjectStatements
);
// Set the SigningCredentials for the SamlAssertion
samlAssertion.SigningCredentials = signingCredentials;
// Create a SamlSecurityToken from the SamlAssertion and return it
return new SamlSecurityToken(samlAssertion);
}
示例9: AuthController
public AuthController(ISessionProvider<AefSession> sessionProvider,
IOptions<JwtBearerOptions> bearerOptions,
SigningCredentials signingCredentials,
IAccountManager accountManager)
:base(sessionProvider)
{
this.m_BearerOptions = bearerOptions.Value;
this.m_SigningCredentials = signingCredentials;
this.m_AccountManager = accountManager;
}
示例10: AuthController
public AuthController(ISessionScopeFactory sessionScopeFactory,
IOptions<OAuthBearerAuthenticationOptions> bearerOptions,
SigningCredentials signingCredentials,
IAccountManager accountManager)
:base(sessionScopeFactory)
{
//this.m_BearerOptions = bearerOptions.Options;
this.m_SigningCredentials = signingCredentials;
this.m_AccountManager = accountManager;
this.m_SessionScopeFactory = sessionScopeFactory;
}
示例11: CreateJsonWebToken
protected virtual string CreateJsonWebToken(Token token, SigningCredentials credentials)
{
var jwt = new JwtSecurityToken(
token.Issuer,
token.Audience,
token.Claims,
new Lifetime(DateTime.UtcNow, DateTime.UtcNow.AddSeconds(token.Lifetime)),
credentials);
var handler = new JwtSecurityTokenHandler();
return handler.WriteToken(jwt);
}
示例12: EnvelopedSignatureWriter
/// <summary>
/// Initializes an instance of <see cref="EnvelopedSignatureWriter"/>. The returned writer can be directly used
/// to write the envelope. The signature will be automatically generated when
/// the envelope is completed.
/// </summary>
/// <param name="innerWriter">Writer to wrap/</param>
/// <param name="signingCredentials">SigningCredentials to be used to generate the signature.</param>
/// <param name="referenceId">The reference Id of the envelope.</param>
/// <param name="securityTokenSerializer">SecurityTokenSerializer to serialize the signature KeyInfo.</param>
/// <exception cref="ArgumentNullException">One of he input parameter is null.</exception>
/// <exception cref="ArgumentException">The string 'referenceId' is either null or empty.</exception>
public EnvelopedSignatureWriter(XmlWriter innerWriter, SigningCredentials signingCredentials, string referenceId, SecurityTokenSerializer securityTokenSerializer)
{
if (innerWriter == null)
{
throw DiagnosticUtility.ExceptionUtility.ThrowHelperArgumentNull("innerWriter");
}
if (signingCredentials == null)
{
throw DiagnosticUtility.ExceptionUtility.ThrowHelperArgumentNull("signingCredentials");
}
if (string.IsNullOrEmpty(referenceId))
{
throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(new ArgumentException(SR.GetString(SR.ID0006), "referenceId"));
}
if (securityTokenSerializer == null)
{
throw DiagnosticUtility.ExceptionUtility.ThrowHelperArgumentNull("securityTokenSerializer");
}
// Remember the user's writer here. We need to finally write out the signed XML
// into this writer.
_dictionaryManager = new DictionaryManager();
_innerWriter = innerWriter;
_signingCreds = signingCredentials;
_referenceId = referenceId;
_tokenSerializer = securityTokenSerializer;
_signatureFragment = new MemoryStream();
_endFragment = new MemoryStream();
_writerStream = new MemoryStream();
XmlDictionaryWriter effectiveWriter = XmlDictionaryWriter.CreateTextWriter(_writerStream, Encoding.UTF8, false);
// Initialize the base writer to the newly created writer. The user should write the XML
// to this.
base.InitializeInnerWriter(effectiveWriter);
_hashAlgorithm = CryptoHelper.CreateHashAlgorithm(_signingCreds.DigestAlgorithm);
_hashStream = new HashStream(_hashAlgorithm);
base.InnerWriter.StartCanonicalization(_hashStream, false, null);
//
// Add tracing for the un-canonicalized bytes
//
if (DiagnosticUtility.ShouldTraceVerbose)
{
_preCanonicalTracingStream = new MemoryStream();
base.InitializeTracingWriter(new XmlTextWriter(_preCanonicalTracingStream, Encoding.UTF8));
}
}
示例13: CreateToken
private string CreateToken(ClaimsIdentity identity, SigningCredentials signingCredentials)
{
var tokenDescriptor = new SecurityTokenDescriptor
{
AppliesToAddress = Audience,
Subject = identity,
TokenIssuerName = TokenIssuerName,
SigningCredentials = signingCredentials,
};
var handler = new JwtSecurityTokenHandler();
var token = handler.CreateToken(tokenDescriptor);
return handler.WriteToken(token);
}
示例14: BoxJWTAuth
/// <summary>
/// Constructor for JWT authetication
/// </summary>
/// <param name="boxConfig">Config contains information about client id, client secret, enterprise id, private key, private key password, public key id </param>
public BoxJWTAuth(IBoxConfig boxConfig)
{
this.boxConfig = boxConfig;
var pwf = new PEMPasswordFinder(this.boxConfig.JWTPrivateKeyPassword);
AsymmetricCipherKeyPair key;
using (var reader = new StringReader(this.boxConfig.JWTPrivateKey))
{
key = (AsymmetricCipherKeyPair)new PemReader(reader, pwf).ReadObject();
}
var rsa = DotNetUtilities.ToRSA((RsaPrivateCrtKeyParameters)key.Private);
this.credentials = new SigningCredentials(new RsaSecurityKey(rsa), SecurityAlgorithms.RsaSha256Signature, SecurityAlgorithms.Sha256Digest);
}
示例15: 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);
}