How can I do automatic oauth / openid authentication for WebAPI?

Imagine a client and service application registered with Windows Azure.

The client is a console and runs unattended (for example, running tests overnight) A service is an oAuth-protected WebAPI service typically available using OpenID Connect hosted in Azure.

How can a client authenticate to the service WITHOUT any user interaction (for example, an application authenticates to a service using ADAL.Net)?

I tried ADAL .Net Sample Daemon for WebAPI but it still opens an authentication dialog ...

Thank!

[ edit ] Here is some code showing very roughly how I interact with the client. All App IDs, etc. Are correct.

var authContext = new AuthenticationContext("https://login.windows.net/common");
var result = await authContext.AcquireTokenAsync(ServiceAppId, ClientCredential);
var client = new HttpClient
{
    BaseAddress = new Uri("https://localhost:44301/"),

};
client.DefaultRequestHeaders.Authorization = 
    new AuthenticationHeaderValue(
        AuthenticationHeaderScheme.Bearer, 
        result.AccessToken);
var response = await client.GetAsync("api/something");
var jsonString = response.Content.ReadAsStringAsync().Result;

      

This just creates an HTML login page ...

I also tried to add [HostAuthentication("OAuth2Bearer")]

etc. to the api controller of the service and add to the OWIN startup logic, but to no avail, e.g .:

app.UseWindowsAzureActiveDirectoryBearerAuthentication(
    new WindowsAzureActiveDirectoryBearerAuthenticationOptions
    {
        TokenValidationParameters = new TokenValidationParameters
        {
            ValidAudience = myRealm,
        },

        Tenant = "mytenant.onmicrosoft.com",
        AuthenticationType = BearerAuthenticationType.OAuth2Bearer,
    });

      

+3


source to share


1 answer


EDIT: After rereading the original post, I think I now understand what's going on. You mentioned that you have OpenId Connect in your application and when you hit the web API, you get HTML. I suspect that the OpenId Connect middleware starts when you hit the web API, not the Oauth2 middleware. If so, I recommend taking a look at http://www.cloudidentity.com/blog/2014/04/28/use-owin-azure-ad-to-secure-both-mvc-ux-and-web-api- in-the-same-project / for instructions on how to use redirect-based middleware and OAuth2 secure resource middleware in the same project.



Original answer: have you tried https://github.com/AzureADSamples/NativeClient-Headless-DotNet ? This should do what you are looking for. Sorry for your patience, on the phone :-) NTN V.

+2


source







All Articles