Braindead simple social login with Laravel and Eloquent.

Overview

Important: This package is not actively maintained. For bug fixes and new features, please fork.

Eloquent OAuth

This Project Has Been Deprecated. Code Climate Scrutinizer Code Quality Build Status

Eloquent OAuth is a package for Laravel designed to make authentication against various OAuth providers ridiculously brain-dead simple. Specify your client IDs and secrets in a config file, run a migration and after that it's just two method calls and you have OAuth integration.

Video Walkthrough

Screenshot

Basic example

// Redirect to Facebook for authorization
Route::get('facebook/authorize', function() {
    return OAuth::authorize('facebook');
});

// Facebook redirects here after authorization
Route::get('facebook/login', function() {
    
    // Automatically log in existing users
    // or create a new user if necessary.
    OAuth::login('facebook');

    // Current user is now available via Auth facade
    $user = Auth::user();

    return Redirect::intended();
});

Supported Providers

  • Facebook
  • GitHub
  • Google
  • LinkedIn
  • Instagram
  • SoundCloud

Feel free to open an issue if you would like support for a particular provider, or even better, submit a pull request.

Installation

Check the appropriate wrapper package for installation instructions for your version of Laravel.

Usage

Authentication against an OAuth provider is a multi-step process, but I have tried to simplify it as much as possible.

Authorizing with the provider

First you will need to define the authorization route. This is the route that your "Login" button will point to, and this route redirects the user to the provider's domain to authorize your app. After authorization, the provider will redirect the user back to your second route, which handles the rest of the authentication process.

To authorize the user, simply return the OAuth::authorize() method directly from the route.

Route::get('facebook/authorize', function() {
    return OAuth::authorize('facebook');
});

Authenticating within your app

Next you need to define a route for authenticating against your app with the details returned by the provider.

For basic cases, you can simply call OAuth::login() with the provider name you are authenticating with. If the user rejected your application, this method will throw an ApplicationRejectedException which you can catch and handle as necessary.

The login method will create a new user if necessary, or update an existing user if they have already used your application before.

Once the login method succeeds, the user will be authenticated and available via Auth::user() just like if they had logged in through your application normally.

use SocialNorm\Exceptions\ApplicationRejectedException;
use SocialNorm\Exceptions\InvalidAuthorizationCodeException;

Route::get('facebook/login', function() {
    try {
        OAuth::login('facebook');
    } catch (ApplicationRejectedException $e) {
        // User rejected application
    } catch (InvalidAuthorizationCodeException $e) {
        // Authorization was attempted with invalid
        // code,likely forgery attempt
    }

    // Current user is now available via Auth facade
    $user = Auth::user();

    return Redirect::intended();
});

If you need to do anything with the newly created user, you can pass an optional closure as the second argument to the login method. This closure will receive the $user instance and a SocialNorm\User object that contains basic information from the OAuth provider, including:

  • id
  • nickname
  • full_name
  • avatar
  • email
  • access_token
OAuth::login('facebook', function($user, $details) {
    $user->nickname = $details->nickname;
    $user->name = $details->full_name;
    $user->profile_image = $details->avatar;
    $user->save();
});

Note: The Instagram and Soundcloud APIs do not allow you to retrieve the user's email address, so unfortunately that field will always be null for those provider.

Advanced: Storing additional data

Remember: One of the goals of the Eloquent OAuth package is to normalize the data received across all supported providers, so that you can count on those specific data items (explained above) being available in the $details object.

But, each provider offers its own sets of additional data. If you need to access or store additional data beyond the basics of what Eloquent OAuth's default ProviderUserDetails object supplies, you need to do two things:

  1. Request it from the provider, by extending its scope:

    Say for example we want to collect the user's gender when they login using Facebook.

    In the config/eloquent-oauth.php file, set the [scope] in the facebook provider section to include the public_profile scope, like this:

       'scope' => ['email', 'public_profile'],

For available scopes with each provider, consult that provider's API documentation.

NOTE: By increasing the scope you will be asking the user to grant access to additional information. They will be informed of the scopes you're requesting. If you ask for too much unnecessary data, they may refuse. So exercise restraint when requesting additional scopes.

  1. Now where you do your OAuth::login, store the to your $user object by accessing the $details->raw()['KEY'] data:
       OAuth::login('facebook', function($user, $details) (
           $user->gender = $details->raw()['gender']; // Or whatever the key is
           $user->save();
       });

TIP: You can see what the available keys are by testing with dd($details->raw()); inside that same closure.

Comments
  • Changed InstallCommand file to properly publish migration file.

    Changed InstallCommand file to properly publish migration file.

    Problem : As the create_oauth_identities_table as original file and when it is published both original and published file are colliding an results to error. So make the file as stub and then use laravel for migrating it.

    opened by knvpk 16
  • Unable to register provider later / externally

    Unable to register provider later / externally

    We have our own authentication package which is basically a wrapper around this package. This was done in order to make it easier to work with, since only our package (and config) needed to be there and it would supply the underlying eloquent-oauth with appropriate configurations. It also adds some additional routes, views (403 etc) and the related model. All in one package is very convenient.

    With Laravel 4(.2) this was working just fine. However, with the dev-laravel-5 version this doesn't work anymore :(

    In our serviceprovider we registered our provider as such:

    \AdamWathan\EloquentOAuth\Facades\OAuth::registerProvider('CustomAuth', $this->app->make('CustomAuthProvider'));
    

    This was working fine with L4. But with L5 this doesn't appear to be possible (anymore) since we're getting an exception stating:

    Invalid argument supplied for foreach() 
    

    This originates from /vagrant/vendor/adamwathan/eloquent-oauth/src/EloquentOAuthServiceProvider.php:

         return $oauth;
        });
        }
        protected function registerProviders($oauth)
        {
        $providerAliases = $this->app['config']['eloquent-oauth.providers'];
        foreach ($providerAliases as $alias => $config) {
        if(isset($this->providerLookup[$alias])) {
        $providerClass = $this->providerLookup[$alias];
    

    Has anything changed in that regard?

    opened by syphernl 10
  • Accessing data from additional scopes

    Accessing data from additional scopes

    Hey Adam,

    Thanks a lot for the package, it really makes Oauth easy true Laravel style!

    I do however have a question, in regards to using the package. When i provide additional scopes for a provider, in my example Facebook, the returned user details that i access through the login callback doesn't include the extra details that i requested permission for.

    How would i go about retrieving these extra details, e.g. the birthday of a user. Am i missing something here, or do i need to create a custom provider? And even so, how would i access the data?

    opened by cbojer 9
  • Username / nickname not saved in database

    Username / nickname not saved in database

    After a successful login an entry is inserted into oauth_identities and users. However, the username field remains empty. I have tried renaming "username" to "nickname" in the table definition but this didn't have any result.

    This is being returned by the userdata service and the field is correctly configured in the provider

    opened by syphernl 9
  • Oauth with Facebook depreciated

    Oauth with Facebook depreciated

    Hi, Thanks for your package.

    When I'm using your package with the Facebook API I'm getting a warning "You must upgrade this app to Graph API v2.x v1.0 will be deprecated on April 30, 2015"

    I'm using the version for Laravel 4.

    Are you going to update your package for the new API from Facebook ?

    Thanks.

    opened by Metrakit 8
  • No rows are inserted in oauth_identities

    No rows are inserted in oauth_identities

    I'm using the package in laravel 5 and I'm facing an issue. I manage to be redirected to Facebook, and being redirected back to my app, and using the closure I can see the details of the user, but I cannot login normally because no info is added to the table oauth_identities.

    If I manually populate a row with the required info, all the new login attepts work properly..

    Is this a normal behaviour because it's something I must manually insert or the package is supposed to do that for me?

    Thanks and sorry if it is a stupid question.

    opened by vgomes 8
  • Custom provider for background sync operations

    Custom provider for background sync operations

    Hi,

    I read your readme. It lists custom provider documentation as well as "stop saving token as its totally single time use"...

    Our need is to integrate with a custom provider with whom we need to get the token once and then the integration link stays on as long as the user decides to unlink. The token will be used for backend syncing of application data to this custom API. So there is no user session going on.

    Have you thought of this kind of use scenario? For us it has been a pain to realize every package out there is strictly for session based auth purposes, with a limited set of big providers, and without clear documentation on how to create custom integrations.

    opened by ux-engineer 8
  • Laravel Session Timeout?

    Laravel Session Timeout?

    I'm experiencing something odd:

    Auth::check() is fine, but when I check Auth::user() it doesn't exist. This happens only after a period of inactivity, which leads me to believe that there is a timeout issue happening somewhere, perhaps on the Github provider?

    opened by mikebronner 7
  • Field 'name' doesn't have a default value

    Field 'name' doesn't have a default value

    Hi,

    I'm getting the following error.

        SQLSTATE[HY000]: General error: 1364 Field 'name' doesn't have a default value (SQL: insert into `users` (`updated_at`, `created_at`) values (2015-03-10 22:46:19, 2015-03-10 22:46:19))
    

    This is the 'simple' code i'm using

    public function authorize()
        {
            return OAuth::authorize('facebook');
        }
    
        public function login()
        {
            try {
                Oauth::login('facebook');
            } catch(ApplicationRejectedException $e) {
                // Add errors if users reject
            } catch(InvalidAuthorizationCodeException $e) {
                // Add errors if csrf
            }
    
            //$user = Auth::user();
            //return Redirect::intended();
        }
    

    Any idea what might be going wrong? Thanks!

    opened by notflip 6
  • Support Guzzle 4.x

    Support Guzzle 4.x

    Could Guzzle 4.x be implemented instead of 3.7? My app uses 4.0 which means there are issues with this particular module.

    In my fork I have made some changes to make use of Guzzle 4.0 (mostly namespace changes) but there are still a few things I haven't yet figured out. The access_token request is different when 4.0 is being used.

    opened by syphernl 6
  • Added functionality to place requests on GitHub API.

    Added functionality to place requests on GitHub API.

    I added in the initial functionality needed to place requests on the GitHub API. This could/should probably be extracted out to the other providers as well. Also, it could probably use some refactoring to be more accessible through the OAuthManager Facade, or something.

    I can then do the following, for example:

        public function index($nickname = null)
        {
            $user = User::whereNickname($nickname)->first();
            $gitHubProvider = OAuth::getProvider('github');
    dd($gitHubProvider->request('/users/' . $nickname . '/gists', $user->gitHubAccessToken));
        }
    

    I think it is important to keep the access token configurable, but could default to the logged in user if left blank. That way I can issue requests on behalf of different users that are authenticated in my system.

    Please let me know what you think. I have implemented it in this rudimentary fashion for now to get up and running, but would be happy to discuss cleaning it up with you, and discuss how you think it should work.

    All the best, ~Mike

    opened by mikebronner 6
  • Authorize more than one provider for one user

    Authorize more than one provider for one user

    Hello,

    Looks like this plugin has been kinda quiet lately but appears to still work great!

    Does this plugin allow for a user (once logged in) to authorize more providers? I would like to have a bit of logic available on the login() method that would allow for a user to authorize a second provider once that user is already logged in on my site.

    opened by KroniK907 1
  • Using Google Oauth behind proxy

    Using Google Oauth behind proxy

    I am facing a few issues especially regarding GuzzleHttp/RingPhp when it comes to Google auth through a company proxy.

    I tried hacking curl by inserting

    curl_setopt($handle, CURLOPT_SSL_VERIFYPEER, false); curl_setopt($handle, CURLOPT_PROXY, '');

    directly in the RingPhp CurlFactory, that used to work then but that seems to be not enough anymore. The initial call seems to succeed but the callback route throws an exception that it cannot fopen(https://accounts.google.com/o/oauth2/token). So I would also need to hack the fopen stream context, could not yet figure out how to do this. But since directly editing vendor files is not at all good practice, is there an easy solution to use eloquent-oauth behind proxy that I maybe missed?

    I am using Laravel 5. Thanks a lot!

    opened by markuskoehler 0
  • Log in by access token

    Log in by access token

    Hello, first of all, thank you for your hard work, this library works wonderfully.

    I would like to ask you, if it's possible to log in / create a user by a valid facebook access token. I'm posting it to my laravel application from a mobile client, and i want to get the user associated with the facebook token and generate another token to use for authenticating my api requests.

    Best, Peter

    opened by petert0th 2
  • Add documentation for

    Add documentation for "Designing your users table"

    See discussions:

    https://github.com/adamwathan/eloquent-oauth/issues/33#issuecomment-75374725 https://github.com/adamwathan/eloquent-oauth-l5/issues/7

    opened by adamwathan 0
Releases(v8.1.0)
Owner
Adam Wathan
Creator of Tailwind CSS, author of Refactoring UI, host of Full Stack Radio.
Adam Wathan
A Laravel 5 package for OAuth Social Login/Register implementation using Laravel socialite and (optionally) AdminLTE Laravel package

laravel-social A Laravel 5 package for OAuth Social Login/Register implementation using Laravel socialite and (optionally) AdminLTE Laravel package. I

Sergi Tur Badenas 42 Nov 29, 2022
Login Social and product store

Run Stores Fake Marvel store This is a fake Marvel Store, here you can find a list of all the Marvel characters and simulate a shopping of its product

Ricardo Rito Anguiano 1 Jan 22, 2022
It's authorization form, login button handler and login to your personal account, logout button

Authorization-form It's authorization form, login button handler and login to your personal account, logout button Each file is: header.php - html-fil

Galina 2 Nov 2, 2021
Laravel Auth is a Complete Build of Laravel 8 with Email Registration Verification, Social Authentication, User Roles and Permissions, User Profiles, and Admin restricted user management system.

Laravel Auth is a Complete Build of Laravel 8 with Email Registration Verification, Social Authentication, User Roles and Permissions, User Profiles, and Admin restricted user management system. Built on Bootstrap 4.

Jeremy Kenedy 2.8k Dec 31, 2022
How to create a simple auth system with login and signup functionalities in Code-igniter 4.

Codeigniter 4 Authentication Login and Registration Example Checkout the step-by-step tutorial on: Codeigniter 4 Authentication Login and Registration

Digamber Rawat 7 Jan 9, 2023
A simple, safe magic login link generator for Laravel

Laravel Passwordless Login A simple, safe magic login link generator for Laravel This package provides a temporary signed route that logs in a user. W

gro.sv 689 Dec 25, 2022
Social OAuth Authentication for Laravel 5. drivers: facebook, github, google, linkedin, weibo, qq, wechat and douban

Social OAuth Authentication for Laravel 5. drivers: facebook, github, google, linkedin, weibo, qq, wechat and douban

安正超 330 Nov 14, 2022
💝The Plus (ThinkSNS+) is a powerful, easy-to-develop social system built with Laravel.

Plus (ThinkSNS+) Plus (ThinkSNS+) 是使用 Laravel 框架开发;一个功能强大、易于开发和动态拓展的社交系统。Plus 是遵循 PSR 规范 代码统一,并功能块松耦合。你安装完成 Plus 并不意味着已经成功安装了所有功能,因为 Plus 使用 模块化 的 原则,

Slim Kit 2.2k Jan 3, 2023
:atom: Social (OAuth1\OAuth2\OpenID\OpenIDConnect) sign with PHP :shipit:

SocialConnect Auth Getting Started :: Documentation :: Demo Open source social sign on PHP. Connect your application(s) with social network(s). Code e

SocialConnect 518 Dec 28, 2022
:atom: Social (OAuth1\OAuth2\OpenID\OpenIDConnect) sign with PHP :shipit:

SocialConnect Auth Getting Started :: Documentation :: Demo Open source social sign on PHP. Connect your application(s) with social network(s). Code e

SocialConnect 458 Apr 1, 2021
A wrapper around Spatie’s Browsershot for managing social share images (OGP, Twitter etc.)

Very short description of the package This package allows you to create dynamic social sharing images in your Laravel apps. It uses Spatie’s Browsersh

Richard Le Poidevin 4 Dec 25, 2021
Discuz!ML is a multilingual version of Discuz!X, social network engine from Tencent Cloud

Discuz! ML (MultiLingual Discuz) Introduction Discuz!ML is a multilingual version of Discuz!X, social network engine from Tencent Cloud Related Sites

Valery Votintsev 3 Dec 7, 2022
Social (OAuth1\OAuth2\OpenID\OpenIDConnect) sign with PHP

Open source social sign on PHP. Connect your application(s) with social network(s).

SocialConnect 517 Dec 11, 2022
User registration and login form with validations and escapes for total security made with PHP.

Login and Sign Up with PHP User registration and login form with validations and escapes for total security made with PHP. Validations Required fields

Alexander Pérez 2 Jan 26, 2022
A complete Login and Register page using a Mysql Database and php

Login With Mysql A complete Login and Register page using a Mysql Database ?? Built with ⚙️ ?? Description A login with Frontend, Backend and Database

Marc Medrano 1 Nov 5, 2021
A whitelabeled and modernized wp-login.php

Modern Login Here lives a simple mu-plugin to whitelabel and modernize wp-login.php. No admin panels, no bloat – just a simple filter to optionally cu

Brandon 65 Dec 22, 2022
PHP Login and Registration Script

dj_login PHP Login and Registration Script To function this script requires you put your MySQL info into both login.php and register.php, and have the

djsland.com 1 Nov 16, 2021
This extension expands WSOAuth extension and provide a EveOnline SSO login method

This extension expands WSOAuth extension and provide a EveOnline SSO login method

Raze Soldier 1 Nov 15, 2021
Helps you securely setup a master password and login into user accounts with it.

?? Make your Login form smart in a minute! Built with ❤️ for every smart laravel developer Helps you set a master password in .env file and login into

Iman 341 Jan 1, 2023