0

I have an ASP.NET Core MVC application. I don't have any separate DB for this. It is completely depend on Rest API. For login, making an API call and get response. In that json response role is also included. I want to show/hide menu based on this role. Do not show all menu to all users. Show only to specific role only (like admin, consultant etc). What is the best way to do this? How to do this?

Thanks in advance.

2 Answers 2

0

To use Role based menu you can make API call and get the user role. and then store the information in session or cookie:

public async Task<IActionResult> Login(LoginViewModel model)
{
    if (ModelState.IsValid)
    {
        var response = await _apiClient.AuthenticateUserAsync(model.Username, model.Password);
        if (response.IsSuccess)
        {
            HttpContext.Session.SetString("UserRole", response.UserRole);
            return RedirectToAction("Index", "Home");
        }
    }
    return View(model);
}

Method to Check User Role:

public bool IsUserInRole(string requiredRole)
{
    var userRole = HttpContext.Session.GetString("UserRole");
    return userRole != null && userRole.Equals(requiredRole, StringComparison.OrdinalIgnoreCase);
}

View:

@{
    bool isAdmin = IsUserInRole("Admin");
}

<div>
    <ul>
        <li><a href="/home/index">Home</a></li>
        @if (isAdmin)
        {
            <li><a href="/admin/dashboard">Admin Dashboard</a></li>
        }
        <li><a href="/account/profile">Profile</a></li>
    </ul>
</div>

Add the [Authorize(Roles = "Admin")] to securing Actions in Controllers.

Sign up to request clarification or add additional context in comments.

Comments

0

Add Claims to User Identity:

var claims = new List<Claim>
{
    new Claim(ClaimTypes.Role, "Admin") // Replace "Admin" with the actual role retrieved from API response
};

var claimsIdentity = new ClaimsIdentity(claims, CookieAuthenticationDefaults.AuthenticationScheme);
var authProperties = new AuthenticationProperties();

await HttpContext.SignInAsync(
    CookieAuthenticationDefaults.AuthenticationScheme,
    new ClaimsPrincipal(claimsIdentity),
    authProperties);

and put below condition like

@if (User.IsInRole("Admin"))
{
    <li><a href="#">Admin Menu Item</a></li>
}

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.