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
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
you should also add this in main layout blade file
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.
and then in your javascript, you can do this