首页 > 解决方案 > 如何为登录请求修复 401(未经授权)

问题描述

我使用 JWT 身份验证的登录请求出现 401 错误,在注册页面上它运行良好,它在数据库中创建用户,但登录不起作用。我真的不知道要包含哪些代码,所以请随意使用所需的代码。

我验证输入的凭据已存在于数据库中

登录.ts

export class LoginComponent {

  public form={
em:null,
pass:null
  };
  public error = null;
    constructor(private http :HttpClient) { 

    }
Submit(){
    this.http.post('http://localhost:8000/api/login',this.form).subscribe(
      data => console.log(data),
      error => console.log(error)
    );

  }
    }

api.php

<?php


Route::group([

    'middleware' => 'api',


], function () {

    Route::post('login', 'AuthController@login');
});

登录功能

public function login()
    {
        $credentials = request(['email', 'password']);

        if (! $token = auth()->attempt($credentials)) {
            return response()->json(['error' => 'user does not exist'], 401);
        }

        return $this->respondWithToken($token);
    }

标签: angularlaravel

解决方案


Authorization您需要在发布请求中发送标头:

Authorization: 'Bearer ' + jwtToken

与其在每个 api 调用中手动发送授权标头,不如使用HttpInterceptor.

有关更多详细信息,请参阅此博客


推荐阅读