Neo
Neo

Reputation: 16219

How to generate token for WebAPI who is hosted on Azure AD?

I have one api which is hosted on azure AD.

I have below code inside Startup.cs

 public partial class Startup
    {
        private static readonly string ClientId = ConfigurationManager.AppSettings["ida:ClientId"];
        private static readonly string AadInstnace = ConfigurationManager.AppSettings["ida:AADInstance"];
        private static readonly string TenantId = ConfigurationManager.AppSettings["ida:TenantId"];
        private static readonly string PostLogoutRedirectUri = ConfigurationManager.AppSettings["ida:PostLogoutRedirectUri"];
        private static readonly string Authority = AadInstnace + TenantId;

        public void ConfigureAuth(IAppBuilder app)
        {
            app.SetDefaultSignInAsAuthenticationType(CookieAuthenticationDefaults.AuthenticationType);
            app.UseCookieAuthentication(new CookieAuthenticationOptions());
            app.UseOpenIdConnectAuthentication(new OpenIdConnectAuthenticationOptions
            {
                ClientId = ClientId,
                Authority = Authority,
                PostLogoutRedirectUri = PostLogoutRedirectUri
            });
        }
    }

I do not see any postback token generation code here :(

how can I get a token which i can use to call this webapi from console app ?

Upvotes: 0

Views: 198

Answers (1)

Dylan Morley
Dylan Morley

Reputation: 1726

Have a look at nuget package - Microsoft.IdentityModel.Clients.ActiveDirectory (https://www.nuget.org/packages/Microsoft.IdentityModel.Clients.ActiveDirectory)

You can then generate an access token using code along the line of,

var authority = "https://login.microsoftonline.com/your-aad-tenant-id/oauth2/token";
var context = new AuthenticationContext(authority);
var resource = "https://some-resource-you-want-access-to";

var clientCredentials = new ClientCredential(clientId, clientSecret);

var result = await context.AcquireTokenAsync(resource, clientCredentials);  

You will need to create the secret value for the AAD clientId

Upvotes: 1

Related Questions