承接 firesphere/graphql-jwt 相关项目开发

从需求分析到上线部署,全程专人跟进,保证项目质量与交付效率

邮箱:yvsm@zunyunkeji.com | QQ:316430983 | 微信:yvsm316

firesphere/graphql-jwt

Composer 安装命令:

composer require firesphere/graphql-jwt

包简介

JWT Authentication for GraphQL

README 文档

README

CircleCI Scrutinizer Code Quality codecov

License

GPL v3 or later

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.

Cow?

Of course!

               /( ,,,,, )\
              _\,;;;;;;;,/_
           .-"; ;;;;;;;;; ;"-.
           '.__/`_ / \ _`\__.'
              | (')| |(') |
              | .--' '--. |
              |/ o     o \|
              |           |
             / \ _..=.._ / \
            /:. '._____.'   \
           ;::'    / \      .;
           |     _|_ _|_   ::|
         .-|     '==o=='    '|-.
        /  |  . /       \    |  \
        |  | ::|         |   | .|
        |  (  ')         (.  )::|
        |: |   |;  U U  ;|:: | `|
        |' |   | \ U U / |'  |  |
        ##V|   |_/`"""`\_|   |V##
           ##V##         ##V##

firesphere/graphql-jwt 适用场景与选型建议

firesphere/graphql-jwt 是一款 基于 PHP 开发的 Composer 扩展包,目前已累计 6.54k 次下载、GitHub Stars 达 19, 最近一次更新时间为 2017 年 11 月 14 日, 在 PHP 生态内属于活跃度较高的组件。

我们在过去多个企业项目中使用过 firesphere/graphql-jwt 或与其功能相近的方案,如果你在选型或落地过程中遇到问题,例如 版本兼容、二次改造、私有化封装、与内部系统对接、生产 BUG 排查,欢迎联系我们协助评估。

围绕 firesphere/graphql-jwt 我们能提供哪些服务?
定制开发 / 二次开发

基于 firesphere/graphql-jwt 在你已有业务上做功能扩展、字段裁剪、UI 适配、与内部账号 / 权限 / 日志系统的深度对接。

BUG 修复 & 性能优化

线上偶发问题、内存泄漏、慢查询、并发异常等排查修复;针对高流量场景做缓存、队列、索引层面的调优。

项目外包 & 长期维护

承接完整的项目从需求 → 设计 → 开发 → 上线 → 长期运维;也可按月提供技术保姆服务。

yvsm@zunyunkeji.com QQ:316430983 微信:yvsm316 西安尊云信息科技 · 专注 PHP / Go / 分布式系统研发

统计信息

  • 总下载量: 6.54k
  • 月度下载量: 0
  • 日度下载量: 0
  • 收藏数: 19
  • 点击次数: 10
  • 依赖项目数: 0
  • 推荐数: 0

GitHub 信息

  • Stars: 19
  • Watchers: 6
  • Forks: 25
  • 开发语言: PHP

其他信息

  • 授权协议: bsd-3-clause
  • 更新时间: 2017-11-14