I am trying to access the Auth0 Management API from my ASP .Net Core 1.1 Web API. According to Documentation I can do the following:
var apiClient = new ManagementApiClient("token", new Uri("https://YOUR_AUTH0_DOMAIN/api/v2"));
var allClients = await apiClient.Clients.GetAllAsync();
To get a list of all clients. This requires that I provide a token. Is this token the one that my web API receives from the calling client (in our case a web app and a IONIC2 phone app) when they call the web API? If so, anyone know how I can get that from my web API controller action? Or is this another token I should be getting from elsewhere?
Thank you…
The management API is called from your back-end so you can create the token before you call the API.
In .Net Core, I use something like this to create the client (this uses the Jose.Jwt library via nuget):
private ManagementApiClient GetClient(object scopes)
{
return new ManagementApiClient(_jwt.GenerateToken(scopes), new Uri($"https://{_auth0Settings.Domain}/api/v2/"));
}
Get the JWT token like this:
using System;
using System.Collections.Generic;
using Microsoft.Extensions.Options;
namespace App.Auth0
{
public class Jwt : IJwt
{
private readonly Auth0Settings _auth0Settings;
public Jwt(IOptions<Auth0Settings> authSettings)
{
_auth0Settings = authSettings.Value;
}
public string GenerateToken(object scopes)
{
var payload = new Dictionary<string, object>
{
{"iss", $"https://{_auth0Settings.Domain}" },
{"aud", _auth0Settings.ManagementApiKey},
{"sub", Guid.NewGuid().ToString("N")},
{"jti", Guid.NewGuid().ToString("N")},
{"iat", ToUnixTime(DateTime.Now).ToString()},
//{"exp", ToUnixTime(DateTime.Now.AddHours(10)).ToString()}, // This doesnt work
{"scopes", scopes}
};
return Jose.JWT.Encode(payload, Base64UrlDecode(_auth0Settings.ManagementApiGlobalSecret), Jose.JwsAlgorithm.HS256);
}
private byte] Base64UrlDecode(string arg)
{
string s = arg;
s = s.Replace('-', '+'); // 62nd char of encoding
s = s.Replace('_', '/'); // 63rd char of encoding
switch (s.Length % 4) // Pad with trailing '='s
{
case 0: break; // No pad chars in this case
case 2: s += "=="; break; // Two pad chars
case 3: s += "="; break; // One pad char
default:
throw new System.Exception(
"Illegal base64url string!");
}
return Convert.FromBase64String(s); // Standard base64 decoder
}
private long ToUnixTime(DateTime dateTime)
{
return (int)(dateTime.ToUniversalTime().Subtract(new DateTime(1970, 1, 1))).TotalSeconds;
}
}
}
Hope this helps