如何使用 .net 核心从 Ionic 对移动设备进行身份验证,对 Web 进行另一个身份验证?

How to do an authentication for mobile from Ionic and another from web using .net core?

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

根据 我需要为每个客户端或身份验证方式设置模式

//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 请求进行的,其中 returns 带有令牌的 200 状态代码,但是当请求到任何 Web API 控制器在 header 中包含一个令牌或 Bearer 令牌重定向到 adfs 登录站点以进行身份​​验证。我想从 Ionic 应用程序发送用户名和密码并访问所有网络 API 控制器。

如果您需要管理两种身份验证方法,则需要像此处的答案一样配置授权:。另外,如果你使用的是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();

            });

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

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

如果它是一个网络 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