How to integrate ASP.NET Core Identity with Vue.js Frontend for Authentication Using Razor Pages?

Aakash Bashyal 0 Reputation points
2024-11-10T15:38:20.41+00:00

I am developing a web application using ASP.NET Core 8 for the backend and Vue.js for the frontend.

I set up my project by following the ASP.NET Core app with Vue.js in Visual Studio guide and configured my frontend and backend as separate applications, with the frontend using a proxy setup in vite.config.ts to communicate with the backend.

Current Implementation

I have implemented authentication by following the guide on using Identity to secure a Web API backend for SPAs, which led me to create custom UI for login.

The Vue.js frontend has separate login pages that interact with the new identity API endpoint.

I have been checking the whether user is logged and checking the protect routes in the frontend as:


router.beforeEach(async (to, from, next) => {
  const authStore = useAuthStore();

  if (to.matched.some(record => record.meta.requiresAuth)) {
    const isSignedIn = await authStore.isSignedIn();

    if (!isSignedIn) {
      // Redirect to sign-in page if not authenticated
      next({ path: '/signin' });
    } else {
      // Proceed if authenticated
      next();
    }
  } else {
    // Route does not require authentication
    next();
  }
});

To check whether user is already signed in:


async isSignedIn() {
      const userInfo = await fetchUserInfo();

      const isValid = !!(userInfo && userInfo.email && userInfo.email.length > 0);

      this.$patch({
        name: userInfo?.email,
        isAuthenticated: isValid
      })

      return isValid;
    },

async function fetchUserInfo() {
  try {
    const response = await fetch('manage/info', {
      method: 'GET'
    });

    if (!response.ok) {
      throw new Error('Not authenticated');
    }

    const data = await response.json();
    return data;
  } catch (error) {
    console.error('Fetch user info error:', error);
    return null; // Return null if an error occurs
  }
}

What I want to achieve

Instead of using the identity API endpoints, I would like to use the razor pages for user registration and login that can be scaffolded in Visual Studio, which would separate out the logic of authentication from the frontend, and I am little bit doubting on myself that i may not do the authentication flow correct on the frontend.

Also, the new identity endpoints are not easily extended, which doesn't allow the most of the desired field to be added on the different identity endpoints.

My goal is to keep the frontend's UI intact while handling the authentication logic through ASP.NET Core backend pages.

However I do not want to use external authentication providers (e.g., OAuth or IdentityServer).

I want to use only ASP.NET Core Identity for user management and authentication.

Questions

Is it possible to integrate the Razor-based authentication flow while keeping the Vue.js frontend as the main UI framework?

How can I manage redirects and sessions between the Vue.js frontend and the ASP.NET Core backend in this setup?

Developer technologies ASP.NET ASP.NET Core
0 comments No comments
{count} votes

2 answers

Sort by: Most helpful
  1. Bruce (SqlWork.com) 77,686 Reputation points Volunteer Moderator
    2024-11-10T17:17:36.4933333+00:00

    If you use individual identity for a SPA, with asp.net core backend you need to decided if you will use cookie or token authentication. The razor pages only support cookie authentication, but you could add a token login.

    to use the razor pages, the SPA needs to redirect to the razor pages. You might want to scaffold them so you know the urls.

    with cookie authentication and SPA you need to include the cookie in the api calls. You also need middleware to detect missing / invalid cookie so the api call can return a detectable 401 error, rather than the login page html. This is because the default behavior is to redirect to the login page.


  2. Anonymous
    2024-11-12T03:03:02.7333333+00:00

    Hi @Aakash Bashyal

    I want to set up separate front-end and back-end applications for my UI, but for authentication (login, registration, password reset, etc.), I want to use the Identity UI. I've already scaffolded the Identity UI and integrated it into my project. My question is how to use it with a Vue.js front-end setup. Since Razor Pages and the front-end can't be served from the same domain, if I redirect from Vue.js, I will need to redirect to a different domain. Essentially, I want to keep the front-end on its own domain but serve the Identity UI, and I would like to use cookie-based authentication instead of access tokens. How can I achieve this?

    You can configure the cookie to use the same path and domain to share the authentication cookies among front-end and back-end application.

    In the server project, since you have already added ASP.NET Core Identity UI, I suppose you can already use the Identity UI to register user or login. By default, asp.net core identity is using cookie to store the identity information. So, you can refer to the following code to configure the cookie and set the same path and domain:

    builder.Services.ConfigureApplicationCookie(options =>
    {
        // Cookie settings
        options.Cookie.Name = ".AspNet.SharedCookie";
        options.Cookie.Path ="/";
        options.Cookie.Domain = "localhost";
        options.Cookie.HttpOnly = true;
        options.ExpireTimeSpan = TimeSpan.FromMinutes(5);
        options.LoginPath = "/Identity/Account/Login";
        options.AccessDeniedPath = "/Identity/Account/AccessDenied";
        options.SlidingExpiration = true;
    });
    

    Then, running the application, you can see they are using the same authentication cookies:

    Front-end:

    User's image

    and back-end:

    User's image

    Reference: Share authentication cookies among ASP.NET apps


    If the answer is the right solution, please click "Accept Answer" and kindly upvote it. If you have extra questions about this answer, please click "Comment".

    Note: Please follow the steps in our documentation to enable e-mail notifications if you want to receive the related email notification for this thread.

    Best regards,

    Dillion


Your answer

Answers can be marked as Accepted Answers by the question author, which helps users to know the answer solved the author's problem.