Как правильно реализовать обработку логинов и токенов из конечной точки REST в ASP.NET Core/MAUI Blazor

Я разрабатываю приложение MAUI Blazor, которое взаимодействует с бэкендом Django REST Framework. Я пытаюсь реализовать аутентификацию пользователей, но при попытке войти в систему я сталкиваюсь с ошибкой «Bad Request».

Я успешно обращаюсь к конечной точке /api/login/, но получаю ошибку «Bad Request». Что может быть причиной этого? Как я должен оформить запрос, чтобы обеспечить успешную аутентификацию?

Вот соответствующая часть моего кода Blazor:

@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}");
        }
    }
}
The "Bad Request" error when trying to log in with your Django REST Framework backend could stem from a few potential issues in the request format or in the way Django is set up to handle authentication. Here are some steps to troubleshoot and fix the issue:

1. Check the Request Payload Format
Ensure that the keys in your loginData object match what the Django backend is expecting. Commonly, the Django REST Framework expects keys to be lowercase. Modify your loginData to use lowercase keys:

var loginData = new
{
    username = username,  // Change from Username to username
    password = password   // Change from Password to password
};

2. Verify Django Endpoint
Make sure your Django endpoint at /api/login/ is set up to accept POST requests with the expected payload. The view handling this endpoint should use a serializer that matches the expected fields.

3. Inspect Django Settings
Check the following in your Django settings:

Ensure that django.contrib.auth is included in your INSTALLED_APPS.

Verify that you have the proper authentication classes set in your Django settings:

REST_FRAMEWORK = {
    'DEFAULT_AUTHENTICATION_CLASSES': (
        'rest_framework.authentication.SessionAuthentication',
        'rest_framework.authentication.BasicAuthentication',
        # or any other relevant authentication classes
    ),
}

4. Inspect Response Content
When you log the error content on a "Bad Request", it may contain useful information about what went wrong. Look for validation errors or any other messages in the response body.

5. Use Fiddler/Postman for Testing
Consider using tools like Postman or Fiddler to manually test the /api/login/ endpoint. This can help you verify that the server responds correctly when the right data is sent, isolating whether the issue lies in your Blazor code or Django.

Updated Blazor Code Example
Here’s how your updated Blazor code might look:

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}");  // Inspect this for `enter code here`clues
    }
}


Conclusion
After making these adjustments, try logging in again. If you still encounter issues, check the Django logs for more detailed error messages, which can provide insight into why the "Bad Request" is being triggered.

Mark as answered if this helps

Вы можете попробовать это

var loginData = new
{
    username = "username",
    password = "password"
};

var response = await httpClient.PostAsJsonAsync("http://127.0.0.1:8000/api/login/", loginData);

И убедитесь, что бэкэнд разрешает использовать домен blazor orgins.

Вернуться на верх