Problem sending HTTP post request from VUE to ASP.NET Core MVC project

33 views Asked by At

In the vue project, I have a LoginView.vue subpage in the views folder, in which I would like to link to an ASP.NET Core MVC project in which I use the ASP.NET Core Identity for the login/user registration form.

When sending a request from vue to ASP.NET Core MVC, I get an error http 400, I am 100% sure that my login details are correct.

I previously added exceptions such as CORS support to get rid of locks on the ASP.NET Core MVC side.

LoginView.vue:

<template>
    <div>
        <h2>Hello</h2>
        <hr />
        <div class="form-floating mb-3">
            <input v-model="email" type="email" class="form-control" autocomplete="username" aria-required="true" />
            <label for="email" class="form-label">Email</label>
        </div>
        <div class="form-floating">
            <input v-model="password" type="password" class="form-control" autocomplete="current-password"
                aria-required="true" />
            <label for="password" class="form-label">Password</label>
        </div>
        <div class="form-check">
            <input v-model="rememberMe" type="checkbox" class="form-check-input" id="rememberMe" />
            <label class="form-check-label" for="rememberMe">Remember Me</label>
        </div>
        <button @click="login" type="button" class="w-100 btn btn-lg btn-primary">Log in</button>
    </div>
</template>

<script>
import axios from 'axios';

const API_URL = "http://localhost:5211/";

export default {
    data() {
        return {
            email: '',
            password: '',
            rememberMe: false
        };
    },
    methods: {
        login() {
            const loginData = {
                email: this.email,
                password: this.password,
                rememberMe: this.rememberMe
            };

            axios.post(API_URL + 'identity/Account/Login', loginData)
                .then(response => {
                    console.log('Login response:', response.data);

                    console.log("Email:", this.email);
                    console.log("Password:", this.password);
                })
                .catch(error => {
                    console.error('Error during login:', error);
                });
        }
    }
}
</script>

<style scoped></style>

ASP.NET Core MVC project - Program.cs:

// Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
#nullable disable

using System;
using System.Collections.Generic;
using System.ComponentModel.DataAnnotations;
using System.Linq;
using System.Threading.Tasks;
using Microsoft.AspNetCore.Authorization;
using AuthProject.Areas.Identity.Data;
using Microsoft.AspNetCore.Authentication;
using Microsoft.AspNetCore.Identity;
using Microsoft.AspNetCore.Identity.UI.Services;
using Microsoft.AspNetCore.Mvc;
using Microsoft.AspNetCore.Mvc.RazorPages;
using Microsoft.Extensions.Logging;

namespace AuthProject.Areas.Identity.Pages.Account
{
    public class LoginModel : PageModel
    {
        private readonly SignInManager<ApplicationUser> _signInManager;
        private readonly ILogger<LoginModel> _logger;

        public LoginModel(SignInManager<ApplicationUser> signInManager, ILogger<LoginModel> logger)
        {
            _signInManager = signInManager;
            _logger = logger;
        }

        [BindProperty]
        public InputModel Input { get; set; }

        public IList<AuthenticationScheme> ExternalLogins { get; set; }

        public string ReturnUrl { get; set; }

        [TempData]
        public string ErrorMessage { get; set; }

        public class InputModel
        {
            [Required]
            [EmailAddress]
            public string Email { get; set; }

            [Required]
            [DataType(DataType.Password)]
            public string Password { get; set; }

            [Display(Name = "Remember me?")]
            public bool RememberMe { get; set; }
        }

        public async Task OnGetAsync(string returnUrl = null)
        {
            if (User.Identity.IsAuthenticated)
            {
                Response.Redirect("/");
            }

            if (!string.IsNullOrEmpty(ErrorMessage))
            {
                ModelState.AddModelError(string.Empty, ErrorMessage);
            }

            returnUrl ??= Url.Content("~/");

            await HttpContext.SignOutAsync(IdentityConstants.ExternalScheme);

            ExternalLogins = (await _signInManager.GetExternalAuthenticationSchemesAsync()).ToList();

            ReturnUrl = returnUrl;
        }

        public async Task<IActionResult> OnPostAsync(string returnUrl = null)
        {
            returnUrl ??= Url.Content("~/");

            ExternalLogins = (await _signInManager.GetExternalAuthenticationSchemesAsync()).ToList();

            if (ModelState.IsValid)
            {
                var result = await _signInManager.PasswordSignInAsync(Input.Email, Input.Password, Input.RememberMe, lockoutOnFailure: false);

                if (result.Succeeded)
                {
                    _logger.LogInformation("User logged in.");
                    return LocalRedirect(returnUrl);
                }

                if (result.RequiresTwoFactor)
                {
                    return RedirectToPage("./LoginWith2fa", new { ReturnUrl = returnUrl, RememberMe = Input.RememberMe });
                }

                if (result.IsLockedOut)
                {
                    _logger.LogWarning("User account locked out.");
                    return RedirectToPage("./Lockout");
                }
                else
                {
                    ModelState.AddModelError(string.Empty, "Invalid login attempt.");
                    return Page();
                }
            }

            return Page();
        }
    }
}

When I enter login data (works in ASP.NET Core MVC) in the vue form after submitting the order using the Log in button, I get a response in the browser console

POST http://localhost:5211/identity/Account/Login 

400 (Bad Request)

@LoginView.vue:44
_createElementVNode.onClick._cache.._cache.
@LoginView.vue:18

@LoginView.vue:43 code:

axios.post(API_URL + 'identity/Account/Login', loginData)

@LoginView.vue:18 code:

<button @click="login" type="button" class="w-100 btn btn-lg btn-primary">Log in</button>

Second error:

enter image description here

0

There are 0 answers