Cliente OAuth2 para Gov.br

Overview

Cliente OAuth2 para Gov.br

CI Build codecov Scrutinizer Code Quality Latest Version Software License

Este pacote fornece suporte OAuth 2.0 para Gov.br usando a biblioteca cliente do League PHP.

Requisitos

Versões suportadas do PHP:

  • PHP 8.0
  • PHP 7.4
  • PHP 7.3
  • PHP 7.2
  • PHP 7.1

Instalação

Via composer:

composer brenoroosevelt/oauth2-govbr 

Exemplos de Uso

Criando uma instância do provider para GovBr em ambiente de produção:

use BrenoRoosevelt\OAuth2\Client\GovBr;

$govBr = new GovBr([
    'clientId'     => 'XXXXXXXX', // Client ID fornecido pelo GovBr
    'clientSecret' => 'YYYYYYYY', // Senha fornecida pelo provedor GovBr
    'redirectUri'  => "https://seu-app-dominio.com.br/seu-login", // Url de redirecionamento
    'redirectUriLogout'   => "https://seu-app-dominio.com.br/seu-logout"
]);

Atenção! Os parâmetros clientId e clientSecret acima são sigilosos, evite enviar esses valores para seu repositório git; prefira obtê-los usando getenv(...).

Obtendo a url de autorização:

$urlAutorizacao = $govBr->getAuthorizationUrl();
$state = $this->govBr->getState();
// redirecionar o usuário para a url 

Obtendo o token de acesso (Access Token):

$authorizationCode = $_GET['code'];
$accessToken = 
       $govBr->getAccessToken(
            new AuthorizationCode(), 
            ['code' => $authorizationCode]
       );

Obtendo mais informações do usuário:

$govBrUser = $govBr->getResourceOwner($accessToken);         
$govBrUser->getName();
$govBrUser->getCpf();
$govBrUser->getAvatarUrl();
$govBrUser->getProfile();
$govBrUser->getPhoneNumber();
$govBrUser->phoneNumberVerified();
$govBrUser->getEmail();
$govBrUser->emailVerified();

// Obtendo o avatar do usuário
$avatar = $govBr->getAvatar($govBrUser);
if ($avatar !== null) {
    $avatar->image();
    $avatar->imageBase64();
    $avatar->mimeType();
    $avatar->toHtml(['width' => 60]);
}

Obtendo a url de logout:

$urlLogout = $govBr->getLogoutUrl();
// redirecionar  

Ambiente de Homologação

Por padrão, o ambiente será de produção, mas você pode escolher o ambiente de homologação (staging) solicitando uma instância da seguinte forma:

<?php
$govBr = GovBr::staging([
    'clientId'     => 'XXXXXXXX', // Client ID fornecido pelo GovBr
    'clientSecret' => 'YYYYYYYY', // Senha fornecida pelo provedor GovBr
    'redirectUri'  => "https://seu-app-dominio.com.br/seu-login", // Url de redirecionamento
    'redirectUriLogout'   => "https://seu-app-dominio.com.br/seu-logout"
]);

Além do provider para Gov.br, junto com este pacote fornecemos um exemplo para o fluxo Authorization Code aqui. Diponibilizamos também um servidor (containar docker) para que você possar executar esse fluxo em um ambiente de homolocação usando suas configuraçoes. Para isso, basta seguir as instruções desse ROTEIRO.

Contribuindo

Para contribuir com esse projeto, por favor veja nossas diretrizes.

Segurança

Se você descobrir qualquer problema relacionado à segurança, envie um e-mail em vez de abrir uma issue.

Licença

Este projeto está licenciado sob os termos da licença MIT. Consulte o arquivo LICENSE para entender os direitos e limitações.

You might also like...
A plugin for implementing an OAuth2 server in CakePHP 3

OAuth2 Server for CakePHP 3 A plugin for implementing an OAuth2 server in CakePHP 3. Built on top of the PHP League's OAuth2 Server. Currently we supp

EvaOAuth provides a standard interface for OAuth1.0(a) / OAuth2.0 client authorization, it is easy to integrate with any PHP project by very few lines code.

EvaOAuth EvaOAuth provides a standard interface for OAuth1.0 / OAuth2.0 client authorization, it is easy to integrate with any PHP project by very few

Static utilitiy classes to bridge PSR-7 http messages to OAuth2 Server requests and responses.

Static utilitiy classes to bridge PSR-7 http messages to OAuth2 Server requests and responses. While this libray is entended for use with Slim 3, it should work with any PSR-7 compatible framework.

This plugin integrates OAuth2 functionality into Guzzle Bundle

Guzzle Bundle OAuth2 Plugin This plugin integrates OAuth2 functionality into Guzzle Bundle, a bundle for building RESTful web service clients. Prerequ

Routes and Middleware for Using OAuth2 Server within a Slim Framework API

Chadicus\Slim\OAuth2 A collection of OAuth2 Server routes, middleware and utilities for use within a Slim 3 Framework API Requirements Chadicus\Slim\O

Laravel Passport is an OAuth2 server and API authentication package that is simple and enjoyable to use

Introduction Laravel Passport is an OAuth2 server and API authentication package that is simple and enjoyable to use. Official Documentation Documenta

A demo application for running an OAuth2 server
A demo application for running an OAuth2 server

OAuth2 Demo PHP This application is designed to demo the workflow between OAuth2.0 Clients and Servers. If this is your first time here, try experimen

Social (OAuth1\OAuth2\OpenID\OpenIDConnect) sign with PHP

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

This library extends the 'League OAuth2 Client' library to provide OpenID Connect Discovery support for supporting providers that expose a .well-known configuration endpoint.

OpenID Connect Discovery support for League - OAuth 2.0 Client This library extends the League OAuth2 Client library to provide OpenID Connect Discove

Releases(1.0.2)
StartZ oauth2-etsy compatible League of PHP OAuth2

Etsy Provider for OAuth 2.0 Client This package provides Etsy OAuth 2.0 support for the PHP League's OAuth 2.0 Client. Requirements The following vers

StartZ 2 Nov 10, 2022
Sistema de Administrativo - Cliente e Vendedor - Autenticação JWT e Relacionamentos BD

Hi there, My name is ATTILA SAMUELL TABORY, I love technology ?? Sistema Administrativo Laravel e Vue JS - JWT e Relacionamentos BD Sistema Administra

Attila Samuell 7 May 9, 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 518 Dec 28, 2022
documentation for the oauth2-server-php library

OAuth2 Server PHP Documentation This repository hosts the documentation for the oauth2-server-php library. All submissions are welcome! To submit a ch

Brent Shaffer 227 Nov 24, 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
:octocat: Socialite is an OAuth2 Authentication tool. It is inspired by laravel/socialite, you can easily use it without Laravel.

Socialite Socialite is an OAuth2 Authentication tool. It is inspired by laravel/socialite, You can easily use it in any PHP project. 中文文档 This tool no

安正超 1.2k Dec 22, 2022
OAuth client integration for Symfony. Supports both OAuth1.0a and OAuth2.

HWIOAuthBundle The HWIOAuthBundle adds support for authenticating users via OAuth1.0a or OAuth2 in Symfony. Note: this bundle adds easy way to impleme

Hardware Info 2.2k Dec 30, 2022
This is a basic Oauth2 authorization/authentication server implemented using Mezzio.

Mezzio-OAuth2-Authorization-Authentication-Server This is a basic OAuth2 authorization/authentication server implemented using Mezzio. I have found so

null 1 Nov 15, 2022
EvaOAuth provides a standard interface for OAuth1.0(a) / OAuth2.0 client authorization, it is easy to integrate with any PHP project by very few lines code.

EvaOAuth EvaOAuth provides a standard interface for OAuth1.0 / OAuth2.0 client authorization, it is easy to integrate with any PHP project by very few

AlloVince 256 Nov 16, 2022