Angular4,Azure Active Directory和WebApi2后端,承载令牌无法正常工作

时间:2017-09-19 13:41:41

标签: c# asp.net-web-api owin ninject azure-active-directory

我有一个Angular4客户端,它使用ADAL.js处理AAD的身份验证 登录后,我可以成功查看我的用户名以及我的JWT令牌。

现在我想连接到WebApi2服务。我在令牌中将令牌作为承载令牌传递,但由于某种原因,我不断获得 401"授权已被拒绝" 来自我的API。

Angular4客户端

headers.append('Accept', 'application/json');
headers.append('Content-Type', 'application/json');
headers.append('Authorization', 'Bearer ' + this.adalService.accessToken);

请求标题
Request header

回复标题
Response header

Startup.cs

public partial class Startup
{
    public void Configuration(IAppBuilder app)
    {
        ConfigureAuth(app);
        ConfigureNinject(app);
    }
}

Startup.Auth.cs

public partial class Startup
{
    public void ConfigureAuth(IAppBuilder app)
    {
        app.UseWindowsAzureActiveDirectoryBearerAuthentication(new WindowsAzureActiveDirectoryBearerAuthenticationOptions
        {
            Tenant = ConfigurationManager.AppSettings["ida:Tenant"],
            TokenValidationParameters = new TokenValidationParameters
            {
                ValidAudience = ConfigurationManager.AppSettings["ida:Audience"],
            }
        }
    }
}

Startup.Ninject.cs

public partial class Startup
{
    public void ConfigureNinject(IAppBuilder app)
    {
        var kernel = CreateKernel();
        app.UseNinjectMiddleware(() => kernel).UseNinjectWebApi(WebApiConfig.GetConfiguration());

        return kernel;
    }

    private static IKernel CreateKernel()
    {
        var kernel = new StandardKernel();
        kernel.Bind<Func<IKernel>>().ToMethod(ctx => () => new Bootstrapper().Kernel);
        kernel.Bind<IHttpModule>().To<HttpApplicationInitializationHttpModule>();

        RegisterServices(kernel);
        GlobalConfiguration.Configuration.DependencyResolver = new NinjectDependencyResolver(kernel);
        return kernel;
    }

    private static void RegisterServices(IKernel kernel)
    {
        // some bindings here
    }
}

UsersController.cs

public class UsersController : ApiController
{
    public async Task<IHttpActionResult> Get
    {
        return Ok("test");
    }
}

更新:解决方案
正如Navya Canumalla在评论中指出的那样,adal.js和ida中使用的clientId值:Web.config中的Audience必须是相同的值。这不是这种情况。我已经更正了,现在按预期工作。

0 个答案:

没有答案