Created
February 27, 2020 00:07
-
-
Save ahelland/71d51d1ce9620e366c1793e53b3878c9 to your computer and use it in GitHub Desktop.
Method for generating and mailing "magic links"
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
protected async Task SendSignInLinkAsync() | |
{ | |
string email = mailer.to.Email; | |
string token = BuildIdToken(email); | |
string link = BuildUrl(token); | |
string htmlTemplate = System.IO.File.ReadAllText("SignInTemplate.html"); | |
var apiKey = configuration.GetSection("MailerSettings")["SendGridApiKey"]; | |
var client = new SendGridClient(apiKey); | |
var plainTextContent = "You should be seeing a SignIn link below."; | |
var htmlContent = string.Format(htmlTemplate, email, link); | |
var msg = MailHelper.CreateSingleEmail(mailer.from, mailer.to, mailer.subject, plainTextContent, htmlContent); | |
var response = await client.SendEmailAsync(msg); | |
} | |
private string BuildIdToken(string Email) | |
{ | |
string B2CClientId = configuration.GetSection("MailerSettings")["B2CClientId"]; | |
double LinkExpiresAfterMinutes; | |
double.TryParse(configuration.GetSection("MailerSettings")["LinkExpiresAfterMinutes"], out LinkExpiresAfterMinutes); | |
string issuer = configuration.GetSection("MailerSettings")["issuer"]; | |
// All parameters sent to Azure AD B2C needs to be sent as claims | |
IList<System.Security.Claims.Claim> claims = new List<System.Security.Claims.Claim> | |
{ | |
new System.Security.Claims.Claim("email", Email, System.Security.Claims.ClaimValueTypes.String, issuer) | |
}; | |
// Create the token | |
JwtSecurityToken token = new JwtSecurityToken( | |
issuer, | |
B2CClientId, | |
claims, | |
DateTime.Now, | |
DateTime.Now.AddMinutes(LinkExpiresAfterMinutes), | |
SigningCredentials.Value); | |
// Get the representation of the signed token | |
JwtSecurityTokenHandler jwtHandler = new JwtSecurityTokenHandler(); | |
return jwtHandler.WriteToken(token); | |
} | |
private string BuildUrl(string token) | |
{ | |
string B2CSignInUrl = configuration.GetSection("MailerSettings")["B2CSignInUrl"]; | |
return $"{B2CSignInUrl}?id_token_hint={token}"; | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment