Laravel 4 Basic Auth custom error - laravel

I'm using the 'HTTP Basic Authentication' feature of laravel. I want to customize the error message which is generated from laravel if the entered credentials are wrong.
Is it possible to catch the 401 Error which is generated when HTTP Auth fails?
Hope you can help me.
Regards

Basic Auth
Try to capture 401 error and return cusom view?!
App::error(function($exception, $code)
{
switch ($code)
{
case 401:
return Response::view('errors.403', array(), 401);
case 403:
return Response::view('errors.403', array(), 403);
case 404:
return Response::view('errors.404', array(), 404);
case 500:
return Response::view('errors.500', array(), 500);
default:
return Response::view('errors.default', array(), $code);
}
});
Using Auth library
I think, code is pretty straightforward and self explaining.
Just to note, $errors variable is of type MessageBag and is available in views even if you don't set it explicitly! Which is great! :)
I used simple routing, place it into your controllers
app/routes.php
Route::get('auth', function()
{
$creds = array(
'email' => Input::get('email'),
'password' => Input::get('password'),
);
if ( ! Auth::attempt($creds))
{
$errors = new MessageBag;
$errors->add('login', trans("Username and/or password invalid."));
return Redirect::to('/')->withErrors($errors);
}
return Redirect::to('/protected/area');
});
Route::get('/', function(){
return View::make('hello');
});
// app/views/hello.php
#if($errors->has('login'))
{{ $errors->first('login') }}
#endif

Here's how I did it:
Route::filter('auth.basic', function()
{
$message = [
"error" => [
"code" => 401,
"message" => "Invalid Credentials"
]
];
$headers = ['WWW-Authenticate' => 'Basic'];
$response = Auth::basic();
if (!is_null($response)) {
return Response::json($message, 401, $headers);
}
});
If you look in Illuminate\Auth\Guard you'll find the basic method that's called by Auth::basic(). It either returns null or a Response object via the getBasicResponse method.
/**
* Attempt to authenticate using HTTP Basic Auth.
*
* #param string $field
* #param \Symfony\Component\HttpFoundation\Request $request
* #return \Symfony\Component\HttpFoundation\Response|null
*/
public function basic($field = 'email', Request $request = null)
{
if ($this->check()) return;
$request = $request ?: $this->getRequest();
// If a username is set on the HTTP basic request, we will return out without
// interrupting the request lifecycle. Otherwise, we'll need to generate a
// request indicating that the given credentials were invalid for login.
if ($this->attemptBasic($request, $field)) return;
return $this->getBasicResponse();
}
Here's getBasicResponse:
/**
* Get the response for basic authentication.
*
* #return \Symfony\Component\HttpFoundation\Response
*/
protected function getBasicResponse()
{
$headers = array('WWW-Authenticate' => 'Basic');
return new Response('Invalid credentials.', 401, $headers);
}
Here we finally have our 'Invalid credentials.' text that we're looking to change. We see it's just returning an instance of a Symphony response with a 401 status code and the Basic Auth header and null in all other occasions. So, we'll just check for a non-null result and if we get one, return our new response as shown above.
Also, if you want it to actually be stateless you should use:
Auth::onceBasic()
I don't know how future proof this method is, but it works as of Laravel 4.1.
Final results once again:
Route::filter('auth.basic', function()
{
$message = [
"error" => [
"code" => 401,
"message" => "Invalid Credentials"
]
];
$headers = ['WWW-Authenticate' => 'Basic'];
$response = Auth::onceBasic();
if (!is_null($response)) {
return Response::json($message, 401, $headers);
}
});

Related

Get user data using passport access token - Laravel

I've been trying to return user data using access token but keep getting error:
Invalid payload
My method was to get the token then find the user id from oauth_access_tokens table. My code is as follows:
public function authenticateUser($token){
$user_id = DB::table('oauth_access_tokens')->where('id', trim($token))->value('user_id');
$user = \App\User::find($user_id);
Auth::login($user, true);
}
The token is something like this:
eyJ0eXAiOiJKV1QiLCJhbGciOiJSUzI1NiIsImp0aSI6IjkyZGU3ZGYyMDcxZjgzMzU5YWUxMmRlYzM4ZGJiM2EyMTk0NzEyYTQ5NmRiNzgwZWJkMDg2Yjc0NThkZjU0NmFlZmU2Yzg0N2Q0Mjc5MDAxIn0.eyJhdWQiOiIxIiwianRpIjoiOTJkZTdkZjIwNzFmODMzNTlhZTEyZGVjMzhkYmIzYTIxOTQ3MTJhNDk2ZGI3ODBlYmQwODZiNzQ1OGRmNTQ2YWVmZTZjODQ3ZDQyNzkwMDEiLCJpYXQiOjE1NzczNzE4MDYsIm5iZiI6MTU3NzM3MTgwNiwiZXhwIjoxNjA4OTk0MjA1LCJzdWIiOiIzMCIsInNjb3BlcyI6W119.Io4xkJYEczbI7rhFD_UKAoe7v_1-RLJXjA6XqGIe2nRAWEgMkg-mokQUiGz41xYVazmDmACDwwYSRr-iTTzwc591NABfxsmMk7OdYkUKb93UTA3JhKClEGSP82y1QrIfm9XTZ0KKDaCKlfKqye1Aobj9zFthQdApegTaK61ReLQa7MzO6EM5fcZ3udsLL3QpKXFuyO6JcPKRauKIbA8oNIKEdadprLWJSeQieIyA8lpYOr453QzgZGgzCwPY1U2RmIbCzqyNQD_L5264-ix1503KxgPt4F_Cl82WXm7tNsZKNwE-vGKhCc2CcgAgTV1lIj7ItDf2KpDh_Jt96Uiv2eJ3OtXYvuOTErz9mNnQ1T38hxQmKDh8XlG3f7JgIWWzN6m8ItBV1KyGZi0-vn2HXetkZTNIyfJV8E5-RaGUzIKX7RejWd5BVaqFw0OjDYPeliVOaZzfcZCRnPDSJBGwf7YqJrRXP61LMasn_ZJ-i8G5JIaQx2vdmfYgE41O5F9fE5uEF5-mIV979RbnswL6CJsSGmmUMzC7mPhqL6HtPu2hMTnfHbKY0-efqtzZ5I2TBQU6ODM37RFN5TEljoEgBFG6kAImkGDy4QFH5uqt6V7-ZFxvrKQzQozgezSgA6ITF1sRb7yWfI-9rF7sYE_aKu3r1_KRr4UJLoZqFyvGPP0
Isn't it the token that I should pass to the function above. When I pass it to base64_decode, I see the JSON object along with other gibberish. What am I doing wrong here?
I have never used Laravel Passport before, but I would imagine that the user is already authenticated when using the token. So maybe a route like:
Route::get('/user', function(Request $request) {
return Auth::user();
})->middleware('auth:api');
I've reached to way to do so eventually by sending a request to the api in the other machine while adding the token in the header:
public function authenticateUser($token) {
$client = new \GuzzleHttp\Client();
try {
$response = $client->request('GET', env('APP_API_URL') . '/api/v2/user_data', [
'headers' => [
'Accept' => 'application/json',
'Authorization' => 'Bearer ' . $token,
],
]);
$request = (string) $response->getBody();
$request = json_decode($request);
$user = User::where('email', $request->data->user->email)->first();
Auth::login($user, true);
} catch (RequestException $e) {
dd('Something went wrong while connection to the api');
}
}

Laravel Passport consuming own API fail

I'm building a SPA with Vue. My front-end and my back-end (Laravel) are in the same codebase. I want to approach my API (that is in my back-end) via the Laravel Passport Middleware CreateFreshApiToken. I'm approaching my sign in method in my AuthController via web.php.
My problem:
As soon as I'm successfully signed in via my sign in method I would expect that at this time Passport created the laravel_token cookie. This is not the case. The cookie is created after a page refresh. But as I said I'm building a SPA and that's why I don't want to have page refreshes.
What I want:
I want to sign in via my sign in method then use the Passport CreateFreshApiToken middleware. After that I want to use the (just created in the middleware) laravel_token cookie so that I can correctly and safely speak to my own API in my signed-in section of the SPA.
More information:
Kernel.php
// Code...
protected $middlewareGroups = [
'web' => [
// other middlewares...
\Laravel\Passport\Http\Middleware\CreateFreshApiToken::class,
],
];
// Code...
AuthController.php
// Code...
public function login()
{
if (Auth::attempt(['email' => Input::get('email'), 'password' => Input::get('password')], true)) {
return response()->json([
'user' => Auth::user(),
'authenticated' => auth()->check(),
]);
}
return response()->json(['authenticated' => false], 401);
}
// Code...
Login.vue
// Code...
methods: {
login: function (event) {
event.preventDefault();
this.$http.post(BASE_URL + '/login', {
email: this.email,
password: this.password,
})
.then(function (response) {
localStorage.user_id = response.body.user.id;
router.push({
name: 'home'
});
});
},
},
// Code...
What goes wrong? This:
CreateFreshApiToken.php
// Code...
public function handle($request, Closure $next, $guard = null)
{
$this->guard = $guard;
$response = $next($request);
// I'm signed in at this point
if ($this->shouldReceiveFreshToken($request, $response)) { // returns false unless you refresh the page. That's why it won't create the laravel_token cookie
$response->withCookie($this->cookieFactory->make(
$request->user($this->guard)->getKey(), $request->session()->token()
));
}
return $response;
}
protected function shouldReceiveFreshToken($request, $response)
{
// both methods below return false
return $this->requestShouldReceiveFreshToken($request) &&
$this->responseShouldReceiveFreshToken($response);
}
protected function requestShouldReceiveFreshToken($request)
{
// $request->isMethod('GET') - returns false because it's a POST request
// $request->user($this->guard) - returns true as expected
return $request->isMethod('GET') && $request->user($this->guard);
}
protected function responseShouldReceiveFreshToken($response)
{
// $response instanceof Response - returns false
// ! $this->alreadyContainsToken($response) - returns false as expected
return $response instanceof Response &&
! $this->alreadyContainsToken($response);
}
// Code...
I assume it is possible what I want to achieve right? If yes, how?
I had the same issue, decided to stick to client_secret way. I guess it's not relevant for you now, but I've found 2 ways of receiving the laravel token without refresh:
1) sending dummy get request with axios or $http, whatever you use - token will get attached to response;
2) changing requestShouldReceiveFreshToken method in CreateFreshApiToken.php - replace return $request->isMethod('GET') && $request->user($this->guard); with return ($request->isMethod('GET') || $request->isMethod('POST')) && $request->user($this->guard);
function consumeOwnApi($uri, $method = 'GET', $parameters = array())
{
$req = \Illuminate\Http\Request::create($uri, $method, $parameters, $_COOKIE);
$req->headers->set('X-CSRF-TOKEN', app('request')->session()->token());
return app()->handle($req)->getData();
}

Unable to communicate with the PayPal error

i m using Magento ver. 1.8.1.0
i got Unable to communicate with the PayPal gateway. error with paypal express checkout or paypal Payments Pro in both case.
i have already Enable SSL verification :- No
Can you explain me about this error.
Thanks
Paypal have recently rolled out some security updates on the sandbox (production will be updated in June) https://devblog.paypal.com/upcoming-security-changes-notice/
Most importantly, TLS 1.0 and 1.1 are no longer accepted by the sandbox, and the Magento Paypal module doesn't use 1.2 by default. We can expect an official patch to fix this shortly, but in the meantime you can work around it by overriding Mage/Paypal/Model/Api/Nvp.php (in your local codepool or with a rewrite) with the following call function:
public function call($methodName, array $request)
{
$request = $this->_addMethodToRequest($methodName, $request);
$eachCallRequest = $this->_prepareEachCallRequest($methodName);
if ($this->getUseCertAuthentication()) {
if ($key = array_search('SIGNATURE', $eachCallRequest)) {
unset($eachCallRequest[$key]);
}
}
$request = $this->_exportToRequest($eachCallRequest, $request);
$debugData = array('url' => $this->getApiEndpoint(), $methodName => $request);
try {
$http = new Varien_Http_Adapter_Curl();
$http->addOption(CURLOPT_SSLVERSION,6);//CURL_SSLVERSION_TLSv1_2
$config = array(
'timeout' => 60,
'verifypeer' => $this->_config->verifyPeer
);
if ($this->getUseProxy()) {
$config['proxy'] = $this->getProxyHost(). ':' . $this->getProxyPort();
}
if ($this->getUseCertAuthentication()) {
$config['ssl_cert'] = $this->getApiCertificate();
}
$http->setConfig($config);
$http->write(
Zend_Http_Client::POST,
$this->getApiEndpoint(),
'1.1',
$this->_headers,
$this->_buildQuery($request)
);
$response = $http->read();
} catch (Exception $e) {
$debugData['http_error'] = array('error' => $e->getMessage(), 'code' => $e->getCode());
$this->_debug($debugData);
throw $e;
}
$response = preg_split('/^\r?$/m', $response, 2);
$response = trim($response[1]);
$response = $this->_deformatNVP($response);
$debugData['response'] = $response;
$this->_debug($debugData);
$response = $this->_postProcessResponse($response);
// handle transport error
if ($http->getErrno()) {
Mage::logException(new Exception(
sprintf('PayPal NVP CURL connection error #%s: %s', $http->getErrno(), $http->getError())
));
$http->close();
Mage::throwException(Mage::helper('paypal')->__('Unable to communicate with the PayPal gateway.'));
}
// cUrl resource must be closed after checking it for errors
$http->close();
if (!$this->_validateResponse($methodName, $response)) {
Mage::logException(new Exception(
Mage::helper('paypal')->__("PayPal response hasn't required fields.")
));
Mage::throwException(Mage::helper('paypal')->__('There was an error processing your order. Please contact us or try again later.'));
}
$this->_callErrors = array();
if ($this->_isCallSuccessful($response)) {
if ($this->_rawResponseNeeded) {
$this->setRawSuccessResponseData($response);
}
return $response;
}
$this->_handleCallErrors($response);
return $response;
}
The important line is $http->addOption(CURLOPT_SSLVERSION,6);//CURL_SSLVERSION_TLSv1_2

How can I process a Response directly in Laravel?

I'm writing code in my Laravel Controller and I want to trap some exceptions firing a response directly without returning something to the routes.
For example, I wrote a method for returning a 404 response:
public static function respondNotFound( $message = null, $instantResponse = false )
{
$message = $message ? $message : "Not Found";
$statusCode = self::STATUS_NOTFOUND;
return self::makeResponse( array( 'status' => $statusCode, 'message' => $message ), $statusCode );
}
This method calls another one for building an Illuminate Response
protected static function makeResponse( $data, $statusCode = self::STATUS_OK, $instantResponse = false )
{
$response = Illuminate\Support\Facades\Response::json( $data, $statusCode );
$response->setCallback( Input::get( 'callback' ) );
if( $instantResponse ) {
//..... I want to fire my Response here!
}
else {
return $response;
}
}
Referring to the method above, I want to specify that my response must be fired directly rather than being returned outside, avoiding a "waterfall of return".
My solution is to set up some php headers and then kill the script, but I think that it's a bit rough.
Can someone help me?
Thanks in advance.
I'm confused - why dont you just use the App::missing() filter and handle your 404 in there?
In 'app/start/global.php' add:
App::missing(function($exception)
{
if (Request::ajax())
{
return Response::json( ['status' => 'error', 'msg' => 'There was an error. I could not find what you were looking for.'] );
}
elseif ( ! Config::get('app.debug'))
{
return Response::view('errors.404', array(), 404);
}
});
From looking at your code - you seem to be duplicating the response class. I dont understand why you are doing all of that, when you can just do
return Response::view('error', $message, $statuscode);
anywhere in your application...
Edit: you could also do
App::abort(404);
And then catch the abort filter in your app. You can change the 404 to be any HTTP response code you want.

Laravel, log in user for one request

I am building a REST API with Laravel, and I have a filter that checks for a TOKEN:
Route::filter('api.auth', function() {
$token = Request::header('X-CSRF-Token') ? Request::header('X-CSRF-Token') : '';
if (empty($token)) {
return Response::json(
['message' => 'A valid API key is required!'],
401
);
};
$user = User::where('token', '=', $token);
if ($user->count()) {
$user = $user->first();
Auth::login($user);
} else {
return Response::json(
['message' => 'Your token has expired!'],
401
);
};
});
If everything is ok, the filter will log in the user with uth::login($user);
How can I log him for only 1 request?
Since this filter is going to be checked on every request, I think it would be better to log the user out each time.
I have seen this in Laravel's docs, not sure how to apply it:
if (Auth::once($credentials))
{
//
}
Could I have a callback in my response? where I could log the user out?
/*
Get all products.
*/
public function getProducts() {
$products = Auth::user()->products;
return Response::json($products, 200);
}
Any ideas?
If you haven't user's password use this:
if(Auth::onceUsingId($userId)) {
// do something here
}
If I correctly understand the question then I would say that, just replace following
Auth::login($user);
with this (To log the user in only for current request):
Auth::once(['email' => $user->email, 'password' => $user->password]);
If you log in a user only for once then you don't have to manually logo out the user, the user will be asked again for to log in on next request.

Resources