locked
.NET Core v3 doesnt have UseIdentity() when building ApplicationBuidler in StartUp.cs RRS feed

  • Question

  • User1428199325 posted

    I upgraded & ran into this issue where `UseIdentity()` is not available in StartUp.cs when building application (ApplicationBuilder).

    The webservice use it so what is the recommended fix?  The MVC Controller have attribute that checked for valid Identity.  The `OnAuthorizationAsync` in Filter Attribute class do check for active Identity.  This is where custom basic authentication pass in the login.

    // Startup.cs

    public void Configure(IApplicationBuilder applicationBuilder, ILoggerFactory loggerFactory, IServiceProvider serviceProvider)

    {

                // Webservice API access.

                applicationBuilder.UseWhen(context =>

                    !context.Request.Path.StartsWithSegments(new PathString("/api/v1")), 

                    b => b.UseIdentity()

                );

                applicationBuilder.UseWhen(context => 

                    !context.Request.Path.StartsWithSegments(new PathString("/api/v1")), 

                    b => b.UseAuthentication()

                );

            }

    // MerchantsV1Controller.cs

    [TypeFilter(typeof(AuthorizeWithNoChallengeFilterAttribute))]

    public class MerchantsV1Controller : Controller

    {

    }

    // AuthorizeWithNoChallengeFilterAttribute.cs

    public class AuthorizeWithNoChallengeFilterAttribute : IAsyncAuthorizationFilter

    {

         public async Task OnAuthorizationAsync(AuthorizationFilterContext context)

         {

                if (!context.HttpContext.User.Identity.IsAuthenticated)

                    context.Result = new UnauthorizedResult();

                    await Task.CompletedTask;

            }

        }

    Wednesday, June 17, 2020 7:12 PM

All replies

  • User-474980206 posted

    you should go thru the migration steps:

    https://docs.microsoft.com/en-us/aspnet/core/migration/1x-to-2x/identity-2x?view=aspnetcore-3.1

    you will need to go thru all steps from your current version to 3.1

    note: it looks like you are upgrading from 1.*.  there are a lot of differences. its probably easier to create a new 3.1 project, and add your code to it. anyway use the new project as a template.

    Wednesday, June 17, 2020 7:50 PM
  • User1428199325 posted

    The thing is with the upgrade by changing `UseIdentity()` to `UseAuthentication()` then I have 2  of them that does the same thing, so I remove the 1st one instead.

    // Webservice API access.
    applicationBuilder.UseWhen(context =>
       !context.Request.Path.StartsWithSegments(new PathString("/api/v1")),
       b => b.UseIdentity()
    );

    Then the `OnAuthorizationAsync()` in `AuthorizeWithNoChallengeFilterAttribute` said that Identity is not Authenticated.

    if (!context.HttpContext.User.Identity.IsAuthenticated)
    context.Result = new UnauthorizedResult();

    So as result, the webservice login doesnt work & it continue to be unauthorized.

    The webservice does not use cookie because the client app is a non-web-browser client.   For some reasons, the custom basic authentication never ran.

    We use `AddBasic()` part.

    services.AddAuthentication()

    .AddBasic(AuthenticationWebservice.SchemeCustomMerchantBasic, options =>

    {

                      //## options.AutomaticChallenge = false;

                     options.Realm = "AutoPayment API v1";

                    options.Events = new BasicEvents()

                        {

                            OnSignIn = async context =>

                            {

                              var claims = new List<Claim>();

                               if (context.Username == "foo1" && context.Password == "foo2")

                               claims.Add(new Claim(ClaimTypes.Role, "InternalAPIUser"));

                                else

                                {

                                  string merchantAccountId = context.Request.Path.Value.Split('/').Skip(4).FirstOrDefault();

                                  var merchantRepository = context.HttpContext.RequestServices.GetRequiredService<IMerchantRepository>();

                                   if (merchantAccountId == null || merchantAccountId.Length != 14 || merchantAccountId.Split('-').Length != 3)

                                       throw new Exception($"Invalid merchant account Id ({merchantAccountId ?? string.Empty}).");

                                    var merchant = await merchantRepository.GetMerchantAsync(merchantAccountId, context.HttpContext.RequestAborted);

                                   if (merchant == null || !merchant.IsActive || (merchant.GatePayApiKey != context.Username || merchant.GatePayApiSecret != context.Password))

                                    {

                                        context.Fail("Invalid merchant"); //## context.HandleResponse();

                                        return;

                                    }

                               }

                              var principal = new ClaimsPrincipal(new ClaimsIdentity(claims, context.Scheme.Name));  //## options.AuthenticationScheme));

                             context.Principal = principal;

                            //## context.Ticket = new AuthenticationTicket(principal, new AuthenticationProperties(), options.AuthenticationScheme);

                           context.Success(); //## context.HandleResponse();

                          //## return Task.CompletedTask;

                               return;

                            }

                       };

                   });

    Wednesday, June 17, 2020 8:43 PM
  • User-474980206 posted

    but authorization has been re-written and does not work the same. nor does routing work the same way (you should be using endpoint routing), you should read thru the docs.

    you can just write middleware (with endpoint the middle ware can check the route). if the middleware handles basic, then you can just use authorization attributes

       https://stackoverflow.com/questions/38977088/asp-net-core-web-api-authentication

    or use a filter:

      https://jasonwatmore.com/post/2019/10/21/aspnet-core-3-basic-authentication-tutorial-with-example-api

    Wednesday, June 17, 2020 9:04 PM