How to properly implement login and token handling from REST endpoint in ASP.NET Core/MAUI Blazor
I'm developing a MAUI Blazor application that communicates with a Django REST Framework backend. I'm trying to implement user authentication, but I'm encountering a "Bad Request" error when trying to log in.
I'm successfully hitting the /api/login/ endpoint, but I'm getting a "Bad Request" error. What could be causing this? How should I format the request to ensure successful authentication?
Here's the relevant part of my Blazor code:
@page "/"
@inject HttpClient HttpClient
@using System.Text
@using mysocial.Models
@using Newtonsoft.Json
<h3>Login</h3>
<div>
<label>Username:</label>
<input type="text" @bind="username" />
</div>
<div>
<label>Password:</label>
<input type="password" @bind="password" />
</div>
<button @onclick="Logins">Login</button>
@if (authToken != null)
{
<p>Login successful! Token: @authToken.Token</p>
}
@code {
private string? username;
private string? password;
private AuthToken? authToken;
private async Task Logins()
{
var loginData = new
{
Username = username,
Password = password
};
var json = JsonConvert.SerializeObject(loginData);
var response = await HttpClient.PostAsync("http://127.0.0.1:8000/api/login/",
new StringContent(json, Encoding.UTF8, "application/json"));
if (response.IsSuccessStatusCode)
{
authToken = await response.Content.ReadFromJsonAsync<AuthToken>();
}
else
{
var errorContent = await response.Content.ReadAsStringAsync();
Console.WriteLine($"Error: {errorContent}");
}
}
}