Laravel api block browser/postman access - php

I just finished api on laravel , it work perfectly on front-end but I want to block api to access via browser or postman or etc, I just want to POST and GET from my front.
for example, if someone run post request in browser:
And if run get request in browser (auth need):
Also if someone run this url api.mywebsite.com, see Laravel intro page, and I don't want to show to user, how can I prevent this?
And last thing, if user runs post or get request in postman, it works, and I only want it to work with my domain. I am using this CORS middleware.
How to prevent user access to get/post request via browser/postman?
How to limit api just on my domain name?

For remove Laravel welcome page:
Go to
route/web.php, comment this line:
return view('welcome');
Or replace with:
return abort(404);
Or you can remove with own route, it return same 404
For remove route login, you need to go to:
app/Http/Middleware/Authenticate.php
Find and replace redirectTo function with:
protected function redirectTo($request)
{
if (! $request->expectsJson()) {
return abort('404');
}
}
Or really redirect to your login page, or etc.
And go to config/cors.php and replace yours with this:
'allowed_origins' => ['http://yourwebsite.com'],
And no need to worry about postman but if you want to avoid people do a direct request to your api you need to use api_token
Oh I forgot your another question, after all, you should not see any of these errors on your browser, except you forget to set these on .env:
APP_ENV=production
APP_DEBUG=false

Related

Laravel 4.2 Redirect::to with GET Params

Is there a possibility to redirect to an url with GET params using Redirect::to() in Laravel 4.2?
I'm trying to redirect users after login to requested page when they weren't logged in.
If you are not logged in and you visit authorized page, I save the full requested url in session (this url can be something like https://page.com/settings or https://page.com/post/23 or https://page.com/post/23?show=full. Lots of variants).
When you then log in and you have an url stored in your session, I redirect you with Redirect::to(https://page.com/post/23)
In first two cases there is no problem, but when I use Redirect::to(https://page.com/post/23?show=full) GET params are ignored.
Is there an option to redirect to url with GET params included?
There's problem with your application. If I understand you correctly, your query parameters (such as: ?param=true&param2=1) are not present in your url after redirect.
Consider the following example:
Route::get('/test', function () {
return Redirect::to('http://localhost:8000/test2?with=params');
});
Route::get('/test2', function () {
echo '1';
});
When I try to access: localhost:8000/test I get redirected to: http://localhost:8000/test2?with=params
Which is the expected behavior. Can you post an example where you do that redirect?
Also I'd suggest using: Redirect::intended() which does exactly what you want by itself.
Try this:
You can pass it like https://page.com/post/23/showFull
And you can got it via following way:
Request::segment(3);
Why not Redirect::back()? The auth filter should be able to redirect all the non-authed requests to the login page, then Redirect::back() the user to the previous visited page.
Edit: filter, not middleware.
In Laravel, By default this feature is available if you are using the auth middleware, as given below:
Route::group(array('before' => 'auth'), function(){
//authorized routes
});
Example
If the user without loging in, is accessing the url "example.com/User?abc=123", which is an authorized route.
Then the user will be redirected automatically to the login page.
After successful login the user will be automatically redirected to the url first requested ("example.com/User?abc=123")

Redirect 302 on Laravel POST request

I'm developing a Laravel Web Service.
When I try my POST routes with web forms, everything works fine, but when I try the same with a REST Client like Postman it doesn't get me the response that should.
It gives me status code 302, and redirects to "/". What's the problem?
This might be useful for other users that having the same problem cannot solve it with the accepted solution.
Make sure that the form fields names for instance <input type="text" name="document_name"> (document_name), match the names of the rules fields declared in the model.
public static $rules = ['document_name' => 'required|string'];
It doesn't throw any errors, nothing in the logs, it just redirects to the form, therefore the difficulty to find the problem.
When you try to POST request by Postman,you need to add _token field and it's value which is used to be protect XSS attack.See https://laravel.com/docs/5.2/routing#csrf-protection
When visiting the endpoint using Postman, set the Header
Accept: application/json
or Laravel would never know it's an API client and thus redirect with 302 message.
It's the mechanism for latest Laravel version since they provide api.php router beside web.php router.
Http status code 302 is used for redirection. It can be due to server side problem, Please check your laravel project's error log file or apache's error log file.
it looks like in postman you should point that the data you send is 'x-www-url-formurlencoded'

laravel redirection to splash page during testing

I've spent too many hours messing with this
I'm just starting with laravel and started a new project.
I want to be able to have a system where a certain users can access the site while it is in development. The rest of the public gets forwarded to the splash page.
I plan to create a secret route that sets a toggle in the session. If this toggle is set then the user can use the entire system. Else they are redirected to the splash page.
The issue is I cannot get it to redirect. I have been adding the code in the bootstrap->start.php file. The standard
header('location:www.thesite.com')
starts doing funny things that I do not understand.
If I run
return Redirect::to(htmlspecialchars_decode($url))
it returns the error:
BadMethodCallException
Method [run] does not exist on Redirect.
I have absolutely no idea what is going on or how to fix it.
Why is the redirection script returning an error? Is start.php not the correct location?
If so how can achieve my objective within laravel?
You should do this in your before filter in app/filters.php like so:
App::before(function($request){
if(!$request->is('splash') && Input::get('allow') != '1')
{
return Redirect::to('/splash');
}
);
Where /splash is your splash screen route. You can then do http://www.example.com?allow=1 to bypass the splash screen.
The before filter is a function that is run before every single route in your application.
Let me know if this works for you!

Laravel 4 bypass maintenance mode for a route

I have put my application down for maintenance using php artisan down command.
My custom maintenance page as a email input to accept the email from the user and store in my database to notify the user when the site is back up and running again.
But when I submit the form using POST, I get redirected to the maintenance mode page.
I want one particular route to bypass the maintenance mode. Is it possible?
Okay so I found a way to go about this problem.
In my app/routes file, I have a route as follows:
// app/routes.php
Route::resource('subscriber', 'SubscriberController');
Now this will route will match any request URI for the form subscriber*
In my app/start/global.php file, I did the following inside App::down()
// app/start/global.php
App::down(function() {
if(Request::is('subscriber*')) {
return null;
}
return Response::view('maintenance', array(), 503);
})
Now only for URIs of starting with subscriber, the maintenance mode page will not be displayed.
:D

Wrong return url in Yii framework

I have used Yii::app()->user->returnUrl but it always redirect me to localhost/index.php. Is there any particular configuration or some pieces of code that other programs that I must write? If you have another solutions let me know it.
#aslingga, can you please explain what you're trying to do with returnUrl? Are you just trying to get back to where you were after logging in, or are you using it somewhere else?
This is from the Yii documentation:
Redirects the user browser to the
login page. Before the redirection,
the current URL (if it's not an AJAX
url) will be kept in returnUrl so that
the user browser may be redirected
back to the current page after
successful login. Make sure you set
loginUrl so that the user browser can
be redirected to the specified login
URL after calling this method. After
calling this method, the current
request processing will be terminated.
In other words, if the page you're trying to request requires authentication, the URI of the page you're on gets stored in a session variable. Then, once you've logged in, it takes you back to that page.
One way I'd recommend troubleshooting is to do a print_r($_SESSION); just to make sure the returnUrl is actually being stored. Then you'll be able to check if index.php is being stored as returnUrl or if you're just being redirected there for some reason.
Looking at the CWebUser methods getState and setState might also be helpful.
I know this question is old but maybe this will help someone out since I didn't couldn't find a decent answer anywhere.
How getReturnUrl works
Setting a default return URL for your Yii app requires a bit of customization. The way it works out of the box is that you specify the default return URL each time you call it:
Yii::app()->user->getReturnUrl('site/internal');
The idea being that if a user were to visit a page that requires authentication, they will get redirected to the login page, but not before the site running
Yii::app()->user->setReturnUrl('site/visitedpage');
Now when the user logs in, they will be returned to the page they intended to go to.
While I like that functionality, having to set the default return URL each time is dumb. If you want to change the default return URL, you have to go find it throughout your code. I suppose you could set the value in a site parameter and call
Yii::app()->user->getReturnUrl(Yii::app()->params['defaultReturnUrl']);
I don't think I have to explain why that solution is annoying too.
My Solution
So when getReturnUrl is called without any parameters, it returns either '/index.php' or just '/'. This is fine in some cases, but not always. This is better IMO.
First, extend the CWebUser class and add the following extras
class WebUser extends CWebUser {
// default return URL property
public defaultReturnUrl;
// override the getReturnUrl method
public function getReturnUrl($defaultUrl=NULL) {
if ($defaultUrl === NULL) {
$defaultReturnUrl = $this->defaultReturnUrl;
}
else {
$defaultReturnUrl = CHtml::normalizeUrl($defaultUrl);
}
return $this->getState('__returnUrl',$defaultReturnUrl);
}
}
Now, let's add a couple items to the user component array.
'user' => array(
'class' => 'WebUser',
'defaultReturnUrl' => 'site/internal'
)
Not only does this allow you to set a default return URL in the config, but also maintains the ability to set a different default return URL and use the setReturnUrl functionality.
I think, you must set it:
Yii::app()->user->setReturnUrl('controller/action');

Categories