accol
Coder
Thank you to anyone who reads and replies to this. I do not know what I'm doing wrong by this point.
I've been trying to connect the React.js frontend to my ASP.NET Core backend. I've tried both Fetch and Axios and I've been getting the same error each time, however it doesn't make sense to me because in Swagger, when I pass in the same username and password, it's successful.
Below is what Response shows under the network tab.
This is the result when I tried using Swagger and it also logs in the console so I'm not sure why the backend wouldn't be validating the model.
Below is the controller code.
The model that it uses.
I've also made sure that inside of
Another thing to note is that when I tried to debug and put breakpoints at various parts of the
I've been trying to connect the React.js frontend to my ASP.NET Core backend. I've tried both Fetch and Axios and I've been getting the same error each time, however it doesn't make sense to me because in Swagger, when I pass in the same username and password, it's successful.
Below is what Response shows under the network tab.
I checked and it seems like the username and password are being passed according to the Payload.JSON:{ "type": "RFC 9110: HTTP Semantics", "title": "One or more validation errors occurred.", "status": 400, "errors": { "password": [ "The password field is required." ], "username": [ "The username field is required." ] }, "traceId": "00-3e924f01d520f60adedb593b857e0cd1-accd29f9df16d4bd-00" }
Code:{username: "OMORI", password: "U_k!ll3d_h3r"}
password: "U_k!ll3d_h3r"
username: "OMORI"
JavaScript:
const onLoginButtonClick = async () => {
if (!onCheckValidInput()) {
return;
}
const response = await axios.post('/api/Authentication/Login', {
username: username,
password: password
}).catch(err => alert(err));
}
This is the result when I tried using Swagger and it also logs in the console so I'm not sure why the backend wouldn't be validating the model.
Below is the controller code.
C#:
namespace OMORI.Server.Controllers
{
[Route("api/[controller]")]
[ApiController]
public class AuthenticationController : ControllerBase
{
private readonly AppDBContext _context;
private readonly ILogger<AuthenticationController> _logger;
public AuthenticationController(AppDBContext context, ILogger<AuthenticationController> logger)
{
_context = context;
_logger = logger;
}
// POST: api/Authentication/Login
[HttpPost("Login")]
public async Task<ActionResult<User>> Login(string username, string password)
{
var user = await _context.User.FirstOrDefaultAsync(u => u.username == username);
if (user == null)
return NotFound();
// I don't think you can convert a byte array like that but I just wanted to log and see if the information's being passed in and out to the console
_logger.LogInformation(
"======================" +
"\nUsername: " + username +
"\nPassword: " + password +
"\n" +
"\nUser ID: " + user.userID.ToString() +
"\nHashed password: " + user.passwordHash +
"\nSalt: " + user.passwordSalt.ToString() +
"\n=====================");
if (AuthenticationService.VerifyPassword(password, user.passwordHash, user.passwordSalt))
return Ok(user);
return NotFound();
}
}
}
The model that it uses.
C#:
public class User
{
[Key, DatabaseGenerated(DatabaseGeneratedOption.Identity)]
public int userID { get; set; }
[Required, Column(TypeName = "nvarchar(max)")]
public string username { get; set; }
[Required, Column(TypeName = "nvarchar(max)")]
public string passwordHash { get; set; }
[Required, Column(TypeName="varbinary(max)")]
public byte[] passwordSalt {get;set;}
}
I've also made sure that inside of
vite.config.js
that I set the proxy to be /api
as well for development.
JavaScript:
// https://vitejs.dev/config/
export default defineConfig({
plugins: [plugin()],
resolve: {
alias: {
'@': fileURLToPath(new URL('./src', import.meta.url))
}
},
server: {
proxy: {
'/api': {
target: 'https://localhost:7095/',
secure: false
}
},
port: 5173,
https: {
key: fs.readFileSync(keyFilePath),
cert: fs.readFileSync(certFilePath),
}
}
})
Another thing to note is that when I tried to debug and put breakpoints at various parts of the
Login
function, when I click on Log In button, it never reaches that function either. I don't know if there's something wrong with the controller itself because according to ASP.NET Core REST API and ModelState.IsValid check,In an ASP.NET Core REST API, there is no need to explicitly check if the model state is Valid. Since the controller class is decorated with the [ApiController] attribute, it takes care of checking if the model state is valid and automatically returns 400 response along the validation errors.