Social authentication with Laravel Socialite

https://www.hibit.dev/images/social/2022/preview/laravel_socialite.png

Social login is now an essential part of any site which performs user authentication. It does not need to replace the standard form based authentication, quite the contrary, social login complements it. Login with social accounts is a straightforward process and it saves the users a lot of time, as they won’t need to fill the whole form. They just sign up with their social account and they can log into the website with just a few clicks.

OAuth is an open standard protocol for access delegation, commonly used as a way for internet users to grant websites or applications access to their information on other websites but without giving them the passwords. Laravel Socialite package provides a simple, fluent interface to authenticate with OAuth providers. It currently supports authentication via Facebook, Twitter, LinkedIn, Google, GitHub, GitLab and Bitbucket.

Prerequisites

A Laravel project is required to use Socialite package. Take a look on how to create your first Laravel project, if you don’t have any yet. The latest stable and compatible version is recommended to be installed for the both: framework and PHP.

Additionally, we recommend reading about the OAuth 2.0 protocol: understanding OAuth 2.0 and how it works.

Installation

To get started with Socialite, use the Composer package manager to add the package to your project’s dependencies:

composer require laravel/socialite

Registering with OAuth providers

Before implementing and using Socialite, you will need to generate credentials for OAuth providers your application want to operate with. Typically, these credentials may be retrieved by creating a developer application within the service you will be authenticating with.

Detailed explanation on how to retrieve credentials for different services can be found below:

Configuring your application

Credentials generated in the step above should be placed in your application’s config/services.php configuration file. Depending on the providers you want to use, credentials are defined with one of the following keys : facebook, twitter-oauth-2, linkedin, google, github, gitlab or bitbucket.

'google' => [
'client_id' => env('OAUTH_GOOGLE_CLIENT_ID'),
'client_secret' => env('OAUTH_GOOGLE_CLIENT_SECRET'),
'redirect' => 'https://your-domain.com/callback-url',
],

That’s an example of definition of Google OAuth credentials in config/services.php configuration file.

Define environment variables

Environment variables provide another way to specify configuration options and credentials. As you can see, the definition of credentials in config/services.php is using environment variables and it means that you need to define them in your .env file:

OAUTH_GOOGLE_CLIENT_ID=your_google_client_id
OAUTH_GOOGLE_CLIENT_SECRET=your_google_client_secret

Feel free to use any variable name and replace values with credentials generated within the OAuth provider.

Specify Socialite routes

Any provider defined with Socialite need two routes:

Route::get('/google', 'OAuthGoogleController@redirect')->name('oauth.google');
Route::get('/google-callback', 'OAuthGoogleController@callback');

Define both routes in the project routes/web.php file with desired options (prefixes, names, middleware, etc…).

Preparing your database

Once the user has been retrieved from the OAuth provider, you may determine if the user exists in your application’s database and authenticate the user. If the user does not exist in your application’s database, you will typically create a new record in your database to represent the user. OAuth callbacks include a string that represents a unique identifier for the user on the OAuth platform.

In case of using MySQL database, a new varchar column can be added to the users table. It will contain OAuth identifier and help us to find the user in future queries, i.e., facebook_id, twitter_id, google_id, etc... You may want to save user token, refresh token and token expiration date too. Everything depends on the use case.

Implementing Socialite controller

We’ve previously configured two routes for the OAuth provider and both routes are pointing to the same controller. Socialite helps to abstract the complicated OAuth logic making the implementation quite standard, with slight differences for different providers. A template has been defined and it can be used for all available OAuth2 providers changing the class constant and completing TODOs that depends on your application.

<?php namespace App\\Controllers;

use Illuminate\\Http\\Request;
use Illuminate\\Http\\RedirectResponse;

use Laravel\\Socialite\\Facades\\Socialite;
use Laravel\\Socialite\\Two\\User as SocialUser;

class OAuthGoogleController
{
// facebook, twitter twitter-oauth-2, linkedin, google, github, gitlab, bitbucket
const OAUTH_PROVIDER = 'google';

public function redirect(): RedirectResponse
{
return Socialite::driver(self::OAUTH_PROVIDER)->redirect();
}

public function callback(Request $request): RedirectResponse
{
/** @var SocialUser $socialUser */
$socialUser = Socialite::driver(self::OAUTH_PROVIDER)->user();

if ($socialUser->getEmail() === null) {
// TODO Missing email, redirect to manual registration page
}

try {
// TODO Get user from database using ID or email address
// TODO Throw UserNotFoundException if user does not exist
// TODO Update user attributes (if needed)
} catch (UserNotFoundException $e) {
// TODO Create new user record in the database
} finally {
// TODO Authenticate existing or new created user in the system
}

// TODO redirect authenticated user
}
}

First let’s check what kind of information social user variable contains:

$socialUser->getId() // User identifier from OAuth provider
$socialUser->getNickname() // User nickname or null
$socialUser->getName() // User name concatenated with surname in some cases
$socialUser->getEmail() // User email address
$socialUser->getAvatar() // User avatar URL

Additional information can be gathered for Google OAuth users:

$socialUser['email_verified'] // User email verification flag (boolean)

Generally, for OAuth2 providers, token information is available too:

$socialUser->token
$socialUser->refreshToken
$socialUser->expiresIn

As you can see it’s very easy to setup any provider and the code for all of them is quite similar.

Conclusion

Login with social accounts is a straightforward process and at the same time it improves the user experience. Officially Socialite plugin only supports popular platforms for OAuth but you can find non-official implementations of other platforms too.

Laravel News Links

Midwest Universities Unite To Support US Chip Industry Revival

An anonymous reader quotes a report from The Register: A dozen US midwestern research colleges and universities have signed up to a project intended to bolster the semiconductor and microelectronics industries with combined research and education to ensure work for their students in high-tech industries. The "Midwest Regional Network to Address National Needs in Semiconductor and Microelectronics" consists of a dozen institutions, made up of eight from Ohio, two from Michigan, and two from Indiana. Their stated aim is to support the onshoring efforts of the US semiconductor industry by addressing the need for research and a skilled workforce.
According to Wright State University, the network was formed in response to Intel’s announcement that it planned to build two chip factories near Columbus, Ohio, and followed a two-day workshop in April hosted by the state. […] However, the university network was also formed to help address the broader national effort to regain American leadership in semiconductors and microelectronics, or at least bring some of it back onshore and make the US less reliant on supplies of chips manufactured abroad.
The president of each institution has signed a memorandum of understanding to form the network, and the expectation is that the group will expand to include more than these dozen initial members. The intention is that the institutions taking part will be able to make use of each other’s existing research, learning programs, capabilities, and expertise in order to boost their collective ability to support the semiconductor and microelectronics industry ecosystems. Challenges for the network include developing mechanisms to connect existing research, and training assets across the region, and developing a common information sharing platform to make it easier to identify opportunities for joint programming and research across the network. The institutions involved in the network include: Wright State University, Columbus State Community College, Lorain County Community College, Michigan State University, Ohio State University, Purdue University, Sinclair Community College, University of Cincinnati, University of Dayton, University of Michigan, and the University of Notre Dame, Indiana.
Further reading: Biden Signs China Competition Bill To Boost US Chipmakers


Read more of this story at Slashdot.

Slashdot

Satisfying Slicing Machine

https://theawesomer.com/photos/2022/08/satisfying_cucumber_slicing_t.jpg

Satisfying Slicing Machine

Link

We’re fascinated by the variety of machines you find in factories. This particular device is fairly simple – a couple of rollers and a spinning blade. But it’s the stroboscopic optical illusion that occurs when it spins up to speed that makes it so satisfying to watch. Somebody needs to turn this into an endless loop.

The Awesomer

Making 1000 Custom Knives

https://theawesomer.com/photos/2022/08/making_1000_custom_knives_t.jpg

Making 1000 Custom Knives

Link

There’s a big difference between making a single custom knife and cranking out a thousand. Maker Matt Estlea takes us through the painstaking and repetitive 12-step build process for each of his wood-handled marking knives. He put the knives up for sale on his website, but they appear to be out of stock at present.

The Awesomer

MySQL WHERE Clause Inequality Comparison Operators

https://i0.wp.com/joshuaotwell.com/wp-content/uploads/2022/07/decision-g4a5740941_640.jpg?w=640&ssl=1

Just as you want to filter the rows of data returned in a SELECT query with the equality comparison operator (=), you can also create a conditional filter to test if 2 values are not equal to one another. Learn more in the following article.

The Newsletter for PHP and MySQL Developers

Receive a copy of my ebook, “10 MySQL Tips For Everyone”, absolutely free when you subscribe to the OpenLampTech newsletter.

In MySQL, there are 2 ‘not equal to’ comparison operators available:

  • <>
  • !=

📰 Get your brand, product, or service the attention it needs with affordable classified ad placement in the OpenLampTech newsletter. Thank you for your support!


Even though both of these comparison operators mean the same thing and work exactly the same, I will use the <> operator as it is supported by the SQL Standard and is used in other SQL dialects as well.

Typically, the inequality conditional comparison filter will look like this:

some_column <> some_value

Similar Reading

Enjoy any of these MySQL beginner-friendly articles:

Like what you have read? See anything incorrect? Please comment below and thank you for reading!!!

A Call To Action!

Thank you for taking the time to read this post. I truly hope you discovered something interesting and enlightening. Please share your findings here, with someone else you know who would get the same value out of it as well.

Visit the Portfolio-Projects page to see blog posts/technical writing I have completed for clients.

To receive email notifications (Never Spam) from this blog (“Digital Owl’s Prose”) for the latest blog posts as they are published, please subscribe (of your own volition) by clicking the ‘Click To Subscribe!’ button in the sidebar on the homepage! (Feel free at any time to review the Digital Owl’s Prose Privacy Policy Page for any questions you may have about: email updates, opt-in, opt-out, contact forms, etc…)

Be sure and visit the “Best Of” page for a collection of my best blog posts.


Josh Otwell has a passion to study and grow as a SQL Developer and blogger. Other favorite activities find him with his nose buried in a good book, article, or the Linux command line. Among those, he shares a love of tabletop RPG games, reading fantasy novels, and spending time with his wife and two daughters.

Disclaimer: The examples presented in this post are hypothetical ideas of how to achieve similar types of results. They are not the utmost best solution(s). The majority, if not all, of the examples provided, are performed on a personal development/learning workstation environment and should not be considered production quality or ready. Your particular goals and needs may vary. Use those practices that best benefit your needs and goals. Opinions are my own.

How can I help you?

Disclosure: Some of the services and product links in this post are affiliate links. At no additional cost to you, should you make a purchase by clicking through one of them, I will receive a commission.

The Newsletter for PHP and MySQL Developers

Receive a copy of my ebook, “10 MySQL Tips For Everyone”, absolutely free when you subscribe to the OpenLampTech newsletter.


📰 Get your brand, product, or service the attention it needs with affordable classified ad placement in the OpenLampTech newsletter. Thank you for your support!


The post MySQL WHERE Clause Inequality Comparison Operators appeared first on Digital Owl’s Prose.

Planet MySQL

Top Laravel & PHP Blogs You Should Be Following

https://ashallendesign.ams3.digitaloceanspaces.com/public/blog/96/top-laravel-and-php-blogs.png

If you’re a web developer, you’ll likely know that the Laravel ecosystem is always changing. Thankfully, there’s a huge amount of content that is written that help us keep up to date with what’s going on, thanks to the amazing community. There’s also a constant stream of guides and tutorials that we can use to improve as developers.

So, I thought that I’d put together a short post with the blogs that I’d recommend every Laravel and PHP web developer to follow. If you’re interested in seeing the top Twitter accounts that I think every Laravel developer should be following, you can also check out my “Top Laravel Twitter Accounts to Follow” post.

Are there any other blogs that you would recommend? If so, let me know in the comments so that I can add it to the list.

In no particular order, here’s a list of the top 35 blogs that I think every Laravel and PHP developer should check out:




































Laravel News Links