0

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 ?

Neo
  • 15,491
  • 59
  • 215
  • 405

1 Answers1

1

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

Dylan Morley
  • 1,656
  • 12
  • 21
  • thanks but i do not have ClientSecret inside web.config of that webapi , it only have `ClientId`,`AADInstance`,`Domain`,`TenantId `,`PostLogoutRedirectUri` i understand we can get `clientSecret` from portal.azure.com but is it good way to store it inside webconfig ? – Neo Sep 28 '18 at 14:04
  • You will need to create the secret value for the AAD clientId means i need to generate clientSecret ? sorry i didn't understand – Neo Sep 28 '18 at 14:08
  • 1
    Have a look at this SO answer that describes creating a Key - https://stackoverflow.com/a/42446822/1538039. Go to the portal, find the AAD application, then follow the instructions to create a key. Once you've done that, you can use it in your console app to generate a token and call your API – Dylan Morley Sep 28 '18 at 14:53
  • I think I can use Keyvalue to generate token if i do not have secret key ? is it true ? – Neo Oct 01 '18 at 14:36