How can I perform unattended oauth / openid authentication to WebAPI?

点点圈 提交于 2019-12-10 18:13:53

问题


Imagine a client and service application registered in Windows Azure.

The client is a console and runs unattended on-premise (e.g. performing tests overnight) The service is a WebAPI service protected by oAuth and normally accessed using OpenID Connect, hosted in Azure.

How can the client authenticate to the service WITHOUT any sort of user login interaction (i.e. the app authenticates itself to the service using ADAL .Net)?

I tried the ADAL .Net Daemon to WebAPI sample but it still pops up an authentication dialog...

Thanks!

[edit] Here's some code to show very roughly how I communicate from the client. All the 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;

That just produces login page HTML...

I've also tried adding [HostAuthentication("OAuth2Bearer")] etc. to the service api controller and adding in 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,
    });

回答1:


EDIT: Re-reading the original post, I think I now understand what's going on. You mention that you have OpenId Connect on your app, and that when you hit the web API you get back HTML. I suspect the OpenId Connect middleware is being triggered when you hit the Web API, instead of the Oauth2 middleware. If that is the case, 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 have redirect-based middleware and OAuth2 protected resource middleware coexist on the same project.

Original answer: Have you tried https://github.com/AzureADSamples/NativeClient-Headless-DotNet? That should do what you you are looking for. Sorry for terseness, on the phone :-) HTH V.



来源:https://stackoverflow.com/questions/25777676/how-can-i-perform-unattended-oauth-openid-authentication-to-webapi

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!