<?xml version="1.0" encoding="UTF-8"?><rss version="2.0"
	xmlns:content="http://purl.org/rss/1.0/modules/content/"
	xmlns:wfw="http://wellformedweb.org/CommentAPI/"
	xmlns:dc="http://purl.org/dc/elements/1.1/"
	xmlns:atom="http://www.w3.org/2005/Atom"
	xmlns:sy="http://purl.org/rss/1.0/modules/syndication/"
	xmlns:slash="http://purl.org/rss/1.0/modules/slash/"
	>

<channel>
	<title>Back end development Archives - Crosstech IT | Blog</title>
	<atom:link href="https://crosstechit.com/blog/category/back-end-development/feed/" rel="self" type="application/rss+xml" />
	<link>https://crosstechit.com/blog</link>
	<description>Apps. Smart. Fun.</description>
	<lastBuildDate>Mon, 14 Jan 2019 19:11:06 +0000</lastBuildDate>
	<language>en-US</language>
	<sy:updatePeriod>
	hourly	</sy:updatePeriod>
	<sy:updateFrequency>
	1	</sy:updateFrequency>
	<generator>https://wordpress.org/?v=5.9</generator>

<image>
	<url>https://crosstechit.com/blog/wp-content/uploads/2019/01/cropped-favicon-1-32x32.png</url>
	<title>Back end development Archives - Crosstech IT | Blog</title>
	<link>https://crosstechit.com/blog</link>
	<width>32</width>
	<height>32</height>
</image> 
	<item>
		<title>Laravel Basic Authentication with Passport &#038; Dingo API &#8211; Improvements</title>
		<link>https://crosstechit.com/blog/2019/01/13/laravel-basic-authentication-with-passport-dingo-api-improvements/</link>
					<comments>https://crosstechit.com/blog/2019/01/13/laravel-basic-authentication-with-passport-dingo-api-improvements/#respond</comments>
		
		<dc:creator><![CDATA[Daniel Isac]]></dc:creator>
		<pubDate>Sun, 13 Jan 2019 17:27:41 +0000</pubDate>
				<category><![CDATA[Back end development]]></category>
		<guid isPermaLink="false">https://crosstechit.com/blog/?p=67</guid>

					<description><![CDATA[<p>In the last post we have managed to login via Passport and return a response containing the access token. This way we need to store the access token on client side and send it attached to every request in order to access the protected routes. As you&#8217;ve may already heard, storing sensitive data on client [&#8230;]</p>
<p>The post <a rel="nofollow" href="https://crosstechit.com/blog/2019/01/13/laravel-basic-authentication-with-passport-dingo-api-improvements/">Laravel Basic Authentication with Passport &#038; Dingo API &#8211; Improvements</a> appeared first on <a rel="nofollow" href="https://crosstechit.com/blog">Crosstech IT | Blog</a>.</p>
]]></description>
										<content:encoded><![CDATA[
<p>In the last post we have managed to login via Passport and return a response containing the access token. This way we need to store the access token on client side and send it attached to every request in order to access the protected routes. As you&#8217;ve may already heard, storing sensitive data on client side could be a security issue. There are ways to protect user&#8217;s data but we will go for a safer way (in my opinion) and store the access token inside a cookie. This cookie is passed on every request/response between client and server and cannot be altered by client.<br></p>



<h2>Where&#8217;s the start point?</h2>



<p> We&#8217;ll try to implement what Laravel documentation describes here: <a href="https://laravel.com/docs/5.7/passport#consuming-your-api-with-javascript">https://laravel.com/docs/5.7/passport#consuming-your-api-with-javascript</a><br>Due the fact that I felt it is not even close to want it promises I want to share this article with you to understand better what is happening under the hood, or just save you few hour of investigating what is wrong with that. </p>



<h2>Security first</h2>



<p>For some security improvements I highly recommend adding the following link into .env file: <code>SESSION_SECURE_COOKIE=true</code>. This will allow cookies to be set only over HTTPS connection. This will protect us from any man-in-the middle attack.<br>Set it <strong>ONLY</strong> in production, when you load your website over HTTPS.</p>



<p>And in <code>config/session.php</code> ensure that <code>same_site</code> is set to <code>"strict"</code> in order to disable cross origin requests.</p>



<p>To protect against CSRF we will use Laravel&#8217;s csrf-token, but we&#8217;ll talk about this a bit later.</p>



<h2>Generating cookies</h2>



<p>Inside <code>app\Http\Kernel.php</code> insert following lines:</p>



<pre class="wp-block-preformatted"> 'api' =&gt; [<br>            \App\Http\Middleware\EncryptCookies::class,<br>             \Illuminate\Cookie\Middleware\AddQueuedCookiesToResponse::class,<br>            \Illuminate\Session\Middleware\StartSession::class,<br>            \Laravel\Passport\Http\Middleware\CreateFreshApiToken::class,<br>            ...<br>        ], </pre>



<p><strong>CreateFreshApiToken</strong>&nbsp;middleware will generate a JWT access token, create a cookie with it + CSRF token of current session + an expiration date and add it to the response.<br><strong>EncryptCookies</strong>&nbsp;will ensure that any incoming or outgoing cookies will be encrypted so the client cannot see the actual value of it.<br><strong>AddQueuedCookiesToResponse </strong>will attach the cookie to our response.<br><strong>StartSession</strong> will give us a session based on the cookie. This way we can access user&#8217;s data from it.</p>



<p>Make sure all 4 classes are inserted above: <code>'throttle:60,1'</code> and <code>'bindings'</code>.</p>



<h2>Here comes the twist</h2>



<p>If you take a look inside <strong>CreateFreshApiToken</strong> class, you will find the following method:</p>



<pre class="wp-block-preformatted"> <br>protected function requestShouldReceiveFreshToken($request)<br>{<br>        return $request-&gt;isMethod('GET') &amp;&amp; $request-&gt;user($this-&gt;guard);<br>} </pre>



<p>Until now I haven&#8217;t find a good reason for checking if the request method is &#8220;GET&#8221; (<strong>Later edit</strong>: I&#8217;ve found one. Maybe will discuss it in a further post) We need to give the user a valid cookie as soon as he logs in. And for oblivious reasons the login and register methods should always be a &#8220;POST&#8221;.  So I created a <strong>CustomCreateApiToken</strong> class and override the method as follows:</p>



<pre class="wp-block-preformatted">use Laravel\Passport\Http\Middleware\CreateFreshApiToken as Middleware;<br><br>class CustomCreateApiToken extends Middleware<br>{<br>   <br>    /**<br>     * Determine if the request should receive a fresh token.<br>     *<br>     * @param  \Illuminate\Http\Request  $request<br>     * @return bool<br>     */<br>    protected function requestShouldReceiveFreshToken($request)<br>    {<br>        return $request-&gt;user($this-&gt;guard);<br>    }<br>}<br></pre>



<h2>Routes middleware</h2>



<pre class="wp-block-preformatted"> <br>$api-&gt;version('v1', function ($api) {<br>    $api-&gt;group(['middleware' =&gt; 'api'], function ($api) {<br>        $api-&gt;post("register", 'App\Http\Controllers\Api\V1\Auth\RegisterController@register');<br>        $api-&gt;get("register/{token}", 'App\Http\Controllers\Api\V1\Auth\RegisterController@registerActivate');<br>        $api-&gt;post("login", 'App\Http\Controllers\Api\V1\Auth\LoginController@login');<br>        ...<br>    });<br><br>    // Protected routes<br>    $api-&gt;group(['middleware' =&gt; 'auth:api'], function ($api) {<br>        $api-&gt;get('profile', 'App\Http\Controllers\Api\V1\ProfileController@show');<br>        $api-&gt;get('logout', 'App\Http\Controllers\Api\V1\Auth\LoginController@logout');<br>    });<br>}); </pre>



<p>As you can see above, we added the <strong>login </strong>and <strong>register </strong>routes in a group protected by <strong>api</strong> middleware in order to call <strong>CreateFreshApiToken</strong> after the user login.<br>Profile and logout routes are set under <code>auth:api</code> to be protected by Passport API authentication.</p>



<h2>Some more tweaks</h2>



<p>Cookie&#8217;s lifetime can be set in <code>config\session.php</code> :</p>



<pre class="wp-block-preformatted"> <br>'lifetime' =&gt; env('SESSION_LIFETIME', 120), // minutes</pre>



<p>If the cookie expires, our client application should be noticed about that in a nice manner. At this moment Passport returns a JSON like this:</p>



<pre class="wp-block-preformatted">{"message":"Unauthenticated.","status_code":500}</pre>



<p>It&#8217;s not the best message you can receive. A 500 error code is usually returned for a server error but in our case there is an Authorization error which is usually reported as 401. So I created a Authenticate class, override the authenticate method and catch that 500 response and forwarded a 401 response code with a custom message:</p>



<pre class="wp-block-preformatted">use Illuminate\Auth\Middleware\Authenticate as Middleware;<br>use Exception;<br><br>class Authenticate extends Middleware<br>{<br><br>    /**<br>     * Determine if the user is logged in to any of the given guards.<br>     *<br>     * @param  \Illuminate\Http\Request  $request<br>     * @param  array  $guards<br>     * @return void<br>     *<br>     * @throws \Illuminate\Auth\AuthenticationException<br>     */<br>    protected function authenticate($request, array $guards)<br>    {<br>        try {<br>            parent::authenticate($request, $guards);<br>        } catch (Exception $e) {<br>            abort(401, 'Unauthorized action.');<br>        }<br>    } <br>}</pre>



<p>To be sure it is active you shall check the <code>app\Http\Kernel.php</code> file to have the right route to your class:</p>



<pre class="wp-block-preformatted"> <br>protected $routeMiddleware = [<br>        'auth' =&gt; \App\Http\Middleware\Authenticate::class,<br>         ...<br>    ]; </pre>



<h1>Final thoughts</h1>



<p>You can craft your own cookie session handling. <br>If you are implementing this in a low risk app you can set a forever cookie. This way, the user will never be logged out. <br>If you are working on something big (eg. a bank software) you can set a low lifetime, let&#8217;s say 15 mins and after this user should login again.<br></p>



<p>You can find the updated code here: <a href="https://github.com/danielcrt/laravel5.7-passport-dingo-api-boilerplate">https://github.com/danielcrt/laravel5.7-passport-dingo-api-boilerplate</a></p>



<p>

If you have any questions or improvements please let us know in comments section.

</p>
<p>The post <a rel="nofollow" href="https://crosstechit.com/blog/2019/01/13/laravel-basic-authentication-with-passport-dingo-api-improvements/">Laravel Basic Authentication with Passport &#038; Dingo API &#8211; Improvements</a> appeared first on <a rel="nofollow" href="https://crosstechit.com/blog">Crosstech IT | Blog</a>.</p>
]]></content:encoded>
					
					<wfw:commentRss>https://crosstechit.com/blog/2019/01/13/laravel-basic-authentication-with-passport-dingo-api-improvements/feed/</wfw:commentRss>
			<slash:comments>0</slash:comments>
		
		
			</item>
		<item>
		<title>Laravel Basic Authentication with Passport &#038; Dingo API &#8211; Setup</title>
		<link>https://crosstechit.com/blog/2019/01/10/laravel-basic-authentication-with-passport-dingo-api/</link>
					<comments>https://crosstechit.com/blog/2019/01/10/laravel-basic-authentication-with-passport-dingo-api/#respond</comments>
		
		<dc:creator><![CDATA[Daniel Isac]]></dc:creator>
		<pubDate>Thu, 10 Jan 2019 08:07:37 +0000</pubDate>
				<category><![CDATA[Back end development]]></category>
		<guid isPermaLink="false">https://crosstechit.com/blog/?p=5</guid>

					<description><![CDATA[<p>Why you might be interested? 1. You might save few hours of your time. 2. You care about your users security so you don't want them to be hacked by a 10yo</p>
<p>The post <a rel="nofollow" href="https://crosstechit.com/blog/2019/01/10/laravel-basic-authentication-with-passport-dingo-api/">Laravel Basic Authentication with Passport &#038; Dingo API &#8211; Setup</a> appeared first on <a rel="nofollow" href="https://crosstechit.com/blog">Crosstech IT | Blog</a>.</p>
]]></description>
										<content:encoded><![CDATA[
<p>Why you might be interested?</p>



<ul><li>You might save few hours of googling </li><li>You <strong>care </strong>about your users so you don&#8217;t want them to be hacked by a 10yo</li></ul>



<h1>Our mission</h1>



<p>Create a secure API boilerplate which can be consumed by any client (web &amp; mobile app)</p>



<h1>Final result</h1>



<p>If you want to skip the process here you can find the result: <a href="https://github.com/danielcrt/laravel5.7-passport-dingo-api-boilerplate">https://github.com/danielcrt/laravel5.7-passport-dingo-api-boilerplate</a></p>



<h1>Let&#8217;s start!</h1>



<p>The setup is inspired by ChristophSchmidl&#8217;s boilerplate available here: <a href="https://github.com/ChristophSchmidl/laravel-5.4-dingo-passport-boilerplate">https://github.com/ChristophSchmidl/laravel-5.4-dingo-passport-boilerplate</a></p>



<p>Install Laravel: <a href="https://laravel.com/docs/5.7/installation#installing-laravel" target="_blank">https://laravel.com/docs/5.7/installation#installing-laravel</a></p>



<p>Add Dingo API to composer.json (find latest version here: https://github.com/dingo/api/releases):</p>



<pre class="wp-block-preformatted">"require": {     <br>    ...     <br>    "dingo/api": "2.0.0-alpha1" <br>}</pre>



<p>Put <code>Dingo\Api\Provider\LaravelServiceProvider::class</code> into the providers array of config/app.php&nbsp;</p>



<p>Run&nbsp;<code>php artisan vendor:publish --provider="Dingo\Api\Provider\LaravelServiceProvider"</code></p>



<p>Put  <code>'DingoApi' =&gt; Dingo\Api\Facade\API::class</code>,&nbsp;<code>'DingoRoute' =&gt; Dingo\Api\Facade\Route::class</code> into aliases array of config/app.php</p>



<p>Update .env file and insert: <br><code>API_PREFIX=api
API_VERSION=v1</code></p>



<p>Install <a href="https://github.com/barryvdh/laravel-cors">CORS</a>. Using this you can handle Cross-Origin Resource Sharing headers and OPTIONS requests.</p>



<p>Run: <code>php artisan vendor:publish --provider="Barryvdh\Cors\ServiceProvider"</code></p>



<p>Make CORS available to all routes. You can change that behaviour by updating&nbsp;<code>app/Http/Kernel.php</code>&nbsp;and put&nbsp;<code>\Barryvdh\Cors\HandleCors::class</code>&nbsp;into your&nbsp;<code>middleware</code> array.</p>



<p>Move the User-model from <code>app</code> into namespace&nbsp;<code>App\Models</code>&nbsp;and adjust all config files (if any) so everything works as before.
<br>In <code>config/auth.php</code> update:</p>



<pre class="wp-block-preformatted">'providers' =&gt; [<br>    'users' =&gt; [<br>        'driver' =&gt; 'eloquent',<br>        'model' =&gt; App\Models\User::class,<br>    ],<br>    ...<br>],</pre>



<p> Install Passport via <code>composer require laravel/passport</code> <br>Register <code>PassportServiceProvider</code> by adding <code>Laravel\Passport\PassportServiceProvider::class</code> to the providers array of <code>config/app.php</code></p>



<p> Run&nbsp;<code>php artisan vendor:publish --tag=passport-migrations</code>&nbsp;to put the default Passport migrations into&nbsp;<code>database/migrations</code>&nbsp;folder.</p>



<p>Run <code>php artisan migrate</code></p>



<h1>Error?!</h1>



<p>If you receive: &#8220;Specified key was too long; max key length is 767 bytes&#8221;</p>



<p>Open <code>app/Providers/AppServiceProvider.php</code> and inside the boot method set a default string length:</p>



<pre class="wp-block-preformatted">use Illuminate\Support\Facades\Schema;<br><br>public function boot() {<br>     Schema::defaultStringLength(191);<br>}</pre>



<h1>We are close</h1>



<p>Run&nbsp;<code>php artisan passport:install</code>&nbsp;This command will create the encryption keys needed to generate secure access tokens. In addition, the command will create &#8220;personal access&#8221; and &#8220;password grant&#8221; clients which will be used to generate access tokens.</p>



<p>Add&nbsp;<code>Laravel\Passport\HasApiTokens</code>&nbsp;to&nbsp;<code>App\Models\User</code></p>



<h1>Final steps</h1>



<p>Thanks to <a href="https://github.com/ChristophSchmidl">ChristophSchmidl</a> we have some nicely crafted controllers and transformers which we will just describe in few words. You can find them on <a href="https://github.com/danielcrt/laravel5.7-passport-dingo-api-boilerplate">github</a>.<br>Under <code>app/Http/Controllers/Api/V1</code> we create a custom Controller named <code><a href="https://github.com/danielcrt/laravel5.7-passport-dingo-api-boilerplate/blob/master/app/Http/Controllers/Api/V1/DingoController.php">DingoController</a></code> which will throw all Laravel exceptions and validation errors to our API&nbsp;responses. You can also find there a <a href="https://github.com/danielcrt/laravel5.7-passport-dingo-api-boilerplate/blob/master/app/Http/Controllers/Api/V1/Auth/LoginController.php">LoginController</a> and a <a href="https://github.com/danielcrt/laravel5.7-passport-dingo-api-boilerplate/blob/master/app/Http/Controllers/Api/V1/Auth/RegisterController.php">RegisterController</a> which validate the input and return the responses.</p>



<p>Under <code>app/Http</code> we have created a folder named <a href="https://github.com/danielcrt/laravel5.7-passport-dingo-api-boilerplate/tree/master/app/Http/Transformers">Transformers</a>. These are meant to convert your Eloquent objects (eg. User) to a custom JSON which is sent in your API response.</p>



<p>In <code>app/Providers</code> We have <a href="https://github.com/danielcrt/laravel5.7-passport-dingo-api-boilerplate/blob/master/app/Providers/DingoExceptionHandlerProvider.php">DingoExceptionHandlerProvider</a> which handles the HTTP errors related to authentication (eg. 401, 403) and <a href="https://github.com/danielcrt/laravel5.7-passport-dingo-api-boilerplate/blob/master/app/Providers/DingoPassportServiceProvider.php">DingoPassportServiceProvider</a> validates the Authorization header.</p>



<p>And finally in <code>routes/api.php</code> you can see some defined routes for Login, Register and Logout.</p>



<h1>You&#8217;re done!</h1>



<p>Thanks for reading by here!</p>



<p>If you have any questions or improvements please let us know in comments section.</p>
<p>The post <a rel="nofollow" href="https://crosstechit.com/blog/2019/01/10/laravel-basic-authentication-with-passport-dingo-api/">Laravel Basic Authentication with Passport &#038; Dingo API &#8211; Setup</a> appeared first on <a rel="nofollow" href="https://crosstechit.com/blog">Crosstech IT | Blog</a>.</p>
]]></content:encoded>
					
					<wfw:commentRss>https://crosstechit.com/blog/2019/01/10/laravel-basic-authentication-with-passport-dingo-api/feed/</wfw:commentRss>
			<slash:comments>0</slash:comments>
		
		
			</item>
	</channel>
</rss>
