Symfony 5 - How implement basic authentication on REST call - php

I have created a URL that take a request in method POST. He take a JSON and he return me a XML converted file.
I would like, before the request, a basic authorization ( just a password , i need not registered user )on this URL to allow the user make the request. But i don't understand how the authorization working on symfony.
I think that all i need is in this page of documentation
but i get some errors and i not understand how it work (what is realme? What does it mean with Secured Area?)
This is my controller, how can i implement a basic authentication on this REST call ?
class IndexController extends AbstractController
{
/**
* #Route("/converter-hl7", name="converter", methods={"POST"})
*/
public function index(Request $request) {
$json = $request->getContent();
$converter = new HL7ConverterService($json, new ErrorService());
$xml = $converter->outputXML();
$response = new Response($xml);
$response->headers->set('Content-Type', 'xml');
return $response;
}
}

i use JWT for my API's to Control and Secure Api access
you should check this Bundle
But to use this you need to create user .
if you don't want to create a user you could demand a password from the sender and integrate it in the request then control access based on that.

Related

Laravel form request - $this->user() vs. auth()->user() in authorization

Can anyone explain if there is a reason why we should not be using getting the authenticated user within a from request authorize method, via the Auth::user() or auth()->user() helpers vs. the $this->user() method as suggested in docs?
https://laravel.com/docs/5.8/validation#authorizing-form-requests
In my case, I am trying to unit test a form request and auth()->user() allows me to retrieve the user whereas $this->user() does not as I am not making a full request. I am just creating the form request object for my test.
public function setUp(): void
{
parent::setUp();
$this->subject = new \App\Http\Requests\OrderStoreRequest();
}
// Acting as has no effect when manually creating the orderStoreRequest object
public function testAuthorize()
{
$this
->actingAs(\factory(User::class)->create())
->assertTrue($this->subject->authorize());
}
ActingAs() is calling the Laravel Auth system, which in the request lifecycle is put into the request (See). Since you are just calling your request without this lifecycle, you will never get anything injected into the Request.
For your code to work, you need to set the UserResolver. This can be done like so.
$this->subject->setUserResolver(function () use($user) {
return $user;
});
For ease of usage, i would highly recommend doing Laravel feature tests instead of unit testing. You are gonna fight your way through a lot of approaches, there is not meant to be called without the Laravel lifecycle. Which you will get doing call() and json() on the app.

How to get User object in Doctrine event subscriber in Zend Expressive

Based on https://github.com/DamienHarper/DoctrineAuditBundle I'm trying to develop audit module for my Zend Expressive application.
But I don't know how to get the User data (id) within audit logic.
I see that $user is passed as request attribute in
vendor/zendframework/zend-expressive-authentication/src/AuthenticationMiddleware.php, but this doesn't make it available via
$container->get(\Psr\Http\Message\ServerRequestInterface::class)->getAttribute(\Zend\Expressive\Authentication\UserInterface::class);
You might want to read again about the concept of middleware. In short, expressive has a middleware stack and depending on a request, it sends a the request through specific layers of middleware.
In your example the request goes through AuthenticationMiddleware. So if you have this as your pipeline:
$app->pipe(AuthenticationMiddleware::class);
$app->pipe(AuditMiddleware::class);
The request goes first through the AuthenticationMiddleware, which makes the UserInterface available in the request, and next through the AuditMiddleware.
In your AuditMiddleware and all middlewares after the AuthenticationMiddleware you can access the UserInterface like this:
function (ServerRequestInterface $request, RequestHandlerInterface $handler)
{
$user = $request->getAttribute(UserInterface::class);
// Do stuff here
return $handler->handle($request);
}
So in your case you probably need to write an AuditMiddleware that grabs the user from the request after the AuthenticationMiddleware and injects it in your Audit module.

Add Account token to routing

I'm trying to add an Account to the Silex route. My goal is to have routes like:
/{_account}/{_locale}/
/{_account}/{_locale}/products
/{_account}/{_locale}/block
You can find my Code here on github. It's a small sample. I can read the account token from the request and save the Account in the AccountListener.
I try to handle the _account like _locale. Once set or updated the application don't have to bother about it. That means that the _account param will be set automatically if I call $app['url_generator']->generate('blog').
This is my current problem. I don't know how to inform the UrlGenerator to set these param.
Maybe my approach is completely wrong.
I Hope you can send me some examples or Cookbooks or somethink. Or a merge request.
The UrlGenerator uses parameters from the request_context (as you can see in the code) so you could set those in your listener.
src/app.php
$dispatcher = $app['dispatcher']->addSubscriber(
new AccountListener(
new AccountRepository(),
$app['request_context'],
$app['monolog']
)
);
SilexLab\Listener\AccountListener
public function __construct(
AccountProvider $accountProvider,
RequestContext $requestContext,
Logger $logger
) {
//...
$this->requestContext = $requestContext;
}
public function onKernelRequest(GetResponseEvent $event)
{
//...
$request->attributes->set('_account', $account);
$this->requestContext->setParameter('_account', $account);
}

Show protected methods in SWAGGER (RESTLER 3)

Im making an API, and I really like the SWAGGER interface for methods, but all my API requests will need to be protected and verified by Basic Auth. So any of those protected methods or classes will be available for SWAGGER. Is there any way to show them ?
Placing the following in your index.php will enable listing of protected methods
use \Luracast\Restler\Resources;
Resources::$hideProtected = false;
Accessing Basic Auth protected api from swagger will work just fine. But authenticating and getting through basic auth will require some work done on the swagger ui side
I read this on the SWAGGER docs but.. I need to dynamically send user & password typed using SWAGGER UI input fields.. and then convert them for Basic Auth. So actually the question is how to add user&pwd fields into every SWAGGER request and set them to be sent via Basic Auth headers.
// add a new ApiKeyAuthorization when the api-key changes in the ui.
$('#input_apiKey').change(function() {
var key = $('#input_apiKey')[0].value;
if(key && key.trim() != "") {
window.authorizations.add("key", new ApiKeyAuthorization("api_key", key, "header"));
}
})

Yii OAuth Implementation

Requiremen :- Yii, OAuth implemenation to authenticate and fetch user data.
I found out that there are two extensions. Eauth(support OAuth 2.0 and other social networking sites) and Eoauth(OAuth 1.0). Correct me If i am wrong.
I dont have to authenticate any social networking site. It's a different url from where I need to get the data.
Now i could successfully login and authenticate using "eoauth" extension but also I need to fetch information about the user. I don't find any function or way how to fetch data from url which lies under OAuth layer. Does Eauth or Eoauth supports fetching or it has to be custom coded ?
If this extensions does not do this then what is the other way I can authenticate and fetch data ?
Of course, Eauth supports fetching user's data.
Let's see on Eauth structure. We have directories /services, /custom_services and class EOAuthService. EOAuthService contains method makeSignedRequest(), that return the protected resource from third-party site.
So, this method we can call from our serviceClass, that extends EOAuthService. For example, class FacebookOAuthService in /services directory. The class contains protected method fetchAttributes(), it calls method makeSignedRequest($url) and get $info (in JSON) from third-party site (FB in our example). Properties of this object - it's our user's data.
What about /custom_services? The directory contains classes for tuning our "BaseServiceClass".
So, for example, CustomFacebookOAuthService extends FacebookOAuthService extends EOAuthService.
You need create your own class, which will make signed request for your third-party site and get proper response (in JSON, for example). Then fetch gotten info - and voila!
Of course, user must be authenticated by third-party site for fine auth on your application through oauth.
Though Old but You just need to use CURL request to the end URL and you will get your data. I guess those modules doesn't have the function to fetch a data. I hope this might help you. I have used in one of my code and It was successful
public function GetData($url){
$signatureMethod = new OAuthSignatureMethod_HMAC_SHA1();
$request = OAuthRequest::from_consumer_and_token($this->consumer,$this->token, 'GET', $url, array());
$request->sign_request($signatureMethod, $this->consumer, $this->token);
$fetchUrl = $request->to_url();
$response = Yii::app()->CURL->run($fetchUrl);
return json_decode($response);
}

Categories