2

我创建了一个使用带有 OpenId 的 Azure Active Directory 身份验证的 MVC 应用程序。这对最终用户很有用,但我想向站点添加一个 webjob 来调用它自己的端点(用户将使用相同的 http post 方法)。我发现这个示例https://github.com/AzureADSamples/Daemon-DotNet允许服务器应用程序调用 webapi 端点。

我的授权配置类如下所示:

public class StartAuth
{
    private static string clientId = ConfigurationManager.AppSettings["ida:ClientId"];
    private static string aadInstance = ConfigurationManager.AppSettings["ida:AADInstance"];
    private static string tenant = ConfigurationManager.AppSettings["ida:Tenant"];
    private static string postLogoutRedirectUri = ConfigurationManager.AppSettings["ida:PostLogoutRedirectUri"];
    private static string audience = ConfigurationManager.AppSettings["ida:Audience"];

    string authority = String.Format(CultureInfo.InvariantCulture, aadInstance, tenant);

    public void Configuration(IAppBuilder app)
    {
        app.SetDefaultSignInAsAuthenticationType(CookieAuthenticationDefaults.AuthenticationType);

        app.UseCookieAuthentication(new CookieAuthenticationOptions());

        app.UseOpenIdConnectAuthentication(
            new OpenIdConnectAuthenticationOptions
            {
                ClientId = clientId,
                Authority = authority,
                PostLogoutRedirectUri = postLogoutRedirectUri,
            });

        app.UseWindowsAzureActiveDirectoryBearerAuthentication(
            new WindowsAzureActiveDirectoryBearerAuthenticationOptions
            {
                Tenant = tenant,
                TokenValidationParameters = new TokenValidationParameters
                {
                    ValidAudience = audience
                }
            });
    }
}

我的网络作业控制台应用程序的请求如下所示(我已经替换了不记名密钥和主机):

POST      
https://some-random-host/myendpoint     
HTTP/1.1
Authorization: Bearer key
Host: some-random-host
Content-Length: 0

来自服务器的响应如下所示(替换了主机、密钥、租户 ID,并截断了位置值):

HTTP/1.1 302 Found
Cache-Control: private
Content-Length: 0
Location: https://login.windows.net/tenant-id/oauth2/authorize....
Server: Microsoft-IIS/8.0
Set-Cookie: OpenIdConnect.nonce.u%noncekey; path=/; secure; HttpOnly
WWW-Authenticate: Bearer
X-AspNetMvc-Version: 5.2
X-AspNet-Version: 4.0.30319
X-Powered-By: ASP.NET
Set-Cookie: ARRAffinity=key;Path=/;Domain=some-random-host
Date: Thu, 19 Mar 2015 11:44:11 GMT

任何想法为什么服务器响应登录位置?当用户尝试访问经过身份验证的端点时,这显然很有效,但不适用于我的控制台应用程序。

提前感谢您的帮助。请让我知道是否有任何其他信息有用。

4

2 回答 2

1

这里有一篇相关的博客文章详细解释了

您的配置看起来正确,但您缺少处理程序的定义。

您需要在 API 控制器类中指定处理程序:

[HostAuthentication("OAuth2Bearer")]
[Authorize]
public class YourAPIController : ApiController
{

HostAuthentication 关键字描述了控制器的处理程序。

于 2015-03-20T22:35:23.237 回答
0

由于在使用密钥进行身份验证时 Azure WebJobs 未绑定到特定用户,因此您不能在指定用户的方法/控制器上具有授权属性。这完全有道理,但在 Omer 提醒我检查属性之前,我一直忽略了这一点。

事实上,用户实际上是空的。

所以与其拥有:[Authorize(Users="user@contoso.com"] 我只需要:[Authorize]

我不确定是否有办法指定只有 WebJob 具有权限。

于 2015-03-24T19:05:16.990 回答