首页 > 解决方案 > 如何使用 .net 核心从 Ionic 和 Web 对移动设备进行身份验证?

问题描述

我在我的 asp net core 应用程序中设置 ADFS 身份验证,它有一个 Web 客户端和一个移动客户端,这意味着它具有 Web 功能和其他使用 Ionic 的移动功能到目前为止我已经为 Web 客户端配置了身份验证,我需要建议或任何有关移动身份验证配置的帮助。

根据Migrating web api authentication from .NET Core 1.1 to 2.0 我需要为每个客户端或身份验证方式设置一个架构

//This is for the controller from the web
    [Microsoft.AspNetCore.Authorization.Authorize]
    public class MyWebControllerController : Controller 
{
//Some code
}

//This is using web api controller
[Route("api/[controller]")]
    [Produces("application/json")]
    [ApiController]
    [Authorize]

    public class MyApiController : ControllerBase     {
//some code
}

因此,如果我知道我需要做的是在我的 Startup.cs 中配置两个身份验证,例如:

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;
           });

          //Some code 
           services.AddCors();
           var policy = new Microsoft.AspNetCore.Cors.Infrastructure.CorsPolicy();

           policy.Headers.Add("*");
           policy.Methods.Add("*");
           policy.Origins.Add("*");
           policy.SupportsCredentials = true;
           services.AddCors(x => x.AddPolicy("corsGlobalPolicy", policy));
           _ = services.AddAuthentication(options =>
           {
               options.DefaultAuthenticateScheme = CookieAuthenticationDefaults.AuthenticationScheme;
               options.DefaultSignInScheme = CookieAuthenticationDefaults.AuthenticationScheme;
               options.DefaultChallengeScheme = OAuthDefaults.DisplayName;
           }).AddOAuth(OAuthDefaults.DisplayName, options =>
             {
                 //Configuration which it works from the web client, it means the browser


             }).AddJwtBearer(options=>
             {
                 // I think that this is the way for mobile
                 options.Configuration = new OpenIdConnectConfiguration
                 {

                 };
             }).AddCookie();


           services.AddMvc(options =>
           {
               // I do not know if this is the correct way or if this it is necessary 
               var politica = new AuthorizationPolicyBuilder()
                 .AddAuthenticationSchemes("Bearer")
                 .RequireAuthenticatedUser()
                 .Build();

               options.Filters.Add(new AuthorizeFilter(politica));
           }).SetCompatibilityVersion(CompatibilityVersion.Version_2_2).



       }

从 Web 或浏览器,身份验证与 Oauth 一起工作,从使用 Ionic 的移动设备,身份验证是通过 Http 请求进行的,该请求返回带有令牌的 200 状态代码,但是当向任何 Web API 控制器发出请求时,在标头或不记名令牌重定向到 adfs 登录站点进行身份验证。我想从 Ionic 应用程序发送用户和密码并访问所有 Web API 控制器。

标签: c#asp.net-coreoauth-2.0ionic3adfs

解决方案


如果您需要管理两种身份验证方法,则需要像这里的答案一样配置授权:将web api authentication from .NET Core 1.1 to 2.0。此外,如果您使用 adfs,则需要进行以下配置:

//ConfigureServices method
 _ = services.AddAuthentication(options =>
            {
                options.DefaultAuthenticateScheme = CookieAuthenticationDefaults.AuthenticationScheme;
                options.DefaultSignInScheme = CookieAuthenticationDefaults.AuthenticationScheme;
                options.DefaultChallengeScheme = OAuthDefaults.DisplayName;

            }).AddOAuth(OAuthDefaults.DisplayName, options =>
              {
                  //Get the configuration from appsettings.json

                  options.AuthorizationEndpoint = Configuration["oauth:auth_uri"];
                  options.TokenEndpoint = Configuration["oauth:token_uri"];
                  options.ClientId = Configuration["oauth:client_id"];
                  options.ClientSecret = Configuration["oauth:client_secret"];
                  var callback = Configuration["oauth:callback_path"].ToString();
                  options.CallbackPath = new PathString(callback);

                options.ClaimsIssuer = "https://YOUR_SERVER/adfs";
                options.Events = new OAuthEvents
                {
                    OnCreatingTicket = OnCreatingTicket,
                };


              }).AddJwtBearer("Bearer",configureOptions=>
              {
                  configureOptions.Authority = "https://YOUR_SERVER/adfs";
                  configureOptions.Audience = "microsoft:identityserver:CLIENT_ID";
                  configureOptions.TokenValidationParameters = new TokenValidationParameters()
                  {
                      ValidIssuer = "http://YOUR_SERVER/adfs/services/trust",
                      ValidateIssuer = true,
                      ValidateAudience = true,
                      ValidAudience = "AUDIENCE",
                      ValidateLifetime = true,
                  };

              }).AddCookie();

 services.AddAuthorization(options =>
            {
                var defaultAuthorizationPolicyBuilder = new AuthorizationPolicyBuilder(
                    JwtBearerDefaults.AuthenticationScheme,
                    "Bearer");
                defaultAuthorizationPolicyBuilder =
                    defaultAuthorizationPolicyBuilder.RequireAuthenticatedUser();
                options.DefaultPolicy = defaultAuthorizationPolicyBuilder.Build();

            });

现在在从 Web 客户端调用的控制器中,授权是这样的:

  [Authorize(AuthenticationSchemes = CookieAuthenticationDefaults.AuthenticationScheme)]
    public class WebController : Controller
    {
      //YOUR CODE
    }

如果它是一个 web api 控制器,则授权是这样的:

 [Route("api/[controller]")]
    [ApiController]
    [Produces("application/json")]
    [Authorize(AuthenticationSchemes =JwtBearerDefaults.AuthenticationScheme)]
    public class WebApiController : ControllerBase
    {
      //Your code here
    }

这篇文章也很有帮助:https ://medium.com/@gabriel.faraday.barros/adfs-angular-asp-net-core-api-5fc61ae89fb3


推荐阅读