本文整理汇总了C#中System.IdentityModel.Tokens.JwtSecurityTokenHandler.WriteToken方法的典型用法代码示例。如果您正苦于以下问题:C# JwtSecurityTokenHandler.WriteToken方法的具体用法?C# JwtSecurityTokenHandler.WriteToken怎么用?C# JwtSecurityTokenHandler.WriteToken使用的例子?那么恭喜您, 这里精选的方法代码示例或许可以为您提供帮助。您也可以进一步了解该方法所在类System.IdentityModel.Tokens.JwtSecurityTokenHandler
的用法示例。
在下文中一共展示了JwtSecurityTokenHandler.WriteToken方法的15个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的C#代码示例。
示例1: CreateTokenString
public static string CreateTokenString(JwtSecurityToken token)
{
JwtSecurityTokenHandler.OutboundClaimTypeMap = new Dictionary<string, string>();
var handler = new JwtSecurityTokenHandler();
return handler.WriteToken(token);
}
示例2: 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;
}
示例3: 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;
}
示例4: 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);
}
示例5: 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;
}
}
示例6: 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;
}
示例7: SetJwtAuthorizationHeader
/// <summary>
/// Sets a JWT authorization header on the default request headers of an <see cref="HttpClient"/>.
/// </summary>
/// <param name="client">The client for which to set the authorization header.</param>
/// <param name="signingCertificate">The signing certificate to sign the token.</param>
/// <param name="appliesToAddress">The address for which the token is considered valid.</param>
/// <param name="claims">The claims that define the user. Leave null for an anonymous user.</param>
/// <param name="tokenIssuerName">Name of the token issuer. Defaults to "self".</param>
/// <param name="tokenDuration">
/// The token duration for which it's considered valid. Defaults to 2 hours.
/// </param>
/// <exception cref="ArgumentNullException">
/// <paramref name="signingCertificate"/> is <see langword="null"/>.
/// </exception>
/// <exception cref="ArgumentException">
/// <paramref name="appliesToAddress"/> is <see langword="null"/> or empty.
/// </exception>
/// <exception cref="ArgumentException">
/// <paramref name="tokenIssuerName"/> is <see langword="null"/> or empty.
/// </exception>
public static void SetJwtAuthorizationHeader(
this HttpClient client,
X509Certificate2 signingCertificate,
string appliesToAddress,
IEnumerable<Claim> claims = null,
string tokenIssuerName = "self",
TimeSpan? tokenDuration = null)
{
signingCertificate.AssertNotNull("signingCertificate");
appliesToAddress.AssertNotNullOrWhitespace("appliesToAddress");
tokenIssuerName.AssertNotNullOrWhitespace("tokenIssuerName");
var now = DateTime.UtcNow;
var tokenHandler = new JwtSecurityTokenHandler();
var tokenDescriptor = new SecurityTokenDescriptor
{
Subject = new ClaimsIdentity(claims),
TokenIssuerName = tokenIssuerName,
AppliesToAddress = appliesToAddress,
Lifetime = new Lifetime(now, now.Add(tokenDuration ?? TimeSpan.FromHours(2))),
SigningCredentials = new X509SigningCredentials(signingCertificate)
};
SecurityToken token = tokenHandler.CreateToken(tokenDescriptor);
string tokenString = tokenHandler.WriteToken(token);
client.DefaultRequestHeaders.Authorization = new AuthenticationHeaderValue("Bearer", tokenString);
}
示例8: 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);
}
示例9: 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
});
}
示例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: BearerToken
static string BearerToken()
{
var signatureAlgorithm = "http://www.w3.org/2001/04/xmldsig-more#hmac-sha256";
var digestAlgorithm = "http://www.w3.org/2001/04/xmlenc#sha256";
var securityKey = Convert.FromBase64String(mainKey);
var inMemKey = new InMemorySymmetricSecurityKey(securityKey);
ClaimsIdentity identity = new ClaimsIdentity();
identity.AddClaim(new Claim("scope", "Full"));
JwtSecurityTokenHandler handler = new JwtSecurityTokenHandler();
SecurityToken securityToken = handler.CreateToken(new SecurityTokenDescriptor()
{
TokenType = "Bearer",
Lifetime = new Lifetime(DateTime.UtcNow, DateTime.UtcNow.AddHours(1)),
SigningCredentials = new SigningCredentials(inMemKey, signatureAlgorithm, digestAlgorithm),
//This data I would get by matching the jwtSecurityToken.Audience to database or something
TokenIssuerName = "PaulsSite",
AppliesToAddress = "http://JoshsSite",
Subject = identity
}
);
return handler.WriteToken(securityToken);
}
示例12: GetJwtToken
public static string GetJwtToken(this ClaimsIdentity identity, SecurityTokenDescriptor tokenDescriptor)
{
if (identity == null || tokenDescriptor == null) return null;
tokenDescriptor.Subject = identity;
var tokenHandler = new JwtSecurityTokenHandler();
var token = tokenHandler.CreateToken(tokenDescriptor);
var tokenString = tokenHandler.WriteToken(token);
return tokenString;
}
示例13: 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;
}
示例14: Execute
#pragma warning disable 1998
public override async Task<Result> Execute()
{
Result result = new Result();
try
{
Console.Out.WriteLine("Generating access token...");
// encryption key
string key_s = ConfigurationManager.ConnectionStrings["JWTKey"].ConnectionString;
byte[] key_b = new byte[key_s.Length * sizeof(char)];
System.Buffer.BlockCopy(key_s.ToCharArray(), 0, key_b, 0, key_b.Length);
// create the token
JwtSecurityTokenHandler tokenHandler = new JwtSecurityTokenHandler();
ClaimsIdentity subject = new ClaimsIdentity(new Claim[] { new Claim(ClaimTypes.Uri, SiteUrl, ClaimValueTypes.String) });
SecurityTokenDescriptor tokenDescriptor = new SecurityTokenDescriptor
{
Subject = subject,
TokenIssuerName = "SpSat",
Lifetime = new Lifetime(DateTime.UtcNow, DateTime.UtcNow.AddHours(4)),
SigningCredentials = new SigningCredentials(new InMemorySymmetricSecurityKey(key_b), "http://www.w3.org/2001/04/xmldsig-more#hmac-sha256", "http://www.w3.org/2001/04/xmlenc#sha256")
};
SecurityToken token = tokenHandler.CreateToken(tokenDescriptor);
using (ClientContext context = new ClientContext(SiteUrl))
{
// authenticate
string usernamePassword = ConfigurationManager.ConnectionStrings["SharePoint"].ConnectionString;
dynamic usernamePassword_j = Newtonsoft.Json.JsonConvert.DeserializeObject(usernamePassword);
string username = usernamePassword_j.username;
string password = usernamePassword_j.password;
SecureString password_s = new SecureString();
Array.ForEach(password.ToCharArray(), password_s.AppendChar);
context.Credentials = new SharePointOnlineCredentials(username, password_s);
// write the token to the property bag
PropertyValues webProperties = context.Web.AllProperties;
webProperties["accessToken"] = tokenHandler.WriteToken(token);
context.Web.Update();
context.ExecuteQuery();
}
Console.Out.WriteLine("Completed generating access token.");
result.Status = Status.Success;
}
catch (Exception ex)
{
result.Status = Status.Failure;
result.Log.Add(ex.Message);
}
return result;
}
示例15: CreateTokenAsBase64
public static string CreateTokenAsBase64(this SecurityTokenDescriptor securityTokenDescriptor)
{
var tokenHandler = new JwtSecurityTokenHandler();
SecurityToken securityToken = tokenHandler.CreateToken(securityTokenDescriptor);
string token = tokenHandler.WriteToken(securityToken);
string tokenAsBase64 = token;
return tokenAsBase64;
}