Customizing page views depending on user roles in Asp.net Core

I have a controller that needs to redirect views based on user roles:

    [Authorize(Roles = "Projects,Projects-Manager")]

    public IActionResult Projects()
    {
        return View();
    }
    [Authorize(Roles = "Procurment,Procurment-Manager")]

    public IActionResult Procurment()
    {
        return View();
    }
    [Authorize(Roles = "HR,HR-Manager")]

    public IActionResult HR()
    {
        return View();
    }
    public IActionResult Index()
    {
        return View();
    }


    //GET: Login 

    [HttpGet]
    public IActionResult Login(string returnUrl)
    {
        ViewData["ReturnUrl"] = returnUrl;
        return View();
    }


    [Authorize]
    [HttpPost]
    [ValidateAntiForgeryToken]
    public async Task<IActionResult> Login(UserLoginModel userModel)
    {
        if (!ModelState.IsValid)
        {

            return View(userModel);
        }


        var result = await _signInManager.PasswordSignInAsync(userModel.UserName, userModel.Password, userModel.RememberMe, false);


        if (result.Succeeded && HttpContext.User.IsInRole("HR,HR-Manager"))
        {
            return Redirect(nameof(HR));
        }
        else if (result.Succeeded && HttpContext.User.IsInRole("Projects,Projects-Manager"))
        {
            return Redirect(nameof(Projects));

        }
        else if (result.Succeeded && HttpContext.User.IsInRole("Procurmant,Procurmant-Manager"))
        {
            return RedirectToAction(nameof(Procurment));
        }


        else
        {

            ModelState.AddModelError("", "Invalid UserName or Password");
            return View();
        }


    }

and here is the startup.cs file.

                services.AddIdentity<User, IdentityRole>(opt =>
                {
                    opt.User.RequireUniqueEmail = true;
                    opt.User.AllowedUserNameCharacters = "";
                    opt.Password.RequiredLength = 7;
                    opt.Password.RequireDigit = false;
                    opt.Password.RequireUppercase = false;
                })
                 .AddEntityFrameworkStores<ApplicationContext>();
           
                services.AddScoped<IUserClaimsPrincipalFactory<User>, CustomClaimsFactory>();
                services.AddAutoMapper(typeof(Startup));

                services.AddControllersWithViews();
            } 

I encountered an error when trying to access my localhost page. The error message reads:
"This localhost page can’t be foundNo webpage was found for the web address: https://localhost:7044/Account/Login?ReturnUrl=%2FHome%2FLogin HTTP ERROR 404"

I've made adjustments to the code as suggested by solutions on StackOverflow, but I continue to face the same issue. Is there any additional configuration that needs to be added in the startup file?

UPDATE: After correcting a mistake in the name of the Login view, I'm still facing issues with redirection and now encountering HTTP ERROR 405.

Answer №1

Seems like only authenticated or authorized users have permission to utilize the Login post method in the controller. Consider using [AllowAnonymous] instead of [Authorize] on that specific method. The 405 error code signifies a "Not Allowed" error

    [AllowAnonymous]
    [HttpPost]
    [ValidateAntiForgeryToken]
    public async Task<IActionResult> Login(UserLoginModel userModel)
    

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

Experiencing a lack of information when trying to retrieve data through an http request in an express/react

Issue: My problem lies in attempting to retrieve data from http://localhost:3000/auth/sendUserData using the http protocol. Unfortunately, I am not receiving any data or response, as indicated by the absence of console logs. Tools at my disposal: The te ...

What is the best way to construct a template string to display the contents of an object?

Here is an array of objects: var students = [ { name : "Mike", track: "track-a", points : 40, }, { name : "james", track: "track-a", points : 61, }, ] students.forEach(myFunction); function myFunction (item, index) ...

Spreading out the 'flip card' divs across various sections of the website while maintaining a seamless animation experience

I found a helpful answer on Stack Overflow that I'm currently following, and it's working perfectly for me. However, I am facing an issue where I need to position the boxes in different parts of the document, causing the animation to break. You ...

Tips for utilizing Javascript Arquero in a web browser

Hello, I am just starting out in the world of JavaScript so please be patient with me. I recently discovered the Arquero JavaScript library and I would like to incorporate it into a standalone HTML file. After reading through the documentation available ...

React Native failing to display images sourced from a URI

I have thoroughly reviewed all responses to similar inquiries, but none of them seem to tackle my specific problem. Despite following all the recommended steps for success, as evident in my code snippet below and the accompanying screenshot, I continue to ...

Struggling to conceal a div element in AngularJS using the ng-if directive

Having trouble concealing a div when the page loads. I am trying to display the div only if the array is empty. <div ng-hide="loading" ng-if="users== null || users.length === 0" > <h3>No Result Found</h3> </div> ...

Exploration of Non-height Divs

Repeatedly encountering the same issue - a fluid div with floated elements lacking a background due to having "no height." I've experimented with various solutions such as :after selectors, , and artificially setting a height, but none are particularl ...

Getting the height of a group of classes using the style attribute

How can I retrieve the current height of 813px in jQuery from the "style" section? An example of F12 CSS is shown here: https://i.sstatic.net/4wFfR.jpg My attempt at achieving this is as follows: function HandleAccordionControlSizeChanges(isOpened) { ...

Experiencing difficulty in personalizing VueDatePicker

<template> <VueDatePicker v-model="date" ref="datepicker" /> </template> <script setup> import { ref } from 'vue'; const date = ref(); const datepicker = ref(null); const yourCustomMethod = () =&g ...

The table does not recognize any of the CSS classes when the TAG is inputted inside

I am currently working on a challenging form for players to save their personal character sheets in a database. To achieve this, I am incorporating numerous Input TAGs and utilizing tables for layout purposes, ensuring an organized and efficient design. E ...

Filtering with XML parsing

My XML file has the following structure - <?xml version="1.0" encoding="UTF-8"?> <prj:Flow xmlns:prj="url1" xmlns:com="url2" xmlns:ns2="url3" xmlns:con="url4" xmlns:ns0="url5" xmlns:ns1="url6" xmlns:ns3="url7"> <prj:str> &l ...

Guide to streaming audio files using vue.js

I am attempting to incorporate an audio file into my vue.js project using the following code: import sound from '../../recordings/sound.mp4' const audio = new Audio(sound) audio.play() Although this method works perfectly fine, I have encounter ...

Is it a scope issue if ng-click is not firing and the function is not working properly?

I'm facing an issue with an animation that is not working as intended. The goal is to have the search button trigger an animation to pull a search bar from the right side, allowing users to input their search query. However, the ng-click function does ...

Utilizing background styles for enhancing the appearance of Ionic side menus

I've been experimenting with ionic and angular.js, trying to figure out the best way to apply background styles to side menus. I currently have a blurred background image with content boxes placed on top of it. My goal is to keep the background fixed ...

Using async/await in combination with the map function may lead to unexpected outcomes

Imagine I have the following code snippet: const array = [1, 2, 3] let counter = 0 array.map(async (item) => { console.log(await item, ++counter) console.log(await item, ++counter) }) The expected output should be 1, 1 1, 2 2, 3 2, 4 3, 5 3, 6 H ...

Ways to efficiently populate several dropdown menus with jQuery by making a single request to a local JSON file

I am running into an issue with the Country/City dropdowns in my project. Every time I try to change the countries, I encounter an unexpected behavior. How can I efficiently fetch the local JSON file to populate multiple dropdowns with just one request? Ta ...

"Enhance your website's loading speed with the Google Page Speed Up

Hi, I've been using the Google PageSpeed Module and have created a .htaccess file to optimize my website (www.anetoi.com). I tried using combine_css to merge my CSS files but it didn't work as expected. I followed Google's instructions but s ...

Which file should I include: npm-shrinkwrap.json, package-lock.json, or yarn.lock?

When shipping a package that is compiled only using tsc (the typescript compiler), I anticipate that consumers will install the necessary dependencies when they use npm or yarn to install my package. I aim to offer flexibility by not enforcing the use of ...

The element refuses to accept the appendChild method

I've created a tampermonkey script that generates certain elements and adds them to the page. The first element, named ControllerBG, is appended to an element with the id "motd". However, when I try to append a second element, nothing appears on the ...

Using Jquery to transfer text from a form to a DIV and ensuring the final character is verified

Users can input their name on my HTML form, which will then be displayed in a DIV as part of a book title. The book title includes apostrophes (e.g. Amy's Holiday Album). However, if the user's name ends with an S, I do not want the apostrophe ...