Iara  Simões

Iara Simões

1669107380

Difference Between Authentication and Authorization

Authentication vs Authorization: What's the Difference? In this tutorial, you'll learn: The differences between authentication and authorization, How each of these processes work, Examples of authorization and authentication in everyday life.

When you're starting out in web development, you'll likely hear the terms authentication and authorization all the time. And it doesn't help that they're both usually abbreviated 'auth', so it's very easy to get the two confused.

In this article, you will learn:

  • The differences between authentication and authorization
  • How each of these processes work
  • Examples of authorization and authentication in everyday life.

‌‌‌‌Ok, let's get started.

What is Authentication?

Authentication is the the process of verifying the credentials a user provides with those stored in a system to prove the user is who they say they are. If the credentials match, then you grant access. If not, you deny it.

Methods of Authentication

Single Factor authentication:

This is often used as the authentication process for lower risk systems. You only need a single factor to authenticate, with the most common being a password, so it's more vulnerable to phishing attacks and key loggers.

In addition to this, a recent article by DataProt showed that  78% of Gen-Z people utilize the same password for multiple services. This means that if an attacker gained access to one user account, they have a high probability of gaining access to others by simply using the same password.

2-Factor Authentication:

This method is more secure, as it comprises two factors of authentication – typically something you know, for example username and password , plus something you have / own, for example a phone SMS or a security token.

For 2-factor authentication, you would enter a one-time SMS password sent to your device, or perhaps a linked authenticator app code and provide an ever-changing access code.

As you can imagine, this is a lot more secure than simply entering a password, or a single authentication credential. You would need to know the login credentials, as well as have access to the physical device for the second part.

2-factor authentication has become very common amongst online services in recent years, and with many large companies it is the default authentication method. Many require that you setup 2-factor auth in order to even utilize the service.

Multi-Factor Authentication:

Going one step further to make your authentication process even more secure is having 3 or more factors. This form of authentication usually works on the premise of:

  • something you know (username + password or a username + security question and answer)
  • something you have (mobile phone sms, authenticator app, USB key)
  • something you are (like a fingerprint / face recognition)

For these reasons, multi-factor authentication offers the most protection, as you would need to compromise multiple factors, and these factors are a lot more difficult to "hack" or replicate.

The downside to this method of authentication, and the reason it's not utilized in many average systems, is it can be cumbersome to setup and maintain. So the data / system you're protecting really has to justify the need for such security.

So, How Much Information Do You Need to Authenticate?

This question comes up at many security architecture meetings, and the answer is "it depends".

It is not unusual for companies to combine various authentication methods to increase security based on the nature of application.

For example, take a banking app. It contains very sensitive information, and could have a huge financial and reputational impacts should it be obtained by the wrong person. The bank may combine personal questions to be answered, along with a customer number and complex password.

On the other hand, for a social media site, you might only require a username and password, which is then checked and verified before allowing access.

Auth_Process-1

It's all about the level of risk involved and what information someone can access once they're in the application. This helps determine the level of authentication you need.

If you or your team underestimates the level of authentication your app needs, you could be prosecuted for not securing the data within your system adequately. So companies employee security specialists to advise on best practices and appropriate solutions.

How Does Authentication Work in the Real World?

Let's take an example of a social media account. You choose your favorite social media site (which is hosted on a server). The server will ask you to provide credentials to access the site via a sign in page. Here you would type in your username and password that you used when creating the account.

server-process-2

Image showing the authentication process

These details are then sent to the server, and the authentication process begins. The details you provided are verified and checked in the server's database, and if they match the details on record you are authenticated. Then you're provided with a form of identification data, for example a cookie or Json Web Token (JWT token).

Success! You have accessed the site and are given entry.

You can learn more about JWT tokens in another FreeCodeCamp article by Beau Carnes here.

Next, let's look at authorization.

What is Authorization?

Authorization, is the process of verifying that you're allowed to access an area of an application or perform specific actions, based on certain criteria and conditions put in place by the application. You may also hear it called access control or privilege control.

Authorization can either grant or deny permission to carry out tasks, or access areas of an application.

Let's look at an example:

We've gained access to the social media site, but what we're allowed to do there depends on what we're authorized to to do.

If we try to access someone's profile that we're not friends with (they've not accepted our connection request), we're not authorized to view their profile. This means that we are denied permission to view their shared posts.

Basic Authorisation Process

Image of authorization flow

How to Implement Authorization

There are many ways you can implement authorization depending on the frameworks you are using.

Within the .NET framework, for example, you could use role-based access control, or claims-based access control.

Role-based access control is centered around the ideology that each user within your system is assigned a role. These roles have predefined permissions associated with them. Being granted a role means that user will automatically inherit all these permissions. The roles are assigned at time of user creation and setup.

The endpoint or site simply then checks if the current logged-in user has the role of Admin when attempting to access the admin area.

The downside to this approach is that sometimes users are granted too many permissions that they don't need or shouldn't have.

For example, giving a user the role of Admin may mean they would have been givenAdvanced Create, Edit, Delete, and View user privileges. Whereas, you may want to only give them View and Basic Create permissions.

Claims-based access control can allow for finer tuning of a specific user's permissions. The application can either check that the claim simply exists on a user, or whether a particular value is assigned to the claim.

As an example, a claim called CreateUser could be given to a user, and this is checked when creating a user. Or you could assign a value of Advanced to the same claim, and then have different actions and user interface available depending whether the value was Advanced or Basic.

What's the Difference between Authentication and Authorization?

So now that we have a better understanding of the terms, let's look at a scenario you may be familiar with that involves both processes.

At a dinner party with an exclusive guest list, each guest is given a nickname and a secret password.

Upon arrival, a security guard asks you for your nickname and secret password. They then authenticate your credentials against the list they have. If your credentials match, you are handed an envelope showing you've been allowed in.

Once inside you are allowed to access the party and public areas of the venue as these require no authorization (everyone has the permission to enjoy the party). However, you then want to visit the VIP area.

As you approach, another security personnel asks to open your envelope (your permissions and roles). They take a look but unfortunately you do not have the VIP role, and therefore are not authorized to access.‌‌‌‌Put as simply as possible, authentication verifies the identity of a user or service allowing access, whereas authorization determines what they can do once they're in.

Why Should You Implement Both Authentication and Authorization?

As you can see, although authentication and authorization are very different, each plays an integral part in the security and integrity of the application or system.

These processes go hand in hand, and without one the other is kind of meaningless. If you can gain access to the Admin area, but do whatever you want once in there, it could lead to big problems.

On the other hand, you can't authorize individuals without knowing who they are! Which is why authentication always comes before authorization.

Closing Thoughts

I hope this has been insightful and you now have a clearer understanding of the differences between Authorization and Authentication, and how to use them.

Remember:

  • Authenticate =  Verifies the identity of a user or process.
  • Authorize = Determines if the user / system has permission to use a resource or carry out an action.

Original article source at https://www.freecodecamp.org

#security #authentication #authorization #auth 

Difference Between Authentication and Authorization

8 Popular PHP Libraries for Authentication and Authorization

In today's post we will learn about 8 Popular PHP Libraries for Authentication and Authorization. 

What is Authentication and Authorization?

Authentication and authorization are two vital information security processes that administrators use to protect systems and information. Authentication verifies the identity of a user or service, and authorization determines their access rights. Although the two terms sound alike, they play separate but equally essential roles in securing applications and data. Understanding the difference is crucial. Combined, they determine the security of a system. You cannot have a secure solution unless you have configured both authentication and authorization correctly.

Table of contents:

  • Aura.Auth - Provides authentication functionality and session tracking using various adapters.
  • SocialConnect Auth - An open source social sign (OAuth1\OAuth2\OpenID\OpenIDConnect).
  • Json Web Token - Json Tokens to authenticate and transmit information.
  • OAuth 1.0 Client - An OAuth 1.0 client library.
  • OAuth 2.0 Client - An OAuth 2.0 client library.
  • Opauth - A multi-provider authentication framework.
  • Paseto - Platform-Agnostic Security Tokens.
  • PHP oAuthLib - Another OAuth library.

1 - Aura.Auth:

Provides authentication functionality and session tracking using various adapters, currently supported adapters are:

  • Apache htpasswd files
  • SQL tables via the PDO extension
  • IMAP/POP/NNTP via the imap extension
  • LDAP and Active Directory via the ldap extension
  • OAuth via customized adapters

Note that the purpose of this package is only to authenticate user credentials. It does not currently, and probably will not in the future, handle user account creation and management. That is more properly the domain of application-level functionality, or at least a separate Aura bundle.

Foreword

Installation

This library requires PHP 7.2 or later, and has no userland dependencies.

It is installable and autoloadable via Composer as aura/auth.

Alternatively, download a release or clone this repository, then require or include its autoload.php file.

Getting Started

Instantiation

To track authentication state and related information, create an Auth object using the AuthFactory.

<?php
$auth_factory = new \Aura\Auth\AuthFactory($_COOKIE);
$auth = $auth_factory->newInstance();
?>

You can retrieve authentication information using the following methods on the Auth instance:

getUserName(): returns the authenticated username string

getUserData(): returns the array of optional arbitrary user data

getFirstActive(): returns the Unix time of first activity (login)

getLastActive(): return the Unix time of most-recent activity (generally that of the current request)

getStatus(): returns the current authentication status constant. These constants are:

Status::ANON -- anonymous/unauthenticated

Status::IDLE -- the authenticated session has been idle for too long

Status::EXPIRED -- the authenticated session has lasted for too long in total

Status::VALID -- authenticated and valid

isAnon(), isIdle(), isExpired(), isValid(): these return true or false, based on the current authentication status.

You can also use the set*() variations of the get*() methods above to force the Auth object to whatever values you like. However, because the values are stored in a $_SESSION segment, the values will not be retained if a session is not running.

To retain values in a session, you can start a session by force with session_start() on your own. Alternatively, it would be better to use one of the Aura.Auth package services to handle authentication and session-state management for you.

Services

This package comes with three services for dealing with authentication phases:

LoginService to log in and start (or resume) a session,

LogoutService to log out and remove the username and user data in the session (note that this does not destroy the session), and

ResumeService to resume a previously-started session.

You can create each by using the AuthFactory. For now, we will look at how to force login and logout; later, we will show how to have the service use a credential adapter.

Forcing Login

You can force the Auth object to a logged-in state by calling the LoginService forceLogin() method with a user name and optional arbitrary user data.

<?php
// the authentication status is currently anonymous
echo $auth->getStatus(); // ANON

// create the login service
$login_service = $auth_factory->newLoginService();

// use the service to force $auth to a logged-in state
$username = 'boshag';
$userdata = array(
    'first_name' => 'Bolivar',
    'last_name' => 'Shagnasty',
    'email' => 'boshag@example.com',
);
$login_service->forceLogin($auth, $username, $userdata);

// now the authentication status is valid
echo $auth->getStatus(); // VALID
?>

Using forceLogin() has these side effects:

it starts a new session if one has not already been started, or resumes a previous session if one exists

it regenerates the session ID

The specified user name and user data will be stored in a $_SESSION segment, along with an authentication status of Status::VALID.

Note that forceLogin() does not check any credential sources. You as the application owner are forcing the Auth object to a logged-in state.

View on Github

2 - SocialConnect Auth:

An open source social sign (OAuth1\OAuth2\OpenID\OpenIDConnect).

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

Code examples you can find in example directory

Features

  • Functional: support 30+ providers such as Facebook, Google, Twitter, GitHub, Vk and another.
  • Completely: We supports all social sign standarts: OAuth1/OAuth2/OpenID/OpenIDConnect.
  • Follow standards: We follow PSR-7/PSR-17/PSR-18 standards.
  • Modular: Use only what, that you need, see architecture overview.
  • Quality: CodeCoverage with 80%+ and We are using static analyzers.

Supported type of providers

Supported providers

SocialConnect/Auth support 30+ providers such as Facebook, Google, Twitter, GitHub, Vk and another.

See all 30+ provider

Installation & Getting Started

There is a documentation for Installation & Getting Started

Referenced projects

View on Github

3 - Json Web Token:

Json Tokens to authenticate and transmit information.

A simple library to work with JSON Web Token and JSON Web Signature based on the RFC 7519.

Installation

Package is available on Packagist, you can install it using Composer.

composer require lcobucci/jwt

Documentation

The documentation is available at https://lcobucci-jwt.readthedocs.io/en/latest/.

View on Github

4 - OAuth 1.0 Client:

An OAuth 1.0 client library.

OAuth 1 Client is an OAuth RFC 5849 standards-compliant library for authenticating against OAuth 1 servers.

It has built in support for:

  • Bitbucket
  • Magento
  • Trello
  • Tumblr
  • Twitter
  • Uservoice
  • Xing

Adding support for other providers is trivial. The library requires PHP 7.1+ and is PSR-2 compatible.

Third-Party Providers

If you would like to support other providers, please make them available as a Composer package, then link to them below.

These providers allow integration with other providers not supported by oauth1-client. They may require an older version so please help them out with a pull request if you notice this.

Terminology (as per the RFC 5849 specification):

client
    An HTTP client (per [RFC2616]) capable of making OAuth-
    authenticated requests (Section 3).

server
    An HTTP server (per [RFC2616]) capable of accepting OAuth-
    authenticated requests (Section 3).

protected resource
    An access-restricted resource that can be obtained from the
    server using an OAuth-authenticated request (Section 3).

resource owner
    An entity capable of accessing and controlling protected
    resources by using credentials to authenticate with the server.

credentials
    Credentials are a pair of a unique identifier and a matching
    shared secret.  OAuth defines three classes of credentials:
    client, temporary, and token, used to identify and authenticate
    the client making the request, the authorization request, and
    the access grant, respectively.

token
    A unique identifier issued by the server and used by the client
    to associate authenticated requests with the resource owner
    whose authorization is requested or has been obtained by the
    client.  Tokens have a matching shared-secret that is used by
    the client to establish its ownership of the token, and its
    authority to represent the resource owner.

The original community specification used a somewhat different
terminology that maps to this specifications as follows (original
community terms provided on left):

Consumer:  client

Service Provider:  server

User:  resource owner

Consumer Key and Secret:  client credentials

Request Token and Secret:  temporary credentials

Access Token and Secret:  token credentials

Install

Via Composer

$ composer require league/oauth1-client

Usage

Bitbucket

$server = new League\OAuth1\Client\Server\Bitbucket([
    'identifier' => 'your-identifier',
    'secret' => 'your-secret',
    'callback_uri' => "http://your-callback-uri/",
]);

Trello

$server =  new League\OAuth1\Client\Server\Trello([
    'identifier' => 'your-identifier',
    'secret' => 'your-secret',
    'callback_uri' => 'http://your-callback-uri/',
    'name' => 'your-application-name', // optional, defaults to null
    'expiration' => 'your-application-expiration', // optional ('never', '1day', '2days'), defaults to '1day'
    'scope' => 'your-application-scope' // optional ('read', 'read,write'), defaults to 'read'
]);

View on Github

5 - OAuth 2.0 Client:

An OAuth 2.0 client library.

The OAuth 2.0 login flow, seen commonly around the web in the form of "Connect with Facebook/Google/etc." buttons, is a common integration added to web applications, but it can be tricky and tedious to do right. To help, we've created the league/oauth2-client package, which provides a base for integrating with various OAuth 2.0 providers, without overburdening your application with the concerns of RFC 6749.

This OAuth 2.0 client library will work with any OAuth 2.0 provider that conforms to the OAuth 2.0 Authorization Framework. Out-of-the-box, we provide a GenericProvider class to connect to any service provider that uses Bearer tokens. See our basic usage guide for examples using GenericProvider.

Many service providers provide additional functionality above and beyond the OAuth 2.0 specification. For this reason, you may extend and wrap this library to support additional behavior. There are already many official and third-party provider clients available (e.g., Facebook, GitHub, Google, Instagram, LinkedIn, etc.). If your provider isn't in the list, feel free to add it.

This package is compliant with PSR-1, PSR-2, PSR-4, and PSR-7. If you notice compliance oversights, please send a patch via pull request. If you're interested in contributing to this library, please take a look at our contributing guidelines.

Requirements

We support the following versions of PHP:

  • PHP 8.1
  • PHP 8.0
  • PHP 7.4
  • PHP 7.3
  • PHP 7.2
  • PHP 7.1
  • PHP 7.0
  • PHP 5.6

Provider Clients

We provide a list of official PHP League provider clients, as well as third-party provider clients.

To build your own provider client, please refer to "Implementing a Provider Client."

Usage

For usage and code examples, check out our basic usage guide.

Contributing

Please see our contributing guidelines for details.

View on Github

6 - Opauth:

A multi-provider authentication framework.

Opauth is a multi-provider authentication framework for PHP, inspired by OmniAuth for Ruby.

Opauth enables PHP applications to do user authentication with ease.

What is Opauth?

Opauth provides a standardized method for PHP applications to interface with authentication providers.

Opauth as a framework provides a set of API that allows developers to create strategies that work in a predictable manner across PHP frameworks and applications.

Opauth works well with other PHP applications & frameworks. It is currently supported on:

If your PHP framework of choice is not yet listed, you can still use Opauth like you would a normal PHP component (class).

Quick start

Guide on how to run the bundled example.

Set DocumentRoot of your web server to example/. (Opauth can be instantiated in your own PHP app, but we will leave that out of this quick start guide)

Configure Opauth.

First, make a copy of opauth config's file by copying or renaming opauth.conf.php.default to opauth.conf.php.

Open up opauth.conf.php and make the necessary changes.

Install some Opauth strategies. Place the strategy files in lib/Opauth/Strategy/.

For this example, we recommend that you start with Opauth-Facebook:

i. Download the strategy files and place them at lib/Opauth/Strategy/Facebook/.

ii. Follow the steps at Opauth-Facebook's README to set up your Faceobok app.

iii. Add the following at opauth.conf.php under Strategy as such:

<?php
'Strategy' => array(
    // Define strategies here.

    'Facebook' => array(
        'app_id' => 'YOUR APP ID',
        'app_secret' => 'YOUR APP SECRET'
    ),
);

Finally, send user to http://localhost/facebook to authenticate.

Check out the wiki for more in-depth details, especially on how to use Opauth with your own PHP application.

Requirements

PHP 5 (>= 5.2) with allow_url_fopen enabled

Contribute

Opauth needs your contributions, especially the following:

More strategies Refer to wiki for contribution guide and inform us when your work is ready.

Plugins for more PHP frameworks and CMSes eg. Symfony, Laravel, WordPress, Drupal, etc.

Guides & tutorials On how to implement Opauth on CakePHP app, etc.

View on Github

7 - Paseto:

Platform-Agnostic Security Tokens.

Paseto (pɔːsɛtəʊ, paw-set-oh) is everything you love about JOSE (JWT, JWE, JWS) without any of the many design deficits that plague the JOSE standards.

This library is a reference implementation of PASETO in the PHP language. Please refer to the PASETO Specification for design considerations.

How to Use this Library

See the documentation.

The PASETO specification may also be useful for understanding why things are designed the way they are.

PASETO Extensions

PASERK

For key wrapping, serialization, and canonical identification, please see the PHP implementation of PASERK.

If you're not sure what that means, please refer to the PASERK specification.

Since PASERK is a PASETO extension, PASERK support is not automatically included with PASETO, but PASETO is bundled with PASERK.

Requirements

PHP PASETO Library Version 3

  • Requires PHP 8.1 or newer.
  • For v3 tokens, the GMP and OpenSSL extensions are required.
  • For v4 tokens, the Sodium extension is strongly recommended (but this library will use sodium_compat if it's not).
  • PASETO Protocol versions: v3, v4

PHP PASETO Library Version 2

  • Requires PHP 7.1 or newer.
  • For v3 tokens, the GMP and OpenSSL extensions are required.
  • For v4 tokens, the Sodium extension is strongly recommended (but this library will use sodium_compat if it's not).
  • PASETO Protocol versions: v1, v2, v3, v4

PHP PASETO Library Version 1

  • Requires PHP 7.0 or newer.
  • For v1 tokens, the OpenSSL extension is required.
  • For v2 tokens, the Sodium extension is strongly recommended (but this library will use sodium_compat if it's not).
  • PASETO Protocol versions: v1, v2

View on Github

8 - PHP oAuthLib:

Another OAuth library.

NOTE: I'm looking for someone who could help to maintain this package alongside me, just because I don't have a ton of time to devote to it. However, I'm still going to keep trying to pay attention to PRs, etc.

PHPoAuthLib provides oAuth support in PHP 7.2+ and is very easy to integrate with any project which requires an oAuth client.

Installation

This library can be found on Packagist. The recommended way to install this is through composer.

    composer require lusitanian/oauth

Features

  • PSR-4
  • Fully extensible in every facet.
    • You can implement any service with any custom requirements by extending the protocol version's AbstractService implementation.
    • You can use any HTTP client you desire, just create a class utilizing it which implements OAuth\Common\Http\ClientInterface (two implementations are included)
    • You can use any storage mechanism for tokens. By default, session, in-memory and Redis.io (requires PHPRedis) storage mechanisms are included. Implement additional mechanisms by implementing OAuth\Common\Token\TokenStorageInterface.

Included service implementations

  • OAuth1
    • 500px
    • BitBucket
    • Etsy
    • FitBit
    • Flickr
    • QuickBooks
    • Scoop.it!
    • Tumblr
    • Twitter
    • Yahoo
  • OAuth2
    • Amazon
    • BitLy
    • Bitrix24
    • Box
    • Buffer
    • Dailymotion
    • Delicious
    • Deezer
    • DeviantArt
    • Dropbox
    • Eve Online
    • Facebook
    • Foursquare
    • GitHub
    • Google
    • Harvest
    • Heroku
    • Hubic
    • Instagram
    • Jawbone UP
    • LinkedIn
    • Mailchimp
    • Microsoft
    • Mondo
    • Nest
    • Netatmo
    • Parrot Flower Power
    • PayPal
    • Pinterest
    • Pocket
    • Reddit
    • RunKeeper
    • Salesforce
    • SoundCloud
    • Spotify
    • Strava
    • Stripe
    • Ustream
    • Vimeo
    • Vkontakte
    • Xing
    • Yahoo
    • Yammer
  • more to come!

Examples

    php -S localhost:8000 -t examples

Then point your browser to:

    http://localhost:8000/

Usage

For usage with complete auth flow, please see the examples. More in-depth documentation will come with release 1.0.

View on Github

Thank you for following this article.

Related videos:

Authorization & Authentication | Login & Register System In Laravel | Laravel For Beginners

#php #authentication #authorization 

8 Popular PHP Libraries for Authentication and Authorization

Library Support Navgiation for Authorization Flow on Flutter

auth_nav

A new Flutter package.

Getting Started

This project is a starting point for a Dart package, a library module containing code that can be shared easily across multiple Flutter or Dart projects.

For help getting started with Flutter, view our online documentation, which offers tutorials, samples, guidance on mobile development, and a full API reference.

Use this package as a library

Depend on it

Run this command:

With Flutter:

 $ flutter pub add auth_nav

This will add a line like this to your package's pubspec.yaml (and run an implicit flutter pub get):

dependencies:
  auth_nav: ^2.0.2

Alternatively, your editor might support flutter pub get. Check the docs for your editor to learn more.

Import it

Now in your Dart code, you can use:

import 'package:auth_nav/auth_nav.dart'; 

example/lib/main.dart

import 'package:auth_nav/bloc/auth_navigation_bloc.dart';
import 'package:auth_nav/bloc/auth_navigation_state.dart';
import 'package:auth_nav/navigation/auth_navigation.dart';
import 'package:example/pages/splash_app_page.dart';
import 'package:flutter/material.dart';
import 'package:flutter_bloc/flutter_bloc.dart';
import 'package:example/pages/authorized_page.dart';
import 'package:example/pages/login_page.dart';

void main() {
  runApp(BlocProvider(
      create: (context) => AuthNavigationBloc(),
      child: MyApp(),
  ));
}

class MyApp extends StatelessWidget {
  @override
  Widget build(BuildContext context) {
    return MaterialApp(
      theme: ThemeData.light(),
      home: AuthNavigation(
        splashScreen: SplashAppPage((context) async {
          return Future.delayed(Duration(seconds: 2), () => AuthNavigationState.unAuthorized());
        }),
        authorizedBuilder: (context) => AuthorizedPage(),
        unAuthorizedBuilder: (context) => LoginPage(),
      ),
    );
  }
} 

Download Details:

Author: dangngocduc

Source Code: https://github.com/dangngocduc/auth_nav

#flutter #authorization #auth 

Library Support Navgiation for Authorization Flow on Flutter
Dexter  Goodwin

Dexter Goodwin

1661243580

Casl: An Isomorphic Authorization JavaScript Library Which Restricts

CASL (pronounced /ˈkæsəl/, like castle) is an isomorphic authorization JavaScript library which restricts what resources a given user is allowed to access. It's designed to be incrementally adoptable and can easily scale between a simple claim based and fully featured subject and attribute based authorization. It makes it easy to manage and share permissions across UI components, API services, and database queries.

Heavily inspired by cancan.

Features

  • Versatile
    An incrementally adoptable and can easily scale between a simple claim based and fully featured subject and attribute based authorization.
  • Isomorphic
    Can be used on frontend and backend and complementary packages make integration with major Frontend Frameworks and Backend ORMs effortless
  • TypeSafe
    Written in TypeScript, what makes your apps safer and developer experience more enjoyable
  • Tree shakable
    The core is only 6KB mingzipped and can be even smaller!
  • Declarative
    Thanks to declarative rules, you can serialize and share permissions between UI and API or microservices

Ecosystem

ProjectStatusDescriptionSupported envinronemnts
@casl/ability@casl/ability-statusCASL's core packagenodejs 8+ and ES5 compatible browsers (IE 9+)
@casl/mongoose@casl/mongoose-statusintegration with Mongoosenodejs 8+
@casl/prisma@casl/prisma-statusintegration with Prismanodejs 12+
@casl/angular@casl/angular-statusintegration with AngularIE 9+
@casl/react@casl/react-statusintegration with ReactIE 9+
@casl/vue@casl/vue-statusintegration with VueIE 11+ (uses WeakMap)
@casl/aurelia@casl/aurelia-statusintegration with AureliaIE 11+ (uses WeakMap)

Documentation

A lot of detailed information about CASL, integrations and examples can be found in documentation.

Have a question?

Ask it in chat or on stackoverflow. Please don't ask questions in issues, the issue list of this repo is exclusively for bug reports and feature requests. Questions in the issue list may be closed immediately without answers.

CASL crash course

CASL operates on the abilities level, that is what a user can actually do in the application. An ability itself depends on the 4 parameters (last 3 are optional):

  1. User Action
    Describes what user can actually do in the app. User action is a word (usually a verb) which depends on the business logic (e.g., prolong, read). Very often it will be a list of words from CRUD - create, read, update and delete.
  2. Subject
    The subject or subject type which you want to check user action on. Usually this is a business (or domain) entity name (e.g., Subscription, BlogPost, User).
  3. Conditions
    An object or function which restricts user action only to matched subjects. This is useful when you need to give a permission on resources created by a user (e.g., to allow user to update and delete own BlogPost)
  4. Fields
    Can be used to restrict user action only to matched subject's fields (e.g., to allow moderator to update hidden field of BlogPost but not update description or title)

Using CASL you can describe abilities using regular and inverted rules. Let's see how

Note: all the examples below will be written in TypeScript but CASL can be used in similar way in ES6+ and Nodejs environments.

1. Define Abilities

Lets define Ability for a blog website where visitors:

  • can read blog posts
  • can manage (i.e., do anything) own posts
  • cannot delete a post if it was created more than a day ago
import { AbilityBuilder, Ability } from '@casl/ability'
import { User } from '../models'; // application specific interfaces

/**
 * @param user contains details about logged in user: its id, name, email, etc
 */
function defineAbilitiesFor(user: User) {
  const { can, cannot, rules } = new AbilityBuilder(Ability);

  // can read blog posts
  can('read', 'BlogPost');
  // can manage (i.e., do anything) own posts
  can('manage', 'BlogPost', { author: user.id });
  // cannot delete a post if it was created more than a day ago
  cannot('delete', 'BlogPost', {
    createdAt: { $lt: Date.now() - 24 * 60 * 60 * 1000 }
  });

  return new Ability(rules);
});

Do you see how easily business requirements were translated into CASL's rules?

Note: you can use class instead of string as a subject type (e.g., can('read', BlogPost))

And yes, Ability class allow you to use some MongoDB operators to define conditions. Don't worry if you don't know MongoDB, it's not required and explained in details in Defining Abilities

2. Check Abilities

Later on you can check abilities by using can and cannot methods of Ability instance.

// in the same file as above
import { ForbiddenError } from '@casl/ability';

const user = getLoggedInUser(); // app specific function
const ability = defineAbilitiesFor(user);

class BlogPost { // business entity
  constructor(props) {
    Object.assign(this, props);
  }
}

// true if ability allows to read at least one Post
ability.can('read', 'BlogPost');
// the same as
ability.can('read', BlogPost);

// true, if user is the author of the blog post
ability.can('manage', new BlogPost({ author: user.id }));

// true if there is no ability to read this particular blog post
const ONE_DAY = 24 * 60 * 60 * 1000;
const postCreatedNow = new BlogPost({ createdAt: new Date() });
const postCreatedAWeekAgo = new BlogPost({ createdAt: new Date(Date.now() - 7 * ONE_DAY) });

// can delete if it's created less than a day ago
ability.can('delete', postCreatedNow); // true
ability.can('delete', postCreatedAWeekAgo); // false

// you can even throw an error if there is a missed ability
ForbiddenError.from(ability).throwUnlessCan('delete', postCreatedAWeekAgo);

Of course, you are not restricted to use only class instances in order to check permissions on objects. See Introduction for the detailed explanation.

3. Database integration

CASL has a complementary package @casl/mongoose which provides easy integration with MongoDB and mongoose.

import { AbilityBuilder } from '@casl/ability';
import { accessibleRecordsPlugin } from '@casl/mongoose';
import mongoose from 'mongoose';

mongoose.plugin(accessibleRecordsPlugin);

const user = getUserLoggedInUser(); // app specific function

const ability = defineAbilitiesFor(user);
const BlogPost = mongoose.model('BlogPost', mongoose.Schema({
  title: String,
  author: mongoose.Types.ObjectId,
  content: String,
  createdAt: Date,
  hidden: { type: Boolean, default: false }
}))

// returns mongoose Query, so you can chain it with other conditions
const posts = await BlogPost.accessibleBy(ability).where({ hidden: false });

// you can also call it on existing query to enforce permissions
const hiddenPosts = await BlogPost.find({ hidden: true }).accessibleBy(ability);

// you can even pass the action as a 2nd parameter. By default action is "read"
const updatablePosts = await BlogPost.accessibleBy(ability, 'update');

See Database integration for details.

4. Advanced usage

CASL is incrementally adoptable, that means you can start your project with simple claim (or action) based authorization and evolve it later, when your app functionality evolves.

CASL is composable, that means you can implement alternative conditions matching (e.g., based on joi, ajv or pure functions) and field matching (e.g., to support alternative syntax in fields like addresses.*.street or addresses[0].street) logic.

See Advanced usage for details.

5. Examples

Looking for examples? Check CASL examples repository.

Want to help?

Want to file a bug, contribute some code, or improve documentation? Excellent! Read up on guidelines for contributing.

If you'd like to help us sustain our community and project, consider to become a financial contributor on Open Collective

Download Details:

Author: Stalniy
Source Code: https://github.com/stalniy/casl 
License: MIT license

#javascript #authorization #permission 

Casl: An Isomorphic Authorization JavaScript Library Which Restricts
Rupert  Beatty

Rupert Beatty

1658099700

Declarative Style Of Authorization and Validation in Laravel

Laravel Hey Man

 

In fact, We have tackled a lot of complexity behind the scenes, to provide you with a lot of simplicity.

Installation:


composer require imanghafoori/laravel-heyman

Requirements:

  • PHP v7.0 or above
  • Laravel v5.1 or above

Example:

Here you can see a good example at:

https://github.com/imanghafoori1/council

Specially this file:

https://github.com/imanghafoori1/council/blob/master/app/Providers/AuthServiceProvider.php

This is fork from result of laracasts.com tutorial series refactored to use the Heyman package.

Heyman, let's fight off zombies

Zombie Http Request =>


 

<= Laravel Heyman
 

A story:

Imagine your boss comes to you and says :

 Hey man !!!
 
 When you visit the login form,
 
 You should be guest,
 
 Otherwise you get redirected to '/panel',

Write the code for me, just now... But KEEP IN MIND you are not allowed to touch the current code. it is very sensitive and we do not want you to tamper with it. You may break it.

And you write code like this in a Service Provider boot method to implement what your boss wanted.

image

That is what this package does for you + a lot more...

Customizable Syntax:

You can alias methods like this if you do not like too much verbose syntax provided by default.

  • Alias Situations (ex. whenYouMakeView to view)
  • Alias Conditions (ex. youShouldBeGuest to beGuest)

You should do it in the boot method.

alias methods

Structural Benefits:

1- This way you can fully decouple authorization and a lot of guarding code from the rest of your application code and put it in an other place. So your Controllers and Routes become less crowded and you will have a central place where you limit the access of users to your application or perform Request validation.

2- In fact, when you write your code in the way, you are conforming to the famous "Tell don't ask principle."

You are telling the framework what to do in certain situations rather than getting information and decide what to do then.

Procedural code gets information then makes decisions. Object-oriented code tells objects to do things. — Alec Sharp

3- This approach is paticularly useful when you for example write a package which needs ACL but you want to allow your package users to override and apply they own ACL (or validation) rules into your package routes...

And that becomes possible when you use laravel-HeyMan for ACL. The users can easily cancel out the default rules and re-write their favorite acl or validation stuff in a regular ServiceProviders.

Hey Man, that is Amazing stuff!


// This is written in package and lives in vendor folder, So we can not touch it.
HeyMan::whenYouHitRouteName('myPackageRoute')->youShouldHaveRole(....; 

To override that we use the forget method, within app/Providers/... :


public function boot() {
  
  // Cancels out the current rules
   HeyMan::forget()->aboutRoute('myPackageRoute');
  
  
   // Add new rules by package user.
   HeyMan::whenYouHitRouteName('myPackageRoute')-> ... 
   
}

Hey Man, Should I Momorize all the Methods?!

You do not need any cheat sheet.

IDE Auto-completion is fully supported.

refactor5

Hey Man, Where do I put these Heyman:: calls?

You may put them in AuthServiceProvider.php (or any other service provider) boot method.

image

Usage:

You should call the following method of the HeyMan Facade class.

use Imanghafoori\HeyMan\Facades\HeyMan;
// or
use HeyMan;  // <--- alias

Again we recommend visiting this file:

Working heyman sample rules

Situations:

HeyMan::  (situation) ->   (condition)   -> otherwise() -> (reaction) ;

1- Url is matched

HeyMan::whenYouVisitUrl(['/welcome', '/home'])->...   // you can pass an Array
HeyMan::whenYouVisitUrl('/admin/*')->...     // or match by wildcard
HeyMan::whenYouSendPost('/article/store')->   ...   
HeyMan::whenYouSendPatch('/article/edit')->  ...  
HeyMan::whenYouSendPut('/article/edit')->    ...     
HeyMan::whenYouSendDelete('/article/delete')-> ...

2- Route Name is matched

HeyMan::whenYouHitRouteName('welcome.name')->...              // For route names
HeyMan::whenYouHitRouteName('welcome.*')->...                 // or match by wildcard

3- Controller Action is about to Call

HeyMan::whenYouCallAction('HomeController@index')->...
HeyMan::whenYouCallAction('HomeController@*')->...          // or match by wildcard

4- A View file is about to render

 HeyMan::whenYouMakeView('article.editForm')->...     // also accepts an array
 HeyMan::whenYouMakeView('article.*')->...            // You can watch a group of views

Actually it refers to the moment when view('article.editForm') is executed.

5- Custom Event is Fired

HeyMan::whenEventHappens('myEvent')->...

Actually it refers to the moment when event('myEvent') is executed.

6- An Eloquent Model is about to save

HeyMan::whenYouSave(\App\User::class)->...
HeyMan::whenYouFetch(\App\User::class)->...
HeyMan::whenYouCreate(\App\User::class)->...
HeyMan::whenYouUpdate(\App\User::class)->...
HeyMan::whenYouDelete(\App\User::class)->...

Actually it refers to the moment when eloquent fires it's internal events like: (saving, deleting, creating, ...)

Note that the saving model is passed to the Gate of callback in the next chain call. so for example you can check the ID of the model which is saving.

Conditions:

HeyMan::  (situation) ->   (condition)   -> otherwise() -> (reaction) ;

After mentioning the situation, it is time to mention the condition.

1- Gates:

// define Gate
Gate::define('hasRole', function(){...});

Then you can use the gate:


HeyMan::whenYouVisitUrl('/home')->thisGateShouldAllow('hasRole', 'editor')->otherwise()->...;

Passing a Closure as a Gate:

$gate = function($user, $role) {
    /// some logic
    return true;
}
HeyMan::whenYouVisitUrl('/home')->thisGateShouldAllow($gate, 'editor')->otherwise()->...;

2- Authentication stuff:

HeyMan::whenYouVisitUrl('/home')->  youShouldBeGuest()    ->otherwise()->...;
HeyMan::whenYouVisitUrl('/home')->  youShouldBeLoggedIn() ->otherwise()->...;

3- Checking A Closure or Method or Value:

HeyMan::whenYouVisitUrl('home')->thisMethodShouldAllow('someClass@someMethod', ['param1'])->otherwise()->...;
HeyMan::whenYouVisitUrl('home')->thisClosureShouldAllow( function($a) { ... }, ['param1'] )  ->otherwise()->...;
HeyMan::whenYouVisitUrl('home')->thisValueShouldAllow( $someValue )->otherwise()->...;

4- Validate Requests:

HeyMan::whenYouHitRouteName('articles.store')->yourRequestShouldBeValid([
    'title' => 'required', 'body' => 'required',
]);

You can also modify the data before validation by calling beforeValidationModifyData().


$modifier = function ($data) {
  // removes "@" character from the "name" before validation.
  $data['name'] = str_replace('@', '', $data['name']);
  return $data;
}

HeyMan::whenYouHitRouteName('welcome.name')
        ->yourRequestShouldBeValid(['name' => 'required'])
        ->beforeValidationModifyData($modifier);

5- Check points:

You can also declare some check points some where, within your application code:


HeyMan::checkPoint('MyLane');

And put some rules for it


HeyMan::whenYouReachCheckPoint('MyLane')->youShouldHaveRole('Zombie')-> ...
HeyMan::whenYouVisitUrl('home')->always()-> ...
HeyMan::whenYouVisitUrl('home')->sessionShouldHave('key1')->...

Other things:

You can also use "always" and "sessionShouldHave" methods:

HeyMan::whenYouVisitUrl('home')->always()-> ...
HeyMan::whenYouVisitUrl('home')->sessionShouldHave('key1')->...

Define your own conditions:

You can extend the conditions and introduce new methods into heyman API like this:


// Place this code:
// In the `boot` method of your service providers

HeyMan::condition('youShouldBeMan', function () {
   return function () {
       return auth()->user() && auth()->user()->gender === 'Man';
   };
});

// or 

HeyMan::condition('youShouldBeMan', '\App\SomeWhere\SomeClass@someMethod');

Then you can use it like this:


HeyMan::whenYouVisitUrl('home')->youShouldBeMan()-> ...

Nice, isn't it ?!

Reactions:

HeyMan::  (situation) ->   (condition)   -> otherwise() -> (reaction) ;

1- Deny Access:

HeyMan::whenSaving(\App\User::class)->thisGateShouldAllow('hasRole', 'editor')->otherwise()->weDenyAccess();

An AuthorizationException will be thrown if needed

2- Redirect:

HeyMan::whenYouVisitUrl('/login')-> ... ->otherwise()->redirect()->to(...)     ->with([...]);
HeyMan::whenYouVisitUrl('/login')-> ... ->otherwise()->redirect()->route(...)  ->withErrors(...);
HeyMan::whenYouVisitUrl('/login')-> ... ->otherwise()->redirect()->action(...) ->withInput(...);
HeyMan::whenYouVisitUrl('/login')-> ... ->otherwise()->redirect()->intended(...);
HeyMan::whenYouVisitUrl('/login')-> ... ->otherwise()->redirect()->guest(...);

In fact the redirect method here is very much like the laravel's redirect() helper function.

3- Throw Exception:

$msg = 'My Message';

HeyMan::whenYouVisitUrl('/login')
    ->youShouldBeGuest()
    ->otherwise()
    ->weThrowNew(AuthorizationException::class, $msg);

4- Abort:

HeyMan::whenYouVisitUrl('/login')-> ... ->otherwise()->abort(...);

5- Send Response:

Calling these functions generate exact same response as calling them on the response() helper function: return response()->json(...);

HeyMan::whenYouVisitUrl('/login')-> ... ->otherwise()->response()->json(...);
HeyMan::whenYouVisitUrl('/login')-> ... ->otherwise()->response()->view(...);
HeyMan::whenYouVisitUrl('/login')-> ... ->otherwise()->response()->jsonp(...);
HeyMan::whenYouVisitUrl('/login')-> ... ->otherwise()->response()->make(...);
HeyMan::whenYouVisitUrl('/login')-> ... ->otherwise()->response()->download(...);

6- Send custom response:

HeyMan::whenYouVisitUrl('/login')-> 
       ...
      ->otherwise()
      ->weRespondFrom('\App\Http\Responses\Authentication@guestsOnly');
namespace App\Http\Responses;

class Authentication
{
    public function guestsOnly()
    {
        if (request()->expectsJson()) {
            return response()->json(['error' => 'Unauthenticated.'], 401);
        }

        return redirect()->guest(route('login'));
    }
}

Hey man, You see ? we have just an Http response here. So our controllers are free to handle the right situaltions and do not worry about exceptional ones.

More Advanced Reactions:

Hey man, You may want to call some method or fire an event right before you send the response back. You can do so by afterCalling() and afterFiringEvent() methods.

HeyMan::whenYouVisitUrl('/login')-> ... ->otherwise()->afterFiringEvent('explode')->response()->json(...);
HeyMan::whenYouVisitUrl('/login')-> ... ->otherwise()->afterCalling('someclass@method1')->response()->json(...);

Disabling Heyman:

You can disable HeyMan checks like this (useful while testing):

untitled


HeyMan::turnOff()->eloquentChecks();

...
/// You may save some eloquent models here...
/// without limitations from HeyMan rules.
...

HeyMan::turnOn()->eloquentChecks();

:raising_hand: Contributing:

If you find an issue, or have a better way to do something, feel free to open an issue or a pull request.

:star: Your Stars Make Us Do More :star:

As always if you found this package useful and you want to encourage us to maintain and work on it. Just press the star button to declare your willing.

More from the author:

Laravel Widgetize

:gem: A minimal yet powerful package to give a better structure and caching opportunity for your laravel apps.


Laravel Terminator

:gem: A minimal yet powerful package to give you opportunity to refactor your controllers.


Laravel AnyPass

:gem: It allows you login with any password in local environment only.


Laravel Microscope

💎 It automatically checks your laravel application (new)


 

Great spirits have always encountered violent opposition from mediocre minds.

"Albert Einstein"

Readability Counts. In fact, Readability is the primary value of your code !!! 

🎀 Heyman continues where the other role-permission packages left off...

We have used CDD (Creativity Driven Development) alongside the TDD

Built with ❤️ for every smart laravel developer

Very well tested, optimized and production ready!


Author: imanghafoori1
Source Code: https://github.com/imanghafoori1/laravel-heyman 
License: MIT license

#laravel #php #authorization 

Declarative Style Of Authorization and Validation in Laravel
Easter  Deckow

Easter Deckow

1654947900

Python LinkedIn: Python Interface to the LinkedIn API

Python LinkedIn

Python interface to the LinkedIn API

This library provides a pure Python interface to the LinkedIn Profile, Group, Company, Jobs, Search, Share, Network and Invitation REST APIs.

LinkedIn provides a service that lets people bring their LinkedIn profiles and networks with them to your site or application via their OAuth based API. This library provides a lightweight interface over a complicated LinkedIn OAuth based API to make it for python programmers easy to use.

Installation

You can install python-linkedin library via pip:

$ pip install python-linkedin

Authentication

The LinkedIn REST API now supports the OAuth 2.0 protocol for authentication. This package provides a full OAuth 2.0 implementation for connecting to LinkedIn as well as an option for using an OAuth 1.0a flow that can be helpful for development purposes or just accessing your own data.

HTTP API example

Set LINKEDIN_API_KEY and LINKEDIN_API_SECRET, configure your app to redirect to http://localhost:8080/code, then execute:

  1. http_api.py
  2. Visit http://localhost:8080 in your browser, curl or similar
  3. A tab in your browser will open up, give LinkedIn permission there
  4. You'll then be presented with a list of available routes, hit any, e.g.:
  5. curl -XGET http://localhost:8080/get_profile

Developer Authentication

To connect to LinkedIn as a developer or just to access your own data, you don't even have to implement an OAuth 2.0 flow that involves redirects. You can simply use the 4 credentials that are provided to you in your LinkedIn appliation as part of an OAuth 1.0a flow and immediately access your data. Here's how:

from linkedin import linkedin

# Define CONSUMER_KEY, CONSUMER_SECRET,  
# USER_TOKEN, and USER_SECRET from the credentials 
# provided in your LinkedIn application

# Instantiate the developer authentication class

authentication = linkedin.LinkedInDeveloperAuthentication(CONSUMER_KEY, CONSUMER_SECRET, 
                                                          USER_TOKEN, USER_SECRET, 
                                                          RETURN_URL, linkedin.PERMISSIONS.enums.values())

# Pass it in to the app...

application = linkedin.LinkedInApplication(authentication)

# Use the app....

application.get_profile()

Production Authentication

In order to use the LinkedIn OAuth 2.0, you have an application key and application secret. You can get more detail from here.

For debugging purposes you can use the credentials below. It belongs to my test application. Nothing's harmful.

KEY = 'wFNJekVpDCJtRPFX812pQsJee-gt0zO4X5XmG6wcfSOSlLocxodAXNMbl0_hw3Vl'
SECRET = 'daJDa6_8UcnGMw1yuq9TjoO_PMKukXMo8vEMo7Qv5J-G3SPgrAV0FqFCd0TNjQyG'

You can also get those keys from here.

LinkedIn redirects the user back to your website's URL after granting access (giving proper permissions) to your application. We call that url RETURN URL. Assuming your return url is http://localhost:8000, you can write something like this:

from linkedin import linkedin

API_KEY = 'wFNJekVpDCJtRPFX812pQsJee-gt0zO4X5XmG6wcfSOSlLocxodAXNMbl0_hw3Vl'
API_SECRET = 'daJDa6_8UcnGMw1yuq9TjoO_PMKukXMo8vEMo7Qv5J-G3SPgrAV0FqFCd0TNjQyG'
RETURN_URL = 'http://localhost:8000'

authentication = linkedin.LinkedInAuthentication(API_KEY, API_SECRET, RETURN_URL, linkedin.PERMISSIONS.enums.values())
# Optionally one can send custom "state" value that will be returned from OAuth server
# It can be used to track your user state or something else (it's up to you)
# Be aware that this value is sent to OAuth server AS IS - make sure to encode or hash it
#authorization.state = 'your_encoded_message'
print authentication.authorization_url  # open this url on your browser
application = linkedin.LinkedInApplication(authentication)

When you grant access to the application, you will be redirected to the return url with the following query strings appended to your RETURN_URL:

"http://localhost:8000/?code=AQTXrv3Pe1iWS0EQvLg0NJA8ju_XuiadXACqHennhWih7iRyDSzAm5jaf3R7I8&state=ea34a04b91c72863c82878d2b8f1836c"

This means that the value of the authorization_code is AQTXrv3Pe1iWS0EQvLg0NJA8ju_XuiadXACqHennhWih7iRyDSzAm5jaf3R7I8. After setting it by hand, we can call the .get_access_token() to get the actual token.

authentication.authorization_code = 'AQTXrv3Pe1iWS0EQvLg0NJA8ju_XuiadXACqHennhWih7iRyDSzAm5jaf3R7I8'
authentication.get_access_token()

After you get the access token, you are now permitted to make API calls on behalf of the user who granted access to you app. In addition to that, in order to prevent from going through the OAuth flow for every consecutive request, one can directly assign the access token obtained before to the application instance.

application = linkedin.LinkedInApplication(token='AQTFtPILQkJzXHrHtyQ0rjLe3W0I')

Quick Usage From Python Interpreter

For testing the library using an interpreter, you can benefit from the test server.

from linkedin import server
application = server.quick_api(KEY, SECRET)

This will print the authorization url to the screen. Go into that URL using a browser to grant access to the application. After you do so, the method will return with an API object you can now use.

Profile API

The Profile API returns a member's LinkedIn profile. You can use this call to return one of two versions of a user's profile which are public profile and standard profile. For more information, check out the documentation.

application.get_profile()
{u'firstName': u'ozgur',
 u'headline': u'This is my headline',
 u'lastName': u'vatansever',
 u'siteStandardProfileRequest': {u'url': u'http://www.linkedin.com/profile/view?id=46113651&authType=name&authToken=Egbj&trk=api*a101945*s101945*'}}

There are many field selectors that enable the client fetch more information from the API. All of them used by each API are listed here.

application.get_profile(selectors=['id', 'first-name', 'last-name', 'location', 'distance', 'num-connections', 'skills', 'educations'])
{u'distance': 0,
 u'educations': {u'_total': 1,
  u'values': [{u'activities': u'This is my activity and society field',
    u'degree': u'graduate',
    u'endDate': {u'year': 2009},
    u'fieldOfStudy': u'computer science',
    u'id': 42611838,
    u'notes': u'This is my additional notes field',
    u'schoolName': u'\u0130stanbul Bilgi \xdcniversitesi',
    u'startDate': {u'year': 2004}}]},
 u'firstName': u'ozgur',
 u'id': u'COjFALsKDP',
 u'lastName': u'vatansever',
 u'location': {u'country': {u'code': u'tr'}, u'name': u'Istanbul, Turkey'},
 u'numConnections': 13}

Connections API

The Connections API returns a list of 1st degree connections for a user who has granted access to their account. For more information, you check out its documentation.

To fetch your connections, you simply call .get_connections() method with proper GET querystring:

application.get_connections()
{u'_total': 13,
 u'values': [{u'apiStandardProfileRequest': {u'headers': {u'_total': 1,
     u'values': [{u'name': u'x-li-auth-token', u'value': u'name:16V1033'}]},
    u'url': u'http://api.linkedin.com/v1/people/lddvGtD5xk'},
   u'firstName': u'John',
   u'headline': u'Ruby',
   u'id': u'2323SDFSsfd34',
   u'industry': u'Computer Software',
   u'lastName': u'DOE',
   u'location': {u'country': {u'code': u'tr'}, u'name': u'Istanbul, Turkey'},
   u'siteStandardProfileRequest': {u'url': u'http://www.linkedin.com/profile/view?id=049430532&authType=name&authToken=16V8&trk=api*a101945*s101945*'}},
   ....

application.get_connections(selectors=['headline', 'first-name', 'last-name'], params={'start':10, 'count':5})

Search API

There are 3 types of Search APIs. One is the People Search API, second one is the Company Search API and the last one is Jobs Search API.

The People Search API returns information about people. It lets you implement most of what shows up when you do a search for "People" in the top right box on LinkedIn.com. You can get more information from here.

application.search_profile(selectors=[{'people': ['first-name', 'last-name']}], params={'keywords': 'apple microsoft'})
# Search URL is https://api.linkedin.com/v1/people-search:(people:(first-name,last-name))?keywords=apple%20microsoft

{u'people': {u'_count': 10,
  u'_start': 0,
  u'_total': 2,
  u'values': [
   {u'firstName': u'John', u'lastName': 'Doe'},
   {u'firstName': u'Jane', u'lastName': u'Doe'}
  ]}}

The Company Search API enables search across company pages. You can get more information from here.

application.search_company(selectors=[{'companies': ['name', 'universal-name', 'website-url']}], params={'keywords': 'apple microsoft'})
# Search URL is https://api.linkedin.com/v1/company-search:(companies:(name,universal-name,website-url))?keywords=apple%20microsoft

{u'companies': {u'_count': 10,
  u'_start': 0,
  u'_total': 1064,
  u'values': [{u'name': u'Netflix',
    u'universalName': u'netflix',
    u'websiteUrl': u'http://netflix.com'},
   {u'name': u'Alliance Data',
    u'universalName': u'alliance-data',
    u'websiteUrl': u'www.alliancedata.com'},
   {u'name': u'GHA Technologies',
    u'universalName': u'gha-technologies',
    u'websiteUrl': u'www.gha-associates.com'},
   {u'name': u'Intelligent Decisions',
    u'universalName': u'intelligent-decisions',
    u'websiteUrl': u'http://www.intelligent.net'},
   {u'name': u'Mindfire Solutions',
    u'universalName': u'mindfire-solutions',
    u'websiteUrl': u'www.mindfiresolutions.com'},
   {u'name': u'Babel Media',
    u'universalName': u'babel-media',
    u'websiteUrl': u'http://www.babelmedia.com/'},
   {u'name': u'Milestone Technologies',
    u'universalName': u'milestone-technologies',
    u'websiteUrl': u'www.milestonepowered.com'},
   {u'name': u'Denali Advanced Integration',
    u'universalName': u'denali-advanced-integration',
    u'websiteUrl': u'www.denaliai.com'},
   {u'name': u'MicroAge',
    u'universalName': u'microage',
    u'websiteUrl': u'www.microage.com'},
   {u'name': u'TRUSTe',
    u'universalName': u'truste',
    u'websiteUrl': u'http://www.truste.com/'}]}}

The Job Search API enables search across LinkedIn's job postings. You can get more information from here.

application.search_job(selectors=[{'jobs': ['id', 'customer-job-code', 'posting-date']}], params={'title': 'python', 'count': 2})
{u'jobs': {u'_count': 2,
  u'_start': 0,
  u'_total': 206747,
  u'values': [{u'customerJobCode': u'0006YT23WQ',
    u'id': 5174636,
    u'postingDate': {u'day': 21, u'month': 3, u'year': 2013}},
   {u'customerJobCode': u'00023CCVC2',
    u'id': 5174634,
    u'postingDate': {u'day': 21, u'month': 3, u'year': 2013}}]}}

Group API

The Groups API provides rich access to read and interact with LinkedIn’s groups functionality. You can get more information from here. By the help of the interface, you can fetch group details, get your group memberships as well as your posts for a specific group which you are a member of.

application.get_group(41001)
{u'id': u'41001', u'name': u'Object Oriented Programming'}

application.get_memberships(params={'count': 20})
{u'_total': 1,
 u'values': [{u'_key': u'25827',
   u'group': {u'id': u'25827', u'name': u'Python Community'},
   u'membershipState': {u'code': u'member'}}]}

application.get_posts(41001)

application.get_post_comments(
    %POST_ID%,
    selectors=[
        {"creator": ["first-name", "last-name"]},
        "creation-timestamp",
        "text"
    ],
    params={"start": 0, "count": 20}
) 

You can also submit a new post into a specific group.

title = 'Scala for the Impatient'
summary = 'A new book has been published'
submitted_url = 'http://horstmann.com/scala/'
submitted_image_url = 'http://horstmann.com/scala/images/cover.png'
description = 'It is a great book for the keen beginners. Check it out!'

application.submit_group_post(41001, title, summary, submitted_url, submitted_image_url, description)

Company API

The Company API:

  • Retrieves and displays one or more company profiles based on the company ID or universal name.
  • Returns basic company profile data, such as name, website, and industry.
  • Returns handles to additional company content, such as RSS stream and Twitter feed.

You can query a company with either its ID or Universal Name. For more information, you can check out the documentation here.

application.get_companies(company_ids=[1035], universal_names=['apple'], selectors=['name'], params={'is-company-admin': 'true'})
# 1035 is Microsoft
# The URL is as follows: https://api.linkedin.com/v1/companies::(1035,universal-name=apple)?is-company-admin=true

{u'_total': 2,
 u'values': [{u'_key': u'1035', u'name': u'Microsoft'},
  {u'_key': u'universal-name=apple', u'name': u'Apple'}]}

# Get the latest updates about Microsoft
application.get_company_updates(1035, params={'count': 2})
{u'_count': 2,
 u'_start': 0,
 u'_total': 58,
 u'values': [{u'isCommentable': True,
   u'isLikable': True,
   u'isLiked': False,
   u'numLikes': 0,
   u'timestamp': 1363855486620,
   u'updateComments': {u'_total': 0},
   u'updateContent': {u'company': {u'id': 1035, u'name': u'Microsoft'},
    u'companyJobUpdate': {u'action': {u'code': u'created'},
     u'job': {u'company': {u'id': 1035, u'name': u'Microsoft'},
      u'description': u'Job Category: SalesLocation: Sacramento, CA, USJob ID: 812346-106756Division: Retail StoresStore...',
      u'id': 5173319,
      u'locationDescription': u'Sacramento, CA, US',
      u'position': {u'title': u'Store Manager, Specialty Store'},
      u'siteJobRequest': {u'url': u'http://www.linkedin.com/jobs?viewJob=&jobId=5173319'}}}},
   u'updateKey': u'UNIU-c1035-5720424522989961216-FOLLOW_CMPY',
   u'updateType': u'CMPY'},
  {u'isCommentable': True,
   u'isLikable': True,
   u'isLiked': False,
   u'numLikes': 0,
   u'timestamp': 1363855486617,
   u'updateComments': {u'_total': 0},
   u'updateContent': {u'company': {u'id': 1035, u'name': u'Microsoft'},
    u'companyJobUpdate': {u'action': {u'code': u'created'},
     u'job': {u'company': {u'id': 1035, u'name': u'Microsoft'},
      u'description': u'Job Category: Software Engineering: TestLocation: Redmond, WA, USJob ID: 794953-81760Division:...',
      u'id': 5173313,
      u'locationDescription': u'Redmond, WA, US',
      u'position': {u'title': u'Software Development Engineer in Test, Senior-IEB-MSCIS (794953)'},
      u'siteJobRequest': {u'url': u'http://www.linkedin.com/jobs?viewJob=&jobId=5173313'}}}},
   u'updateKey': u'UNIU-c1035-5720424522977378304-FOLLOW_CMPY',
   u'updateType': u'CMPY'}]}

You can follow or unfollow a specific company as well.

application.follow_company(1035)
True

application.unfollow_company(1035)
True

Job API

The Jobs APIs provide access to view jobs and job data. You can get more information from its documentation.

application.get_job(job_id=5174636)
{u'active': True,
 u'company': {u'id': 2329, u'name': u'Schneider Electric'},
 u'descriptionSnippet': u"The Industrial Accounts Sales Manager is a quota carrying senior sales position principally responsible for generating new sales and growing company's share of wallet within the industrial business, contracting business and consulting engineering business. The primary objective is to build and establish strong and lasting relationships with technical teams and at executive level within specific in",
 u'id': 5174636,
 u'position': {u'title': u'Industrial Accounts Sales Manager'},
 u'postingTimestamp': 1363860033000}

You can also fetch you job bookmarks.

application.get_job_bookmarks()
{u'_total': 0}

Share API

Network updates serve as one of the core experiences on LinkedIn, giving users the ability to share rich content to their professional network. You can get more information from here.

application.submit_share('Posting from the API using JSON', 'A title for your share', None, 'http://www.linkedin.com', 'http://d.pr/3OWS')
{'updateKey': u'UNIU-8219502-5705061301949063168-SHARE'
 'updateURL': 'http://www.linkedin.com/updates?discuss=&amp;scope=8219502&amp;stype=M&amp;topic=5705061301949063168&amp;type=U&amp;a=aovi'}

Network API

The Get Network Updates API returns the users network updates, which is the LinkedIn term for the user's feed. This call returns most of what shows up in the middle column of the LinkedIn.com home page, either for the member or the member's connections. You can get more information from here.

There are many network update types. You can look at them by importing NETWORK_UPDATES enumeration.

from linkedin.linkedin import NETWORK_UPDATES
print NETWORK_UPDATES.enums
{'APPLICATION': 'APPS',
 'CHANGED_PROFILE': 'PRFU',
 'COMPANY': 'CMPY',
 'CONNECTION': 'CONN',
 'EXTENDED_PROFILE': 'PRFX',
 'GROUP': 'JGRP',
 'JOB': 'JOBS',
 'PICTURE': 'PICT',
 'SHARED': 'SHAR',
 'VIRAL': 'VIRL'}

update_types = (NETWORK_UPDATES.CONNECTION, NETWORK_UPDATES.PICTURE)
application.get_network_updates(update_types)

{u'_total': 1,
 u'values': [{u'isCommentable': True,
   u'isLikable': True,
   u'isLiked': False,
   u'numLikes': 0,
   u'timestamp': 1363470126509,
   u'updateComments': {u'_total': 0},
   u'updateContent': {u'person': {u'apiStandardProfileRequest': {u'headers': {u'_total': 1,
       u'values': [{u'name': u'x-li-auth-token', u'value': u'name:Egbj'}]},
      u'url': u'http://api.linkedin.com/v1/people/COjFALsKDP'},
     u'firstName': u'ozgur',
     u'headline': u'This is my headline',
     u'id': u'COjFALsKDP',
     u'lastName': u'vatansever',
     u'siteStandardProfileRequest': {u'url': u'http://www.linkedin.com/profile/view?id=46113651&authType=name&authToken=Egbj&trk=api*a101945*s101945*'}}},
   u'updateKey': u'UNIU-46113651-5718808205493026816-SHARE',
   u'updateType': u'SHAR'}]}

Invitation API

The Invitation API allows your users to invite people they find in your application to their LinkedIn network. You can get more information from here.

from linkedin.models import LinkedInRecipient, LinkedInInvitation
recipient = LinkedInRecipient(None, 'john.doe@python.org', 'John', 'Doe')
print recipient.json
{'person': {'_path': '/people/email=john.doe@python.org',
  'first-name': 'John',
  'last-name': 'Doe'}}

invitation = LinkedInInvitation('Hello John', "What's up? Can I add you as a friend?", (recipient,), 'friend')
print invitation.json
{'body': "What's up? Can I add you as a friend?",
 'item-content': {'invitation-request': {'connect-type': 'friend'}},
 'recipients': {'values': [{'person': {'_path': '/people/email=john.doe@python.org',
     'first-name': 'John',
     'last-name': 'Doe'}}]},
 'subject': 'Hello John'}

application.send_invitation(invitation)
True

Throttle Limits

LinkedIn API keys are throttled by default. You should take a look at the Throttle Limits Documentation to get more information about it.

Author: ozgur
Source Code: https://github.com/ozgur/python-linkedin
License: MIT license

#python #linkedin #api 

Python LinkedIn: Python Interface to the LinkedIn API
Veronica  Roob

Veronica Roob

1652325720

Awesome PHP: Authentication and Authorization

Authentication and Authorization

Libraries for implementing user authentication and authorization.

Author: ziadoz
Source Code: https://github.com/ziadoz/awesome-php
License: WTFPL License

#php #authentication #authorization 

Awesome PHP: Authentication and Authorization
Coding  Life

Coding Life

1650854537

How to Implementing Token and Role Base Authentication Using Spring Boot, JWT & MySQL

Let's understand, how to implement token and role base authentication mechanism using spring security, jwt and mysql database. In this session, we are going to build a real time application to perform jwt token and role based authentication mechanism.

In this session, I have discussed following points.
1. What is authentication and authorization in an application?
2. How to implement token and role base authentication

Here're links to git repo
1. jwt-youtube (Spring Boot)
https://github.com/team-learn-programming-yourself/jwt-youtube 

2. jwt-youtube-ui (Angular)
https://github.com/team-learn-programming-yourself/jwt-youtube-ui 

Subscribe: https://www.youtube.com/c/LearnProgrammingYourself/featured 

#springsecurity  #jwt  #authentication  #authorization #mysql 

How to Implementing Token and Role Base Authentication Using Spring Boot, JWT & MySQL
Desmond  Gerber

Desmond Gerber

1646597760

Node-casbin: an Authorization Library That Supports Access Control

Node-Casbin

💖 Looking for an open-source identity and access management solution like Okta, Auth0, Keycloak ? Learn more about: Casdoor

casdoor

News: still worry about how to write the correct node-casbin policy? Casbin online editor is coming to help!

casbin Logo

node-casbin is a powerful and efficient open-source access control library for Node.JS projects. It provides support for enforcing authorization based on various access control models.

All the languages supported by Casbin:

golangjavanodejsphp
CasbinjCasbinnode-CasbinPHP-Casbin
production-readyproduction-readyproduction-readyproduction-ready
pythondotnetc++rust
PyCasbinCasbin.NETCasbin-CPPCasbin-RS
production-readyproduction-readybeta-testproduction-ready

Documentation

https://casbin.org/docs/en/overview

Installation

# NPM
npm install casbin --save

# Yarn
yarn add casbin

Get started

New a node-casbin enforcer with a model file and a policy file, see Model section for details:

// For Node.js:
const { newEnforcer } = require('casbin');
// For browser:
// import { newEnforcer } from 'casbin';

const enforcer = await newEnforcer('basic_model.conf', 'basic_policy.csv');

Note: you can also initialize an enforcer with policy in DB instead of file, see Persistence section for details.

Add an enforcement hook into your code right before the access happens:

const sub = 'alice'; // the user that wants to access a resource.
const obj = 'data1'; // the resource that is going to be accessed.
const act = 'read'; // the operation that the user performs on the resource.

// Async:
const res = await enforcer.enforce(sub, obj, act);
// Sync:
// const res = enforcer.enforceSync(sub, obj, act);

if (res) {
  // permit alice to read data1
} else {
  // deny the request, show an error
}

Besides the static policy file, node-casbin also provides API for permission management at run-time. For example, You can get all the roles assigned to a user as below:

const roles = await enforcer.getRolesForUser('alice');

See Policy management APIs for more usage.

Policy management

Casbin provides two sets of APIs to manage permissions:

  • Management API: the primitive API that provides full support for Casbin policy management.
  • RBAC API: a more friendly API for RBAC. This API is a subset of Management API. The RBAC users could use this API to simplify the code.

Official Model

https://casbin.org/docs/en/supported-models

Policy persistence

https://casbin.org/docs/en/adapters

Policy consistence between multiple nodes

https://casbin.org/docs/en/watchers

Role manager

https://casbin.org/docs/en/role-managers

Author: Casbin
Source Code: https://github.com/casbin/node-casbin 
License: Apache-2.0 License

#node #javascript #auth #authorization 

Node-casbin: an Authorization Library That Supports Access Control
Desmond  Gerber

Desmond Gerber

1646589660

CASL: Isomorphic Authorization for UI and API

STOP WAR IN UKRAINE!

All the truth about war in UKRAINE

CASL (pronounced /ˈkæsəl/, like castle) is an isomorphic authorization JavaScript library which restricts what resources a given user is allowed to access. It's designed to be incrementally adoptable and can easily scale between a simple claim based and fully featured subject and attribute based authorization. It makes it easy to manage and share permissions across UI components, API services, and database queries.

Heavily inspired by cancan.

Features

  • Versatile
    An incrementally adoptable and can easily scale between a simple claim based and fully featured subject and attribute based authorization.
  • Isomorphic
    Can be used on frontend and backend and complementary packages make integration with major Frontend Frameworks and Backend ORMs effortless
  • TypeSafe
    Written in TypeScript, what makes your apps safer and developer experience more enjoyable
  • Tree shakable
    The core is only 6KB mingzipped and can be even smaller!
  • Declarative
    Thanks to declarative rules, you can serialize and share permissions between UI and API or microservices

Ecosystem

ProjectStatusDescriptionSupported envinronemnts
@casl/ability@casl/ability-statusCASL's core packagenodejs 8+ and ES5 compatible browsers (IE 9+)
@casl/mongoose@casl/mongoose-statusintegration with Mongoosenodejs 8+
@casl/prisma@casl/prisma-statusintegration with Prismanodejs 12+
@casl/angular@casl/angular-statusintegration with AngularIE 9+
@casl/react@casl/react-statusintegration with ReactIE 9+
@casl/vue@casl/vue-statusintegration with VueIE 11+ (uses WeakMap)
@casl/aurelia@casl/aurelia-statusintegration with AureliaIE 11+ (uses WeakMap)

Documentation

A lot of detailed information about CASL, integrations and examples can be found in documentation.

Have a question?

Ask it in chat or on stackoverflow. Please don't ask questions in issues, the issue list of this repo is exclusively for bug reports and feature requests. Questions in the issue list may be closed immediately without answers.

CASL crash course

CASL operates on the abilities level, that is what a user can actually do in the application. An ability itself depends on the 4 parameters (last 3 are optional):

  1. User Action
    Describes what user can actually do in the app. User action is a word (usually a verb) which depends on the business logic (e.g., prolong, read). Very often it will be a list of words from CRUD - create, read, update and delete.
  2. Subject
    The subject or subject type which you want to check user action on. Usually this is a business (or domain) entity name (e.g., Subscription, BlogPost, User).
  3. Conditions
    An object or function which restricts user action only to matched subjects. This is useful when you need to give a permission on resources created by a user (e.g., to allow user to update and delete own BlogPost)
  4. Fields
    Can be used to restrict user action only to matched subject's fields (e.g., to allow moderator to update hidden field of BlogPost but not update description or title)

Using CASL you can describe abilities using regular and inverted rules. Let's see how

Note: all the examples below will be written in TypeScript but CASL can be used in similar way in ES6+ and Nodejs environments.

1. Define Abilities

Lets define Ability for a blog website where visitors:

  • can read blog posts
  • can manage (i.e., do anything) own posts
  • cannot delete a post if it was created more than a day ago
import { AbilityBuilder, Ability } from '@casl/ability'
import { User } from '../models'; // application specific interfaces

/**
 * @param user contains details about logged in user: its id, name, email, etc
 */
function defineAbilitiesFor(user: User) {
  const { can, cannot, rules } = new AbilityBuilder(Ability);

  // can read blog posts
  can('read', 'BlogPost');
  // can manage (i.e., do anything) own posts
  can('manage', 'BlogPost', { author: user.id });
  // cannot delete a post if it was created more than a day ago
  cannot('delete', 'BlogPost', {
    createdAt: { $lt: Date.now() - 24 * 60 * 60 * 1000 }
  });

  return new Ability(rules);
});

Do you see how easily business requirements were translated into CASL's rules?

Note: you can use class instead of string as a subject type (e.g., can('read', BlogPost))

And yes, Ability class allow you to use some MongoDB operators to define conditions. Don't worry if you don't know MongoDB, it's not required and explained in details in Defining Abilities

2. Check Abilities

Later on you can check abilities by using can and cannot methods of Ability instance.

// in the same file as above
import { ForbiddenError } from '@casl/ability';

const user = getLoggedInUser(); // app specific function
const ability = defineAbilitiesFor(user);

class BlogPost { // business entity
  constructor(props) {
    Object.assign(this, props);
  }
}

// true if ability allows to read at least one Post
ability.can('read', 'BlogPost');
// the same as
ability.can('read', BlogPost);

// true, if user is the author of the blog post
ability.can('manage', new BlogPost({ author: user.id }));

// true if there is no ability to read this particular blog post
const ONE_DAY = 24 * 60 * 60 * 1000;
const postCreatedNow = new BlogPost({ createdAt: new Date() });
const postCreatedAWeekAgo = new BlogPost({ createdAt: new Date(Date.now() - 7 * ONE_DAY) });

// can delete if it's created less than a day ago
ability.can('delete', postCreatedNow); // true
ability.can('delete', postCreatedAWeekAgo); // false

// you can even throw an error if there is a missed ability
ForbiddenError.from(ability).throwUnlessCan('delete', postCreatedAWeekAgo);

Of course, you are not restricted to use only class instances in order to check permissions on objects. See Introduction for the detailed explanation.

3. Database integration

CASL has a complementary package @casl/mongoose which provides easy integration with MongoDB and mongoose.

import { AbilityBuilder } from '@casl/ability';
import { accessibleRecordsPlugin } from '@casl/mongoose';
import mongoose from 'mongoose';

mongoose.plugin(accessibleRecordsPlugin);

const user = getUserLoggedInUser(); // app specific function

const ability = defineAbilitiesFor(user);
const BlogPost = mongoose.model('BlogPost', mongoose.Schema({
  title: String,
  author: mongoose.Types.ObjectId,
  content: String,
  createdAt: Date,
  hidden: { type: Boolean, default: false }
}))

// returns mongoose Query, so you can chain it with other conditions
const posts = await BlogPost.accessibleBy(ability).where({ hidden: false });

// you can also call it on existing query to enforce permissions
const hiddenPosts = await BlogPost.find({ hidden: true }).accessibleBy(ability);

// you can even pass the action as a 2nd parameter. By default action is "read"
const updatablePosts = await BlogPost.accessibleBy(ability, 'update');

See Database integration for details.

4. Advanced usage

CASL is incrementally adoptable, that means you can start your project with simple claim (or action) based authorization and evolve it later, when your app functionality evolves.

CASL is composable, that means you can implement alternative conditions matching (e.g., based on joi, ajv or pure functions) and field matching (e.g., to support alternative syntax in fields like addresses.*.street or addresses[0].street) logic.

See Advanced usage for details.

5. Examples

Looking for examples? Check CASL examples repository.

Want to help?

Want to file a bug, contribute some code, or improve documentation? Excellent! Read up on guidelines for contributing.

If you'd like to help us sustain our community and project, consider to become a financial contributor on Open Collective

Author: Stalniy
Source Code: https://github.com/stalniy/casl 
License: MIT License

#node #authorization #javascript 

CASL: Isomorphic Authorization for UI and API
Micheal  Emard

Micheal Emard

1644514920

How to Make API Authorization for Movie Resource with Laravel 8 API

Hello friends, in this video we are going to make Authorization for Movie Resource.

#authorization #api #laravel 

How to Make API Authorization for Movie Resource with Laravel 8 API

Writing Safe and Secure Apps using Firebase and Firebase Authentication

What is Firebase Authentication? | Better Safe than Sorry

What's the difference between authorization and authentication? How can you protect your backend system and your users' data? What's a trusted environment, and why is it safe to access your app's data directly from the client? Join the Firebase team to learn all of this and more in Better Safe than Sorry, our new show about writing safe and secure apps using Firebase and Firebase Authentication.

Chapters:
0:00 Introduction
1:17 Firebase architecture 
2:55 Protecting access
5:51 Authentication
9:24 Authorization 
11:37 Defense against attackers
12:21 Recap

#firebase #developer #security #authentication #authorization

Writing Safe and Secure Apps using Firebase and Firebase Authentication
Web  Dev

Web Dev

1634096852

How to Authorize User Roles and Permissions in Node & Express

Learn how to authorize user roles and permissions in this Node.js & Express authorization tutorial. We'll start by learning the difference between authentication and authorization. Then we'll build middleware for our REST API that authorizes specific roles for data endpoint access.

🔗 Starter Source Code: https://github.com/gitdagray/express_jwt 

🔗 Completed Source Code: https://github.com/gitdagray/express_user_roles 

How to Authorize User Roles and Permissions | Node.js & Express Authorization Tutorial

(00:00) Intro
(00:05) Welcome
(00:15) Authentication vs Authorization
(01:44) Configure the User Roles
(02:53) Add roles to the user data model
(04:59) Add a user role at registration
(06:01) Add user roles to access token at authentication
(09:09) Add user roles to access token when refreshed
(10:28) Update the verifyJWT middleware to include roles
(13:18) Create the verifyRoles middleware
(19:19) Add the verifyRoles middleware to routes
(22:04) Test routes with Thunder Client
(27:14) A quick note on Thunder Client

📚 JWT References:
Intro to JSON Web Tokens: https://jwt.io/introduction 
NPM jsonwebtoken package: https://www.npmjs.com/package/jsonwebtoken 
NPM cookie-parser package: https://www.npmjs.com/package/cookie-parser 
Deleting Cookies: http://expressjs.com/en/api.html#res.clearCookie 
Cross-Site Scripting (XSS): https://owasp.org/www-community/attacks/xss/ 
Cross-Site Request Forgery (CSRF): https://owasp.org/www-community/attacks/csrf 
REST Security Cheat Sheet: https://cheatsheetseries.owasp.org/cheatsheets/REST_Security_Cheat_Sheet.html 

📚 Login References:
Bcrypt: https://www.npmjs.com/package/bcrypt 
How to Safely Store a Password: https://codahale.com/how-to-safely-store-a-password/ 
MDN: HTTP Response Status Codes: https://developer.mozilla.org/en-US/docs/Web/HTTP/Status 

📚 More References:
Node.js Official site: https://nodejs.org 
NPM Official site: https://www.npmjs.com/ 
Express JS Official site: https://expressjs.com/ 
MDN CORS: https://developer.mozilla.org/en-US/docs/Web/HTTP/CORS 
NPM CORS: https://www.npmjs.com/package/cors 

#node #authorization

How to Authorize User Roles and Permissions in Node & Express
Aiyana  Miller

Aiyana Miller

1627893180

An Introduction to Google Authenticator Time-Based Authorization in PHP

If you are excited about to add a cool and secure time-based authorization in your existing PHP project, then this video series is exclusively for you.
In this video series, we add a custom time-based authorization which can be deciphered by Google Authenticator.

#php #authorization #google

An Introduction to Google Authenticator Time-Based Authorization in PHP

Voters in Symphony 3 (Authorization)

What’s going guys it’s been a while since my last video but i’m back at it (if nothing pops up), in this video i’m going over the basic usage of voters in symfony 3 to check for user permissions, the video is kind of long because i went over the creation of the bundle as well so feel free to skip to whatever part you’re interested in.

Timestamps:
Creating the blog bundle and stuff : 3:28 .
Basic usage of voters: 13:44 or something like that .

#voters #symphony #authorization

Voters in Symphony 3 (Authorization)