I would like to send the header "X-Content-Type-Options: nosniff" back with every response in my zend framework 2 application. How can I do that without explicitly coding it in every single controller method?
You can modify the response object via the bootstrap:
Module.php
/**
* On bootstrap event
*
* #param \Zend\Mvc\MvcEvent $e
*/
public function onBootstrap(MvcEvent $e)
{
$headers = $e->getResponse()->getHeaders();
$headers->addHeaderLine('X-Content-Type-Options: nosniff');
}
Related
I'm developing an API. I want to edit the incoming $request->url so it hits different routes based on the authorization. It should work for any kind of request (POST, GET , DELETE etc...).
By now I 've come this far. The middleware get hit, but $request->server->set('REQUEST_URI','http://...'); doesn 't have any effect. The incoming $request url stays at it is. This is the simplified middleware code of the class RedirectToUrl:
<?php
namespace App\Http\Middleware;
use Closure;
use Auth;
use Illuminate\Http\Request;
class RedirectToUrl
{
/**
* Handle an incoming request.
*
* #param \Illuminate\Http\Request $request
* #param \Closure $next
* #return mixed
*/
public function handle(Request $request, Closure $next)
{
if($request->user()->role()->first()->role === "admin"){
$request->server->set('REQUEST_URI','http://rest-api-with-session-httponly:8888/api/admin');
}elseif($request->user()->role()->first()->role === "basic"){
$request->server->set('REQUEST_URI','http://rest-api-with-session-httponly:8888/api/basic');
}else{
$request->server->set('REQUEST_URI','http://rest-api-with-session-httponly:8888/api/basic');
}
return $next($request);
}
}
I`ve put the middleware RedirectToUrl::class at the end of the middleware priority:
protected $middlewarePriority = [
\App\Http\Middleware\AddAuthHeader::class,
\Illuminate\Auth\Middleware\Authenticate::class,
\Illuminate\Session\Middleware\StartSession::class,
\Illuminate\View\Middleware\ShareErrorsFromSession::class,
\App\Http\Middleware\Authenticate::class,
\Illuminate\Session\Middleware\AuthenticateSession::class,
\Illuminate\Routing\Middleware\SubstituteBindings::class,
\Illuminate\Auth\Middleware\Authorize::class,
\App\Http\Middleware\CheckRole::class,
\App\Http\Middleware\RedirectToUrl::class,
];
Any hint appreciated.
Thx!
I have a Laravel application and I am currently working on integrating docker. The app runs perfectly locally but on production I simply can't log in. Every time I submit the log in form I get redirected to the log in form without any message of success nor failure.
I have realized that the request it reaches the controller it should but it does not reach the action. I put a die command in the constructor and it worked but it didn't when I did the same in the first line of the controller's action.
<?php
namespace App\Http\Controllers\Auth;
use App\User;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\Log;
use Monolog\Logger;
use Validator;
use App\Http\Controllers\Controller;
use Illuminate\Foundation\Auth\AuthenticatesUsers;
class AuthController extends Controller
{
/*
|---------------------------------------------------------------------
| Registration & Login Controller
|---------------------------------------------------------------------
|
| This controller handles the registration of new users, as well as the
| authentication of existing users. By default, this controller uses
| a simple trait to add these behaviors. Why don't you explore it?
|
*/
use AuthenticatesUsers;
/**
* Where to redirect users after login / registration.
*
* #var string
*/
protected $redirectTo = '/';
/**
* Create a new authentication controller instance.
*
* #return void
*/
public function __construct()
{
// die('something') works here
$this->middleware('guest', ['except' => ['logout', 'register', 'showRegistrationForm']]);
// die('something') works here too
}
/**
* Get a validator for an incoming registration request.
*
* #param array $data
* #return \Illuminate\Contracts\Validation\Validator
*/
protected function validator(array $data)
{
return Validator::make($data, [
'rut' => 'required|max:30',
'apellidos' => 'required|max:255',
'name' => 'required|max:255',
'email' => 'required|email|max:255|unique:users',
'password' => 'required|confirmed|min:6',
]);
}
/**
* Create a new user instance after a valid registration.
*
* #param array $data
* #return User
*/
protected function create(array $data)
{
}
public function login(Request $request)
{
//die('something'); doesn't work here
$this->validateLogin($request);
// If the class is using the ThrottlesLogins trait, we can automatically throttle
// the login attempts for this application. We'll key this by the username and
// the IP address of the client making these requests into this application.
if ($this->hasTooManyLoginAttempts($request)) {
$this->fireLockoutEvent($request);
return $this->sendLockoutResponse($request);
}
if ($this->attemptLogin($request)) {
return $this->sendLoginResponse($request);
}
// If the login attempt was unsuccessful we will increment the number of attempts
// to login and redirect the user back to the login form. Of course, when this
// user surpasses their maximum number of attempts they will get locked out.
$this->incrementLoginAttempts($request);
return $this->sendFailedLoginResponse($request);
}
}
I don't know if you still need it, but I had the same problem. You need to modify the paths in bootstrap/cache/config.php with the path that you set it for WORKDIR in Dockerfile.
I am trying to apply middleware on my routes like this:
Route::get('twitterlogin','TwitterController#gettwitterlogin');
Route::post('twitterlogin','TwitterController#posttwitterlogin');
Route::group(['middleware'=>'auth'],function()
{
Route::get('twitternewsfeed','TwitterController#gettwitternewsfeed');
Route::post('postimage','TwitterController#postimage');
Route::post('posttweet','TwitterController#posttweet');
Route::get('twitterlogout','TwitterController#gettwitterlogout');
Route::post('editprofilepic','TwitterController#posteditprofilepic');
Route::post('searchuser','TwitterController#postsearchuser');
Route::post('edittweet{id}','TwitterController#postedittweet');
Route::get('deletetweet{id}','TwitterController#getdeletetweet');
Route::post('editprofile','TwitterController#posteditprofile');
Route::get('userprofile{email}','TwitterController#getuserprofile');
});
And when i am trying to submit my login form it does not bring me on next page. It again opens the login page....what is the exact problem in this? My authenticate middleware is as follows....
<?php
namespace App\Http\Middleware;
use Closure;
use Illuminate\Contracts\Auth\Guard;
class Authenticate
{
/**
* The Guard implementation.
*
* #var Guard
*/
protected $auth;
/**
* Create a new middleware instance.
*
* #param Guard $auth
* #return void
*/
public function __construct(Guard $auth)
{
$this->auth = $auth;
}
/**
* Handle an incoming request.
*
* #param \Illuminate\Http\Request $request
* #param \Closure $next
* #return mixed
*/
public function handle($request, Closure $next)
{
if ($this->auth->guest()) {
if ($request->ajax()) {
return response('Unauthorized.', 401);
} else {
return redirect()->guest('twitterlogin');
}
}
return $next($request);
}
}
I assume you are using the Route::post('twitterlogin','TwitterController#posttwitterlogin') route to perform your login operation - please ensure that you're logging the user in with Laravel's Auth correctly and redirecting the user to the appropriate route in the posttwitterlogin method
I feel you also may also be using a different table to store user data - in which case, kindly ensure that you have your auth.php config file setup appropriately
In case you're using a custom authentication mechanism for some reason, you'll need to replace $this->auth->guest() in your middleware with the appropriate alternative check for the user not being logged-in
For eg: if you're setting a Session variable called is_authenticated to true with \Session::put('is_authenticated', true) upon successfully logging in, you'll check for it with if(\Session::get('is_authenticated') === true) in your Middleware instead of relying on the Laravel Auth method if ($this->auth->guest())
I am using ZF2 as a component of another application.
I am looking for a way to set the URL and View Template of the application between an init() and a run() call. I would like a way to either modify the Request and Response objects, or regenerate them with a different URL.
I currently use ob_start() and ob_get_clean() and a view template that simply generates the_content, thus injecting the output of ZF2 inside a page of another application.
Any suggestions on methodology would be appreciated.
In Module.php you can attach event to event manager for exemple.
class Module
{
public function onBootstrap($e)
{
$eventManager = $e->getApplication()->getEventManager();
$serviceManager = $e->getApplication()->getServiceManager();
$eventManager->attach(MvcEvent::EVENT_ROUTE, function($e) use ($eventManager, $serviceManager){
// your code here
}, -1000);
}
}
Or your action in your controller can dispatch another action and get the result
in action method :
$return = $this->forward()->dispatch('controllerName', array('action' => 'actionName', 'param1' => 'value', ...));
The following code inside another application can be used to set the calling URL and View Template from outside of the application:
$bootstrap = \Zend\Mvc\Application::init( include( '/zf2/config/application.config.php' ) );
$event = $bootstrap->getMvcEvent( );
/* Modify the event with a custom request. */
$request = new \Zend\Http\Request( );
$request->setMethod( \Zend\Http\Request::METHOD_GET );
$request->setUri( $custom_url );
$event->setRequest( $request );
/* Modify the view. */
$event->getViewModel()->setTemplate('layout/custom-layout');
ob_start( );
$bootstrap->run( );
$html = ob_get_clean( );
Hello Stackoverflow Community.
I am currently developing a XML-RPc Server with Zend Framework 2.
I have a ServiceController which is responsible for creating the Server
class ServiceController extends AbstractActionController{
public function xmlAction()
{
$this->handleXML();
$response = $this->getResponse();
return $response;
}
private function handleXML()
{
$xmlServer = new Zend\XmlRpc\Server();
$xmlServer->setClass('Beam\Model\service\Service', 'service');
echo $xmlServer->handle();
}
}
The ServiceClass is my Webapi
class Service{
/**
* getAvailablePackages
*
* getAvailablePackages is responsible for returning all packages which reference a given licensenumber
*
* #param string $licenseNumber
* #return String
*/
public function getAvailablePackages($licenseNumber){
//need to access the entityManager
$em = $this->getServiceLocator->get('Doctrine\ORM\EntityManager');
return "testresponse";
}
}
The XML RPC server works fine. I can call the getAvailablePackages method with a client and i get "testrespons" as a response.
However the problem is, that i would like to select some data from my database in the getAvailablePackages but i'm not sure how to access the entityManager in a non Controller class.
Does anyone have an idea on how to solve this problem ? Thankx for your responses.
Possible solution would be to have a factory.
<?php
namespace ....;
use Zend\ServiceManager\ServiceLocatorInterface;
use Zend\ServiceManager\FactoryInterface;
class ServiceFactory implements FactoryInterface
{
public function createService (ServiceLocatorInterface $serviceLocator)
{
return new Service ($serviceLocator->get ('Doctrine\ORM\EntityManager'));
}
}
thus, you would be able to have an access to Entity manager.