Azure B2B Token auth once of best way for auth.
Way to Generate Auth Token:
public async Task<DataResponse> GenerateB2BToken()
{
List<KeyValuePair<string, string>> postData = new List<KeyValuePair<string, string>>
{
new KeyValuePair<string, string>(CLIENT_CREDENTIALS),
new KeyValuePair<string, string>(B2CClientId),
new KeyValuePair<string, string>(B2CClientSecret),
new KeyValuePair<string, string>(B2BResource)
};
using (var client = new HttpClient())
{
_httpClient.DefaultRequestHeaders.Accept.Clear();
_httpClient.DefaultRequestHeaders.Accept.Add(new MediaTypeWithQualityHeaderValue("application/json"));
FormUrlEncodedContent content = new FormUrlEncodedContent((List<KeyValuePair<string, string>>)postData);
using HttpResponseMessage response = await client.PostAsync(urlPath, content);
{
var responsedata = await response.Content.ReadAsStringAsync();
return responsedata;
}
}
if (!string.IsNullOrEmpty(response))
{
TokenAuthData token = JsonConvert.DeserializeObject<TokenAuthData>(response);
if (token != null && !string.IsNullOrWhiteSpace(token.token_type) && !string.IsNullOrWhiteSpace(token.access_token))
{
return Json( new { Token = $"{token.token_type} {token.access_token}" });
}
}
return null;
}
Token Validation :
public async Task<bool> ValidateB2BToken(string idtoken)
{
string _token = idtoken.Replace(BEARER, "").Replace(BEARER.ToUpper(), "").Trim();
if (!string.IsNullOrEmpty(_token))
{
try
{
var token = new JwtSecurityToken(jwtEncodedString: _token);
if (token.Claims != null && token.Claims.Count() > 0)
{
var expiry = long.Parse(token.Claims.Where(x => x.Type == "exp").Select(x => x.Value).FirstOrDefault());
var aud = token.Audiences.Where(x => x == "your client id").Select(x => x).FirstOrDefault();
long epochTime = await ToUnixTime(DateTime.UtcNow);
//validate expiry and audience
if (!string.IsNullOrEmpty(aud) && epochTime <= expiry)
{
return true;
}
else
return false;
}
}
catch (Exception ex)//Token expired case
{
return false;
}
}
return false;
}
private async Task<long> ToUnixTime(DateTime date)
{
var epoch = new DateTime(1970, 1, 1, 0, 0, 0, DateTimeKind.Utc);
return await Task.FromResult( Convert.ToInt64((date - epoch).TotalSeconds));
}
Above way you can validate Token auth B2b