Last active
September 17, 2021 06:59
-
-
Save hieumoscow/d0822ab87597da1a5f94f166ee216e4e to your computer and use it in GitHub Desktop.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
using System.Collections.Generic; | |
using System.Net; | |
using Microsoft.Azure.Functions.Worker; | |
using Microsoft.Azure.Functions.Worker.Http; | |
using Microsoft.Extensions.Logging; | |
using Azure.Identity; | |
using Azure.Security.KeyVault.Keys.Cryptography; | |
using System.Text; | |
using System.Security.Cryptography; | |
using System.Threading.Tasks; | |
using Microsoft.IdentityModel.Tokens; | |
using System.IdentityModel.Tokens.Jwt; | |
using Newtonsoft.Json; | |
using JwtHeaderParameterNames = Microsoft.IdentityModel.JsonWebTokens.JwtHeaderParameterNames; | |
namespace Company.Function | |
{ | |
public static class jwt_sign | |
{ | |
private static ILogger _logger; | |
[Function("jwt_sign")] | |
public static async Task<HttpResponseData> Run([HttpTrigger(AuthorizationLevel.Anonymous, "get", "post")] HttpRequestData req, | |
FunctionContext executionContext) | |
{ | |
_logger = executionContext.GetLogger("jwt_sign"); | |
_logger.LogInformation("C# HTTP trigger function processed a request."); | |
var response = req.CreateResponse(HttpStatusCode.OK); | |
response.Headers.Add("Content-Type", "text/plain; charset=utf-8"); | |
var rsaCryptoClient = new CryptographyClient(new System.Uri("https://hieuexamplekv.vault.azure.net/keys/logic/aa5c64a48038423da77482fd11b0a926"), new ManagedIdentityCredential()); | |
var token = new JwtSecurityToken( | |
"issuer", | |
"aud", | |
null, | |
null, | |
null); | |
var header = Base64UrlEncoder.Encode(JsonConvert.SerializeObject(new Dictionary<string, string>() | |
{ | |
{ JwtHeaderParameterNames.Alg, "RS256" }, | |
{ JwtHeaderParameterNames.Kid, "https://hieuexamplekv.vault.azure.net/keys/logic/aa5c64a48038423da77482fd11b0a926" }, | |
{ JwtHeaderParameterNames.Typ, "JWT" } | |
})); | |
var byteData = Encoding.UTF8.GetBytes(header + "." + token.EncodedPayload); | |
var hasher = new SHA256CryptoServiceProvider(); | |
var digest1 = hasher.ComputeHash(byteData); | |
var signature = await rsaCryptoClient.SignAsync(SignatureAlgorithm.RS256, digest1); | |
var ret1 = $"{header}.{token.EncodedPayload}.{Base64UrlEncoder.Encode(signature.Signature)}"; | |
response.WriteString(ret1); | |
return response; | |
} | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment