Check if the user has authenticated, and get authenticated user information

Asked

Viewed 272 times

1

I want to check if you had any user authentication, and after checking if any user authenticated to get that user’s ID.

I have a Middleware that will redirect the user to condominium registration screen, always requiring him to register a condo if he no longer has any registered.

The problem is that Middleware is used even before a user authenticates, I need it to work only after there is authentication.

I need to change this to run only after an authentication happens.

Middleware:

public class RedirectNoCondominium
{
    private readonly RequestDelegate _next;
    private readonly IHttpContextAccessor _httpContextAccessor;
    private readonly string path = "~/Condominium/Add";

    public RedirectNoCondominium(
        RequestDelegate next,
        IHttpContextAccessor httpContextAccessor)
    {
        _next = next;
        _httpContextAccessor = httpContextAccessor;
    }

    public async Task Invoke(HttpContext httpContext, ICondominiumService _condominiumManager)
    {

        if (user != null)
        {

            List<ApplicationCondominium> result = await _condominiumManager.GetCondominiumAsync(user);

            if (result.Count() == 0 && httpContext.Request.Path != path)
            {
                httpContext.Response.Redirect(path);
            }
            else
                await _next(httpContext);
        }
        else
        {
            await _next(httpContext);
        }

    }
}

and call her in my startup:

public void Configure(IApplicationBuilder app, IHostingEnvironment env)
    {

        app.UseMiddleware<RedirectNoCondominium>();

        app.UseForwardedHeaders();

        app.Use(async (context, next) =>
        {
            if (context.Request.IsHttps || context.Request.Headers["X-Forwarded-Proto"] == Uri.UriSchemeHttps)
            {
                await next();
            }
            else
            {
                string queryString = context.Request.QueryString.HasValue ? context.Request.QueryString.Value : string.Empty;
                var https = "https://" + context.Request.Host + context.Request.Path + queryString;
                context.Response.Redirect(https);
            }
        });


        if (env.IsDevelopment())
        {

            app.UseDeveloperExceptionPage();
            app.UseDatabaseErrorPage();
        }
        else
        {
            app.UseExceptionHandler("/Home/Error");
            app.UseHsts();
        }


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

        app.UseAuthentication();

        app.UseNToastNotify();

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

1 answer

0

To verify authentication with Asp.NET MVC, the [Authorize], it checks if the user is authenticated. You always put it in controller:

Authentication

To restrict just a page or an action

    [Authorize]
    public ActionResult MyPage()
    {

    }

To restrict every controller

[Authorize]
public class UserController : Controller
{
   public ActionResult MyPage()
    {

    }
}

In the restricted controller you may need to give free access to some action or page

[Authorize]
public class UserController : Controller
{

    public ActionResult MyPage()
    {
        // acesso apenas aos utilizadores auntentiado 
    }

    [AllowAnonymous]
    public ActionResult MyPage()
    {
        //Acesso livre
    }
}

Identifying Here you are taking the data from the user you stored when logging in, which in this case could be the Id

[Authorize]
public ActionResult MyPage()
{
    var user=User.Identity.Name;
}
  • This solution doesn’t fit my case. Since I don’t use controllers, I call Middleware every time the application goes through startup.

Browser other questions tagged

You are not signed in. Login or sign up in order to post.