Home > Enterprise >  How to fix {detail: Authentication credentials were not provided.} in Django Rest Framework
How to fix {detail: Authentication credentials were not provided.} in Django Rest Framework

Time:11-12

I have struggling with getting information from Django rest framework as a backend and from the frontend using flutter.

The sequence of the project of the project is that I login and receive a {"key":"XXXXXXXXXXXXX"}

Just for testing purposes I am trying to manully add the key to get access. I keep getting {detail: Authentication credentials were not provided.} I am not sure whether the error is because of Django Rest Framework setting or Flutter front end

Here is the Fetch user() in the homescreen:

Future<User> fetchUser() async {
  var url = Uri.parse(Config.apiURL   Config.userProfileAPI);
  print(url);
  final response = await http.post(
    url,
    // headers: {
    //   HttpHeaders.authorizationHeader:
    //       'Bearer XXXXXXXXXXXXX',
    headers: {
      "Authorization": 'JWT XXXXXXXXXXXXX'
      // 'Authorization:  ',
    },);

  final responseJson = jsonDecode(response.body);
  print(responseJson);

  if (response.statusCode == 200) {
    return User.fromJson(jsonDecode(response.body));
  } else {
    throw Exception('Failed to load User');
  }}

class User {
  int? pk;
  String? username;

  User({this.pk, this.username});

  User.fromJson(Map<String, dynamic> json) {
    pk = json['pk'];
    username = json['username'];}

  Map<String, dynamic> toJson() {
    final Map<String, dynamic> data = new Map<String, dynamic>();
    data['pk'] = this.pk;
    data['username'] = this.username;
    return data;}}

class HomeScreen extends StatefulWidget {
  const HomeScreen({super.key});

  @override
  State<HomeScreen> createState() => _HomeScreenState();}

class _HomeScreenState extends State<HomeScreen> {
  late Future<User> futureUser;

  @override
  void initState() {
    super.initState();
    futureUser = fetchUser();}

  @override
  Widget build(BuildContext context) {
    return MaterialApp(
      .........................
            FutureBuilder<User>(
              future: futureUser,
              builder: (context, snapshot) {
                if (snapshot.hasData) {
                  return Text(snapshot.data!.username ?? 'noname');
                } else if (snapshot.hasError) ;
                print(snapshot.error);
                {return Text('${snapshot.error}');}
                return const CircularProgressIndicator();
              },),),],)),),);}}

Here is the Django Rest framework setting:

REST_FRAMEWORK = {
    'DEFAULT_AUTHENTICATION_CLASSES': [
        'rest_framework.authentication.BasicAuthentication',
        'rest_framework.authentication.SessionAuthentication',
    ]
}

AUTHENTICATION_BACKENDS=['users.models.EmailBackend']

CORS_ALLOW_ALL_ORIGINS=True
AllowAny =True

My question:

After login why is my HttpHeaders.authorizationHeader not working, if the user is already loged in should I be able to directly get user details using the Token Key?

In my Django I am getting Unauthorized: /api/dj-rest-auth/user/

CodePudding user response:

You need to add TokenAuthentication to your DEFAULT_AUTHENTICATION_CLASSES

REST_FRAMEWORK = {
    'DEFAULT_AUTHENTICATION_CLASSES': [
        'rest_framework.authentication.BasicAuthentication',
        'rest_framework.authentication.SessionAuthentication',
        'rest_framework.authentication.TokenAuthentication',
    ]
}

add rest_framework.authtoken to INSTALLED_APPS:

INSTALLED_APPS = [
    ...
    'rest_framework.authtoken',
]

In Flutter:

    headers: {
      "Authorization": 'Token XXXXXXXXXXXXX'
    },);

  • Related