All Projects → Firesphere → silverstripe-graphql-jwt

Firesphere / silverstripe-graphql-jwt

Licence: other
JWT Authentication for GraphQL

Programming Languages

PHP
23972 projects - #3 most used programming language

Projects that are alternatives of or similar to silverstripe-graphql-jwt

Apiproject
[https://www.sofineday.com], golang项目开发脚手架,集成最佳实践(gin+gorm+go-redis+mongo+cors+jwt+json日志库zap(支持日志收集到kafka或mongo)+消息队列kafka+微信支付宝支付gopay+api加密+api反向代理+go modules依赖管理+headless爬虫chromedp+makefile+二进制压缩+livereload热加载)
Stars: ✭ 124 (+629.41%)
Mutual labels:  cors, headless
lua-resty-cors
It's the implement of CORS on OpenResty
Stars: ✭ 53 (+211.76%)
Mutual labels:  cors
react-kirby-starter
React boilerplate with headless Kirby API [WIP]
Stars: ✭ 23 (+35.29%)
Mutual labels:  headless
shopify-next.js-tailwind
Learn the Shopify + Next.js + Tailwind CSS Stack! SWR, Hydrogen, + more
Stars: ✭ 227 (+1235.29%)
Mutual labels:  headless
headless-chrome-alpine
A Docker container running headless Chrome
Stars: ✭ 26 (+52.94%)
Mutual labels:  headless
dry
Dry is a new template engine and language, and is a superset of Shopify's Liquid, with first-class support for advanced inheritance features, and more. From the creators of Enquirer, Assemble, Remarkable, and Micromatch.
Stars: ✭ 66 (+288.24%)
Mutual labels:  headless
contentjet-api
Headless API-first content management system
Stars: ✭ 95 (+458.82%)
Mutual labels:  headless
horse-cors
No description or website provided.
Stars: ✭ 31 (+82.35%)
Mutual labels:  cors
hubble-frontend-pwa
E-Commerce PWA Frontend
Stars: ✭ 43 (+152.94%)
Mutual labels:  headless
startup-starter-kit
The Structured Content Startup Starter Kit
Stars: ✭ 42 (+147.06%)
Mutual labels:  headless
node-typescript-starter
REST API using Node with typescript, KOA framework. TypeORM for SQL. Middlewares JWT (auth), CORS, Winston Logger, Error, Response
Stars: ✭ 19 (+11.76%)
Mutual labels:  cors
ubuntu-vnc-xfce-g3
Headless Ubuntu/Xfce containers with VNC/noVNC (Generation 3)
Stars: ✭ 83 (+388.24%)
Mutual labels:  headless
ubuntu-vnc-xfce-chromium
Retired. Headless Ubuntu/Xfce container with VNC/noVNC and Chromium (Generation 1)
Stars: ✭ 20 (+17.65%)
Mutual labels:  headless
keycloak-spring-boot-rest-angular-demo
Demo for configuring Keycloak authentication for a spring-boot rest service and AngularJs web client
Stars: ✭ 24 (+41.18%)
Mutual labels:  cors
laravel-storyblok
Make Laravel and Storyblok work together beautifully.
Stars: ✭ 45 (+164.71%)
Mutual labels:  headless
terraform-aws-api-gateway-enable-cors
Easily add an OPTIONS method to an API Gateway resource to enable CORS
Stars: ✭ 56 (+229.41%)
Mutual labels:  cors
laravel-api-boilerplate-passport
An API Boilerplate to create a ready-to-use REST API in seconds.
Stars: ✭ 20 (+17.65%)
Mutual labels:  cors
poop
Firefox extension that prevents sending Origin headers when they are least likely to be necessary, to protect your privacy.
Stars: ✭ 36 (+111.76%)
Mutual labels:  cors
nuxt-ghost
Easy Ghost content API integration with Nuxt.js.
Stars: ✭ 27 (+58.82%)
Mutual labels:  headless
koa-restful-boilerplate
A boilerplate for koa2 RESTful API development
Stars: ✭ 31 (+82.35%)
Mutual labels:  cors

CircleCI Scrutinizer Code Quality codecov

Gitstore

GraphQL JSON Web Token authenticator

This module provides a JWT-interface for creating JSON Web Tokens for authentication.

Installation

composer require firesphere/graphql-jwt

The default config is available in _config\config.yml.

In order to securely process and store data via JWT, you need to set a secret key in your .env file:

JWT_SIGNER_KEY="[your secret key]"

A quick way to generate a secure random value value for JWT_SIGNER_KEY is through a PHP CLI command:

php -r 'echo substr(base64_encode(random_bytes(64)), 0, 64) . "\n";'

You can also use public/private key files.

JWT_SIGNER_KEY="./path/to/private.key"
JWT_PUBLIC_KEY="./path/to/public.key"

Note: Relative paths will be relative to your BASE_PATH (prefixed with ./)

Currently, only RSA keys are supported. ECDSA is not supported. The keys in the test-folder are generated by an online RSA key generator.

The signer key for HMAC can be of any length (keys longer than B bytes are first hashed using H). However, less than L bytes is strongly discouraged as it would decrease the security strength of the function.. Thus, for SHA-256 the signer key should be between 16 and 64 bytes in length.

The keys in tests/keys should not be trusted!

Configuration

Since admin/graphql is reserved exclusively for CMS graphql access, it will be necessary for you to register a custom schema for your front-end application, and apply the provided queries and mutations to that.

For example, given you've decided to create a schema named frontend at the url /api

---
Name: my-graphql-schema
---
SilverStripe\GraphQL\Manager:
  schemas:
    frontend:
      types:
        MemberToken: 'Firesphere\GraphQLJWT\Types\MemberTokenTypeCreator'
        Member: 'Firesphere\GraphQLJWT\Types\MemberTypeCreator'
      mutations:
        createToken: 'Firesphere\GraphQLJWT\Mutations\CreateTokenMutationCreator'
        refreshToken: 'Firesphere\GraphQLJWT\Mutations\RefreshTokenMutationCreator'
      queries:
        validateToken: 'Firesphere\GraphQLJWT\Queries\ValidateTokenQueryCreator'
---
Name: my-graphql-injections
---
SilverStripe\Core\Injector\Injector:
  SilverStripe\GraphQL\Manager.frontend:
    class: SilverStripe\GraphQL\Manager
    constructor:
      identifier: frontend
  SilverStripe\GraphQL\Controller.frontend:
    class: SilverStripe\GraphQL\Controller
    constructor:
      manager: '%$SilverStripe\GraphQL\Manager.frontend'
---
Name: my-graphql-routes
---
SilverStripe\Control\Director:
  rules:
    api:
      Controller: '%$SilverStripe\GraphQL\Controller.frontend'
      Stage: Live

Log in

To generate a JWT token, send a login request to the createToken mutator:

mutation {
  createToken(Email: "admin", Password: "password") {
    Token, // ...request or you won't have a token
    ID,
    FirstName,
    Surname
  }
}

Validate token

If you have an app and want to validate your token, you can address the validateToken method:

query validateToken {
  validateToken {
    Valid
    Message
    Code
  }
}

It only needs to call the endpoint. The token should be in the header, via your middleware for the request, as a Authorization: Bearer [token]. If the token is valid, you'll get a response like this:

{
  "data": {
    "validateToken": {
      "Valid": true,
      "Message": "",
      "Code": 200,
      "__typename": "ValidateToken"
    }
  }
}

If the token is invalid, Valid will be false.

Anonymous tokens

Although not advised, it's possible to use anonymous tokens. When using an anonymous authenticator, SilverStripe will generate a default database record in the Members table with the Email anonymous and no permissions by default.

To enable anonymous tokens, add the following to your configuration .yml:

SilverStripe\Core\Injector\Injector:
  Firesphere\GraphQLJWT\Mutations\CreateTokenMutationCreator:
    properties:
      CustomAuthenticators:
        - Firesphere\GraphQLJWT\Authentication\AnonymousUserAuthenticator

You can then create an anonymous login with the below query.

mutation {
  createToken(Email: "anonymous") {
    Token
  }
}

Note: If the default anonymous authenticator doesn't suit your purposes, you can inject any other core SilverStripe authenticator into CustomAuthenticators.

Warning: The default AnonymousUserAuthenticator is not appropriate for general usage, so don't register this under the core Security class!

Enable CORS

To use JWT, CORS needs to be enabled. This can be done by adding the following to your configuration .yml:

SilverStripe\GraphQL\Controller:
  cors:
    Enabled: true
    Allow-Origin: "*"
    Allow-Headers: "Authorization, Content-Type"
    Allow-Methods: "GET, POST, OPTIONS"
    Max-Age: 86400 # ...in seconds

Usage

After logging in, you will receive a token which can be used for further requests. This token should be in the header of the request with the Bearer as signature:

Authorization: Bearer [token]

Prefix

A prefix can be optionally associated with the unique identifier of a JWT record. This can make it easier to distinguish JWT records created in different contexts, e.g. on a specific domain or environment type. It is not required for security purposes.

JWT_PREFIX="[your secret prefix]"

Security

Currently, the default method for encrypting the JWT is with SHA256. JWT is signed with multiple factors; including the host, audience (app/remote user), a secret key and a timeframe within which the token is valid. Only one device can be logged in at the time.

Supported services

By default, JWT only supports login. As it's tokens can not be disabled, nor used for password changes or resets.

Caveats

When using php under CGI/FastCGI mode with Apache, the Authorization header might not work correctly, see issue#15. The workaround is simple, just add SetEnvIf Authorization .+ HTTP_AUTHORIZATION=$0 in your .htaccess file (refer).

Examples

A Postman collection can be found in the extra folder.

License

This module is published under BSD 3-clause license, although these are not in the actual classes, the license does apply:

http://www.opensource.org/licenses/BSD-3-Clause

Copyright (c) 2012-NOW(), Simon "Firesphere" Erkelens

All rights reserved.

Redistribution and use in source and binary forms, with or without modification, are permitted provided that the following conditions are met:

- Redistributions of source code must retain the above copyright notice, this list of conditions and the following disclaimer.

- Redistributions in binary form must reproduce the above copyright notice, this list of conditions and the following disclaimer in the documentation and/or other materials provided with the distribution.

THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.

Cow?

Of course!

               /( ,,,,, )\
              _\,;;;;;;;,/_
           .-"; ;;;;;;;;; ;"-.
           '.__/`_ / \ _`\__.'
              | (')| |(') |
              | .--' '--. |
              |/ o     o \|
              |           |
             / \ _..=.._ / \
            /:. '._____.'   \
           ;::'    / \      .;
           |     _|_ _|_   ::|
         .-|     '==o=='    '|-.
        /  |  . /       \    |  \
        |  | ::|         |   | .|
        |  (  ')         (.  )::|
        |: |   |;  U U  ;|:: | `|
        |' |   | \ U U / |'  |  |
        ##V|   |_/`"""`\_|   |V##
           ##V##         ##V##
Note that the project description data, including the texts, logos, images, and/or trademarks, for each open source project belongs to its rightful owner. If you wish to add or remove any projects, please contact us at [email protected].