从AngularJS / ADAL.js客户端访问WebApI时出现401未经授权的错误

时间:2017-03-10 04:38:38

标签: angularjs asp.net-web-api2 adal.js

我有一个带有角度前端的自托管网络api应用程序,现在我需要开始通过Azure Active Directory验证用户。

我已经下载了SinglePageApp示例,我已经设置好了并让它成功运行。 https://github.com/Azure-Samples/active-directory-angularjs-singlepageapp-dotnet-webapi

在对我自己的应用程序进行必要的更改后,我可以成功地将用户重定向到Azure登录屏幕,并使用adal.js / adal_angular.js返回userProfile。每当我调用我的API时,我都会收到401个未经授权的错误,但是使用Fiddler,我可以看到每次调用都会将持有者令牌添加到HTTP头中。

这是我的AdalAngular设置:

.config(["$httpProvider", "adalAuthenticationServiceProvider", ($httpProvider, adalProvider) => {
            adalProvider.init(
            {
                instance: "https://login.microsoftonline.com/",
                tenant: "<snip>.onmicrosoft.com",
                clientId: "<snip>",
                extraQueryParameter: "nux=1",
                cacheLocation: "localStorage" // enable this for IE, as sessionStorage does not work for localhost.
            },
            $httpProvider);

这是我的startup.cs代码:

public void Configuration(IAppBuilder appBuilder)
    {

        ConfigureWebApi(appBuilder);
        ConfigureAuth(appBuilder);
        ConfigureFileSystem(appBuilder);
        appBuilder.UseCors(Microsoft.Owin.Cors.CorsOptions.AllowAll);
    }

private void ConfigureWebApi(IAppBuilder appBuilder)
    {
        // Configure Web API for self-host. 
        HttpConfiguration config = new HttpConfiguration();
        config.MapHttpAttributeRoutes();
        config.Routes.MapHttpRoute(
            name: "DefaultApi",
            routeTemplate: "api/{controller}/{id}",
            defaults: new { id = RouteParameter.Optional }
        );

        appBuilder.UseWebApi(config);
    }

    private void ConfigureAuth(IAppBuilder app)
    {
        app.UseWindowsAzureActiveDirectoryBearerAuthentication(
            new WindowsAzureActiveDirectoryBearerAuthenticationOptions
            {
                Tenant = ConfigurationManager.AppSettings["ActiveDirectoryTenant"],
                Audience = ConfigurationManager.AppSettings["ActiveDirectoryApplicationId"]
            });
    }

    private void ConfigureFileSystem(IAppBuilder appBuilder)
    {

        //Set the Welcome page to test if Owin is hosted properly
        appBuilder.UseWelcomePage("/welcome.html");
        appBuilder.UseErrorPage(new Microsoft.Owin.Diagnostics.ErrorPageOptions() { ShowExceptionDetails = true });
        var physicalFileSystem = new PhysicalFileSystem(@".\wwwroot");
        if (ConfigurationManager.AppSettings.AllKeys.Contains("ContentPath"))
        {
            var path = ConfigurationManager.AppSettings["ContentPath"];
            physicalFileSystem = new PhysicalFileSystem(path);
        }
        FileServerOptions fileOptions = new FileServerOptions();

        fileOptions.EnableDefaultFiles = true;
        fileOptions.RequestPath = PathString.Empty;
        fileOptions.FileSystem = physicalFileSystem;
        fileOptions.DefaultFilesOptions.DefaultFileNames = new[] { "index.html" };
        fileOptions.StaticFileOptions.FileSystem = fileOptions.FileSystem = physicalFileSystem;
        fileOptions.StaticFileOptions.ServeUnknownFileTypes = true;
        appBuilder.UseFileServer(fileOptions);
    }

ActiveDirectoryTenant和ActiveDirectoryApplicationId在我的app.config中,并且与我的角度adalProvider.init代码中配置的内容完全匹配。

最后,我的ApiController看起来像这样:

 [Authorize]
[RoutePrefix("api/connection")]
public class ServerConnectionController : ApiController
{
    [Route("all")]
    [HttpGet]
    public HttpResponseMessage GetAllConnections()
    {
        HttpResponseMessage response;
        try
        {
            string owner = ClaimsPrincipal.Current.FindFirst(ClaimTypes.NameIdentifier).Value;
            var connections = _iDataAccess.GetAllConnections().ToList();
            response = Request.CreateResponse(HttpStatusCode.OK, connections);
        }
        catch (Exception ex)
        {
            response = GetExceptionResponseMessage(ex);
        }

        return response;
    }
}

如前所述,Fiddler捕获的HTTP请求标头看起来没问题,我的ADAL.js userInfo.profile上的aud属性是正确的appid。

有关可能遗漏的内容的任何建议? 请注意,这不是基于Web的本机应用程序,它是自托管的,这意味着Web服务作为Windows服务在localhost上运行,而不是在IIS中运行。

我已将网站配置为使用HTTPS,但无论HTTP或HTTPS流量如何,我都会遇到同样的问题。

感谢收听!

1 个答案:

答案 0 :(得分:0)

您需要将ConfigureAuth(appBuilder);声明为Startup.cs配置方法中的第一行。您可以找到一个很好的解释here,说明为什么需要将其声明为第一个。