如何使用Azure AD访问令牌对.NET Core 2.1 API进行身份验证

时间:2019-01-26 02:11:18

标签: asp.net asp.net-mvc asp.net-core azure-active-directory

我正在运行一个使用Azure AD进行身份验证的.NET Core 2.1 Web MVC API应用程序。效果很好,我可以毫无问题地使用Azure AD帐户登录。我还有一个.NET应用程序,希望能够对此应用程序进行API调用。我有一个工人阶级,使用Oauth2 Client Credentials来获得广告访问令牌。我尝试了几种不同的方式通过邮递员传递访问令牌的过程,但是没有运气。我试图让一个班通过:

        public string GetProjects()
       {
           string token = GetToken();
           HttpClient client = new HttpClient();
           client.DefaultRequestHeaders.Authorization = new AuthenticationHeaderValue("Bearer", token);
           var response = client.GetAsync("https://localhost:5001/Jira/GetAllProjects").Result;
           string result = string.Empty;

           if (response.IsSuccessStatusCode)
           {

               result = response.Content.ReadAsStringAsync().Result;
           }
           return result;
       }

但是,它始终只会将我转发到登录页面。这是托管API应用的启动:

using Microsoft.AspNetCore.Authentication;
using Microsoft.AspNetCore.Authentication.AzureAD.UI;
using Microsoft.AspNetCore.Authentication.Cookies;
using Microsoft.AspNetCore.Authentication.OAuth.Claims;
using Microsoft.AspNetCore.Authentication.OpenIdConnect;
using Microsoft.AspNetCore.Authorization;
using Microsoft.AspNetCore.Builder;
using Microsoft.AspNetCore.Hosting;
using Microsoft.AspNetCore.Http;
using Microsoft.AspNetCore.Mvc;
using Microsoft.AspNetCore.Mvc.Authorization;
using Microsoft.Extensions.Configuration;
using Microsoft.Extensions.DependencyInjection;
using System.Security.Claims;

namespace CIM
{
    public class Startup
    {
        public Startup(IConfiguration configuration)
        {
            Configuration = configuration;
        }

        public IConfiguration Configuration { get; }

        // This method gets called by the runtime. Use this method to add services to the container.
        public void ConfigureServices(IServiceCollection services)
        {
            services.Configure<CookiePolicyOptions>(options =>
            {
                // This lambda determines whether user consent for non-essential cookies is needed for a given request.
                options.CheckConsentNeeded = context => true;
                options.MinimumSameSitePolicy = SameSiteMode.None;
            });

            services.AddAuthentication(AzureADDefaults.AuthenticationScheme)
                .AddAzureAD(options => Configuration.Bind("AzureAd", options));


            services.Configure<OpenIdConnectOptions>(AzureADDefaults.OpenIdScheme, options =>
            {
                options.Authority = options.Authority + "/v2.0/";

                               options.TokenValidationParameters.ValidateIssuer = false;
            });



            services.AddMvc(options =>
            {
                var policy = new AuthorizationPolicyBuilder()
                    .RequireAuthenticatedUser()
                    .Build();
                options.Filters.Add(new AuthorizeFilter(policy));
            })
            .SetCompatibilityVersion(CompatibilityVersion.Version_2_1);
        }

        // This method gets called by the runtime. Use this method to configure the HTTP request pipeline.
        public void Configure(IApplicationBuilder app, IHostingEnvironment env)
        {
            if (env.IsDevelopment())
            {
                app.UseDeveloperExceptionPage();
            }
            else
            {
                app.UseExceptionHandler("/Home/Error");
                app.UseHsts();
            }

            app.UseHttpsRedirection();
            app.UseStaticFiles();
            app.UseCookiePolicy();

            app.UseAuthentication();

            app.UseMvc(routes =>
            {
                routes.MapRoute(
                    name: "default",
                    template: "{controller=Home}/{action=Index}/{id?}");
            });
        }
    }
}

要使用访问令牌登录.NET API,我缺少什么?

2 个答案:

答案 0 :(得分:0)

正如junnas所说,您需要配置API以使用承载令牌认证。

您可以将所需的中间件配置添加到$output

echo $output;

有关代码示例,您可以参考:ASP.NET Core WebAPI secured using OAuth2 Client Credentials

答案 1 :(得分:0)

您可以使用AddJwtBearer来验证Web api中的访问令牌:

 services
.AddAuthentication(o =>
{
    o.DefaultScheme = JwtBearerDefaults.AuthenticationScheme;
})
.AddJwtBearer(o =>
{
    o.Authority = Configuration["Authentication:Authority"];
    o.TokenValidationParameters = new Microsoft.IdentityModel.Tokens.TokenValidationParameters
    {
        // Both App ID URI and client id are valid audiences in the access token
        ValidAudiences = new List<string>
        {
            Configuration["Authentication:AppIdUri"],
            Configuration["Authentication:ClientId"]
        }
    };
});

别忘了添加:

app.UseAuthentication();

另一种方法是使用Azure AD Web API模板:新的ASP.NET Core应用程序->选择API模板->更改身份验证->工作或学校帐户->选择您的租户,该模板将为您提供帮助配置您的应用程序。