skip to Main Content

i developed the API in Laravel for authentication and authorization. while user user authentication at api side (through postman) is working fine, as i login from the API from front side it giving unauthorized error

enter image description here

below is my code where i am getting it wrong. or am I using wrong approach at frontend side?

   $(function () {
            $.ajaxSetup({
                    headers: {
                            'X-XSRF-TOKEN': $('meta[name="_token"]').attr('content')
                    }
            });
    });
    
  $('#ajaxcall').on('click', function(e) {
      
       
          e.preventDefault();
                var email = $('#email').val();
                var password = $('#password').val();
                var token = $('input[name="_token"').val();
                $.ajax({
                    url: '{{url("api/login")}}',
                    type: "post",
                    data: {
                        '_token': token,
                        'email': email,
                        'password': password
                    },
                    success: function(res) {
                        console.log(res)
                        if (res.error) {
                            $('#loginerror').text(res.error)
                        }
                        if (res.success) {
                            window.location.href = '/home';
                        }
                    }
                })
          
   });

laravel code

<?php

namespace AppHttpControllersApi;

use AppHttpControllersController;
//use IlluminateHttpRequest;
//use IlluminateHttpRequestsLoginRequest;
use AppHttpRequestsLoginRequest;
use AppHttpHelpersHelpers;
use AppHttpResourcesUserResource;
use Auth;
class LoginController extends Controller
{
    //
    public function login(LoginRequest $request)
    {
    
        if(!Auth::attempt($request->only('email','password')))
        {
            Helpers::sendError('Email or password is wrong !!!');
        }
        return new UserResource(auth()->user());
    }
// }
<?php

namespace AppHttpRequests;

use IlluminateFoundationHttpFormRequest;
use IlluminateContractsValidationvalidator;
use AppHttpHelpersHelpers;


class LoginRequest extends FormRequest
{
    /**
     * Determine if the user is authorized to make this request.
     */
    public function authorize(): bool
    {
        return true;
    }

    /**
     * Get the validation rules that apply to the request.
     *
     * @return array<string, IlluminateContractsValidationRule|array|string>
     */
    public function rules(): array
    {
                

        /*return [
            //
        ];*/
        return['email'=>'required|email|exists:users,email','password'=>'required'];
        
    }
    public function failedValidation(Validator $validator)
    {
        
        Helpers::sendError('validation error',$validator->errors());
    }
}

2

Answers


  1. you should also add this in main layout blade file

    <head>
        <meta name="_token" content="{{ csrf_token() }}">
      </head>
    
    Login or Signup to reply.
  2. You can add this in your root file(blade) layout and also make sure your login route is not wrapped with middleware because that can make the 401 error occur too.

    <meta name="csrf-token" content="{{ csrf_token() }}" />
    

    and then in your javascript, you can do this

          let _token   = $.('meta[name="csrf-token"]').attr('content');
      $('#ajaxcall').on('click', function(e) {
          
           
              e.preventDefault();
                    var email = $('#email').val();
                    var password = $('#password').val();
                    var token = _token ;
                    $.ajax({
                        url: '{{url("api/login")}}',
                        type: "post",
                        data: {
                            '_token': token,
                            'email': email,
                            'password': password
                        },
                        success: function(res) {
                            console.log(res)
                            if (res.error) {
                                $('#loginerror').text(res.error)
                            }
                            if (res.success) {
                                window.location.href = '/home';
                            }
                        }
                    })
              
       });
    
    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search