In order to understand OAuth2 authentication, you must get familiar with the terminology. Because terms like resource owner are rather vague at first, I use a concert ticket analogy to explain it to you.

A quick overview:

These are the essential players in OAuth2 authentication. They are explained further in the article.

  • resource owner = you (mostly)
  • client = app/website
  • auth server = token creator
  • resource server = data creator (or the server with the data you need, but the data is secured)

Using the concert ticket anology

  1. You (=resource owner) buy a ticket (=token) from a vendor (=auth server).
  2. You tell the vendor which gig you want to see (=scope)
  3. The ticket (=token) is only valid at a certain time, and only to that particular concert
  4. Next, you go to the concert venue (= resource server), and you show your ticket (=token).
  5. Eventually, the security guy (= resource server) checks if your ticket is valid, and lets you in to see the concert (= the data you want).
  • If you forge a ticket, or go with a different ticket, you won’t get access (well, unless you are very inventive).
  • You keep the ticket in your wallet because that’s the safest (=https), you don’t leave it in the middle of the street where a thief can see and steal it (=http)
  • It is likely in some cases that the auth server and the resource server are the same server (like you’d buy a ticket at the venue), but it’s not always the case.

Using computer world analogy

  • In computerworld, you’re on a website or app (=client) and the client needs some data from another server (perhaps it wants your Facebook profile data).
  • You login with your username and password at the auth server (Facebook in this example) and in the background your client will pass a scope, the application name, etc.
  • The clients gets an authorization code and exchanges that for a token.
  • The token can contain encoded info like your name, session-id and other stuff. It can also contain a refresh token.
  • The client then sends the token to the resource server (which in the example is also Facebook)
  • The resource server validates the token.
  • The client gets access to the data of the resource server.

There is no official method within OAuth2 on how to validate the token. Possible methods are a self containted token like JWT (json web token) or a call from the resource server to the authorization server to validate the code.

Refresh token, concert ticket analogy

In some cases the client can also get a refresh token. It is used to prolong the session.

Compare it with a stamp you get when you want to get out and get in again in a concert. People with a stamp can go in and out, without checking your original ticket.

  • It contains less information than the initial access token.
  • The refresh token can be exchanged from the auth server by another access token (depends on the implementation)

Some more on refresh tokens

Refresh tokens:

  • don’t make the original access token valid again. It just requests a new access token.
  • are only called when the access token is not valid anymore.
  • are valid longer than access tokens, how long exactly depends of the configuration of the authorization server, but it’s way longer than the access token, otherwise there would be no point in having refresh tokens.
  • are not connected to access tokens. They do not "refresh" a given access token.
  • are (initially) provided by OAuth providers alongside access tokens in certain circumstances that vary by the provider. Typically you’ll be able to get a refresh token when using the Authorization Code Grant and requesting an "offline" scope.

Refresh tokens:

  • can expire, although their expiration time is usually much longer than access tokens.

  • can become invalid in other ways (for example if your user revokes your OAuth client app’s access) . In this case all your refresh tokens and access tokens for that provider would be invalidated).

  • can’t be used for read/write access to a user’s information. Only access tokens do this. Refresh tokens are only used to get new access tokens, not read data.

  • You do not provide an access token when using the refresh flow. You just send a valid refresh token and you get an access token back.

  • If your refresh token is invalid and you also don’t have a valid access token for a user, you must send them through an OAuth authorization flow again.

Json Web Tokens (JWT) are a means to send json objects between 2 parties. They can be secured with keys, so the receiver can verify the source.

It consists of a concatenation of 3 json-strings that are encoded according to an algorithm.

First part

The first json (up to the first point) is a header with info, such as the algorithm used.

Second part

The second part is the actual data (payload) that is encoded with the algorithm from the header.

Registered claims

The payload may contain registered claims. The claims are only 3 characters long. This was done to keep the data as small as possible.

Examples:

  • iss = the issuer (=the sender)
  • exp = expiration time (seconds), how long the token remains valid
  • aud = audience
  • iat = the timestamp of when the token was created
  • jti = unique identifier of the token
  • sid = session id

Third part

The third part is a mechanism to check whether the data was sent by the correct party (verify signature).

It contains a key that is known by the sender and receiver.

This is important, because if someone else would send a token, or change it, but he does not know the key, then that third-party json will not be correct, and so the recipient can know that fraud has occurred.

However, the third part does not protect the data from being decoded. Even without the third part, the data can be decoded.

Example:

  • At the left side you see the json-web token.
  • At the right side you see the decoded 3 parts.
  • Without the 3rd part (the signature) you can also decode the message, you just can’t verify if it was altered by a malicious party.

example_json_web_token

To try it out by yourself, check the official website of JSON web tokens.

If you locked yourself out of your WordPress account, and you can’t figure a way to log back in (even not with recover password), you can get around it by using the command line.

This will only work if you have ssh access and have installed WP-CLI. WP-CLI is such a handy tool, for instance, to automatically update your WordPress installations, that I would recommend it to everyone.

Once you have installed WP-CLI, enter this command in your WordPress project root folder.

wp user update myuser --user_pass=mypassword

Replace myuser and mypassword by your username and password.

Remember that it’s unsafe to enters passwords in plain text through the command line. It is for example tractable with the history command. Once you did this, login to WordPress and change your password the normal way.

Testing with Lorem Ipsum texts is a still a common practise for testing designs and code, certainly in early stages.

Yet, Lorem Ipsum texts has the following downsides:

  • Latin has ñò àççénts or $þ€cial characters. Anything for other non-English languages will not cover your tests.
  • The text also contains no apostrophes. SQL injections won’t be covered in your tests.
  • Latin has fairly short words. Your design may look different if you inject a long (Dutch) word, such as “havenpolitiecommisariaat”.
  • Your typical Lorem Ipsum contains no formatting, no bold or colored texts. What if your customer pushes in the old <font> tag?

But most important of all: it’s not real data. It’s a lie you’re telling yourself.

Users will never inject “Lorem ipsum dolor sit amet” into any field. Your final design won’t look like a Latin course. Therefore, my advise: use as much real data as possible.

The same goes for names. People are not called “John Doe” or “Foo Bar”, some are called “Frederiçus D’Ollande”. A complex name, or better, a list of real complex names, can give much faster insight in how good your code or design is.

I feel some developers expect their users to enter simple, predictable and correct data, while in reality users dump just about any garbage they can find into your controllers. And Lorem Ipsum is not a good preparation for that.

If you don’t have any real customer data, then use a different text than Lorem Ipsum. Find some public domain ebooks, preferably with long words, accents and strange characters. Maybe something Icelandic would be good.

Another example of why real data, or having a sense of real data is very important, even from early on. I worked once with a customer who could add colors to a CMS, colors that would be attributes for products. On top of that, there needed to be a faceted search, so users could filter on those colors. You’d think they’d add 50 colors, 100 maybe, but certainly not more than 500. Well, they provided us the list with colors. It turned out to be more than 10.000! This has so much implications for the import, the data structure, and most importantly the faceted search. So, again: real data is important. For a designer, a developer, and in the end, it matters the most for the customer.

Hi there! After long absence I will reboot this blog. All articles stay here, and I’m writing new ones.

Some updates

At first, this website is now on https. Quite a shame this wasn’t the case yet. I was surprised what a walk in the park this was, with the Certbot tool and Let’s Encrypt. I reserved like an hour or 2 to switch, but it was done is less than 10 minutes. You basically install the program, run a single command, answer some question, and badaboum, your site is in https!

Adapting my posts content to https worked pretty well with the Search And Replace plug-in for WordPress.

Updating WordPress to the latest version works like a charm with the WP-CLI plugin. No hassle, no errors.

wp plugin update --all
wp core update

My cat that has always been features on this blog has sadly disappeared some years ago. One day it didn’t return home. Some months later, I got a new cat from the asylum, named Havana. A lazy, yet dominant and social cat. I’ll post a picture of her later.

The past years I worked mainly in Magento, Pimcore and did I some Raspberry Pi development in my free time. Expect more posts about those subjects.

I’m currently reading a -very- interesting book about working as a software developer. It’s called: Soft Skills: The software developer’s life manual. It’s one of these books I wish I had read 10 years ago.

I also need a new picture for on top. Boy, that’s a boring picture right now 🙂

That’s it for now.

Robin

If you use the debugger in PHPStorm, there will be browser icons in the top right corner of the code editor. I found these distracting and unnecessary.

To remove them:

  • Go to menu File > Settings > Tools > Web Browsers
  • Uncheck “Show browser popup in the editor”
  • Click “Ok”
  • Published:December 19th, 2015
  • Category:Firefox
  • 1 Comment

*sigh* Firefox, it’s like every update I love you a little less. You used to be this technically advanced lightweight browser that showed Microsoft. But ever since Chrome got popular, you’re just running behind whatever the guys at Google are implementing.

Problem

So now Mozilla removed the browser.search.showOneOffButtons option that restored the classic search bar. That “classic” search bar was one of the main reasons why I liked Firefox and this new thing is just a failure.

When you enter a search query, you can’t see which search engine is selected:

firefox_what

Am I searching through Google, Youtube, Wikipedia? I have no idea, it only displays the hourglass icon. In order to know which search engine is selected, I have to click on it.

firefox_search

Then I have to click on the icon of the search engine, which means I need to know which icon is which site, because the name of the site is not displayed (except when I hover it, but that causes an unnecessary delay in my workflow).

Though the new search bar is not as bad as Ubuntu’s Unity or Window’s Metro, I can’t understand why software companies simply don’t keep what uses like and improve what they complain about.

Solution

The only way to have the old search bar back is to install the Classic Theme Restorer extension. Yes, you have to install an extension to get basic functionality.

You must configure the extension in order for it to work. Go to the preferences (about:addons > “Preferences” button), click “General UI (1)” and check “Old search”.

classic_theme_restorer

If you want to keep everything else the way was, uncheck all the checkboxes in the all tabs and set “Tabs (1)” to “Curved tabs (Firefox default)”.

Screenshot-4

Now the question is how long this extension will continue to work, because every Firefox update means that some extensions will stop working.

And now back to Chrome.

  • Published:September 18th, 2015
  • Category:Lavarel4

If you want to match an entire word in a route pattern for Laravel 4, use the underneath snippet.

Route::pattern('my_word_pattern', '^myword$');
Route::get('{my_word_pattern}/...

I spent a crazy amount of time on figuring out how to validate form arrays in Laravel. There is some official documentation, but like most official documentation of Laravel, it only covers the bare minimum of what you need to know. This is an advanced article on how to validate form arrays in Laravel.

I have a form where people can enter 3 iban and bic numbers (these are EU bankaccounts). That makes 3 pairs of textboxes:

  • iban[]
  • bic[]
  • iban[]
  • bic[]
  • iban[]
  • bic[]

… and other form elements …

My desired form validation rules:

  • Maximum 3 couples of iban & bic can be submitted
  • The user is not obligated to fill in any of the iban & bic numbers.
  • When an IBAN is filled in, the user also needs to fill in the BIC.
  • The IBAN and BIC can only contain alphanumerics and spaces.

Out of the box, Laravel can validate form arrays with the dot character.

The next form rule will work out of the box:

'iban.0' => 'required'

In your views, you can check for the error:

$errors->has('iban.0')

The same goes for the second iban:

'iban.1' => 'required`'

But I don’t need that in my setup. The fields are not mandatory.

To check for alpha+num+spaces you have to create a new ValidationRule. The most decent way is to extend the default Validator class and add your own rules. Then you have to create a service provider that returns the ExtendedProvider. Finally you have to add the serviceprovider to app.php and run composer update.

I’ll walk you through each of the files you have to create:

File: ExtendedValidator.php

The function validateAlphaNumSpaces() will listen to the rule alpha_num_spaces. The three parameters are standard parameters for validate-functions. We only use $value and not the other parameters because this is a simple rule. $value is what the user entered in the form field.

The function checks $value with a regex and returns true if it matches.

File: ExtendedServiceProvider.php:

app->validator->resolver(function($translator, $data, $rules, $messages)
         {
             return new ExtendedValidator($translator, $data, $rules, $messages);
         });
     }
 }

Then in app.php, at the end of the providers array:

<pre class="wp-block-syntaxhighlighter-code">'providers' => array(
 ...
 'App\Services\Validators\ExtendedValidatorServiceProvider',
 ),

Run composer dump-autoload -o The -o is for faster performance.

Now we can change the validation rule to:

<pre class="wp-block-syntaxhighlighter-code">'iban.0' => 'required|alpha_num_spaces'

Array max size

I want to make sure that a hacker/user can submit no more than 3 iban numbers. There is no boilerplate code for that so we have to write it ourselves. I continue with the files I created in the previous steps.

In ExtendedValidator.php:

public function validateArraySize($attribute, $value, $parameters){
    $data = array_get($this->data, $attribute);`
    if (!is_array($data)) {
        return true;
    } else {
        $sizeIsOk = (count($data) <= $parameters[0];)
        return $sizeIsOk;
    }
}

This function will listen to the rule array_size. You can use it like this:

'iban' => 'array|array_size:3'

This makes sure that the iban field is an array, and can only contain 3 keys.

To create a nice error message to the user, go to app/lang/en/validation.php

app/lang/en/validation.php

return array(
    'array_size'     => 'You can only enter :array_size different values for :attribute.');

You might wonder how the system knows what :array_size is. Well, it doesn’t. We have to tell Laravel what it is.

Go to ExtendedValidator.php

Enter the following:

/**
    * Replace all place-holders for the min rule.
    *
    * @param  string  $message
    * @param  string  $attribute
    * @param  string  $rule
    * @param  array   $parameters
    * @return string
    */
   protected function replaceArraySize($message, $attribute, $rule, $parameters)  {
       return str_replace(':array_size',  $parameters[0],  $message);
   }

This will replace :array_size with the value you entered in the validation rules.

Almost there.

I also want the following condition: if a user enters an iban, he also has to enter a bic.

You can use this out of the box working rule:

'bic.0' => 'alpha_num_spaces|required_with:iban.0',

required_if with form arrays

For the real daredevils: what if the user first has to check a box before he can enter the iban?

To be able to do this we need a multi_required_if that we have to write ourselves. I based it loosely on validationRequiredIf from Validator.php

In ExtendedValidator.php

/**
 * Required if element corresponds in an array
 */
protected function validateMultiRequiredIf($attribute, $value, $parameters){
    $this->requireParameterCount(2, $parameters, 'multi_required_if');
    $parameterKey = substr($parameters[0], strpos($parameters[0], '.') + 1);
    $parameterName = substr($parameters[0], 0, strpos($parameters[0], '.'));
    $data = array_get($this->data, $parameterName);
    if(!is_array($data)){
        return true;
    }
    $values = array_slice($parameters, 1);
    if (in_array($data[$parameterKey], $values))
    {
        $isEmpty = $this->validateRequired($attribute, $value[$parameterKey]);
        return $isEmpty;
    }
    return true;
}

You can use it like this:

'iban.0' => 'multi_required_if:checkbox-element.0,1',

This means that the first iban textfield (iban.0) must be filled id when the first checkbox element (checkbox-element.0) is checked.

At last, you have to make a rule for each form array element. Too bad I didn’t have the time to figure out how the validation rules can work on each element in the array. With the last example, you have to write a rule for each array element:

'iban.0' => 'multi_required_if:checkbox-element.0,1',
'iban.1' => 'multi_required_if:checkbox-element.1,1',
'iban.2' => 'multi_required_if:checkbox-element.2,1',

Sometimes it can be desirable to remove a database column that hosts a foreign key relationship (eg: in reverse migration scripts). It can be a bit of a hassle to get that done.

Here’s how to do it:

1) Log in to your database and lookup the name of the foreign key relationship. If you use phpmyadmin, go to the table, click the “Structure” tab, click the link “Relation View” and wait a few seconds for it to load. Search for the field “Constraint name”. In my example this is: “contribution_copyright_id_foreign”

2) Go to the Laravel migration script (or create one). The trick is to first drop the foreign key relationship and then drop the column.

public function down()
{
Schema::table('contribution', function(Blueprint $table){
$table->dropForeign('contribution_copyright_id_foreign');
$table->dropColumn('copyright_id');
});

If you want to remove a table where a foreign key is present, you also first have to drop the foreign key relationship.

Next Page »

Wordpress.org clearPaper by CreativeBits.it Copyright © 2012-2019 Robin Brackez. All rights reserved. By visiting this site you agree to accept cookies that are purely used to check how many visitors I have. Theme by: creativebits. Custom adaptations by Robin Brackez.