当前位置: 首页 > 软件库 > Web应用开发 > Web框架 >

koa-shopify-auth

授权协议 MIT License
开发语言 JavaScript
所属分类 Web应用开发、 Web框架
软件类型 开源软件
地区 不详
投 递 者 唐煜
操作系统 跨平台
开源组织
适用人群 未知
 软件概览

@shopify/koa-shopify-auth

Build Status

Middleware to authenticate a Koa application with Shopify.

Sister module to @shopify/shopify-express, but simplified.

Features you might know from the express module like the webhook middleware and proxy will be presented as their own packages instead.

Warning: versions prior to 3.1.68 vulnerable to reflected XSS

Versions prior to 3.1.68 are vulnerable to a reflected XSS attack. Please update to the latest version to protect your app.

Installation

This package builds upon the Shopify Node Library, so your app will have access to all of the library's features as well as the Koa-specific middlewares this package provides.

$ yarn add @shopify/koa-shopify-auth

Usage

This package exposes shopifyAuth by default, and verifyRequest as a named export. To make it ready for use, you need to initialize the Shopify Library and then use that to initialize this package:

import shopifyAuth, {verifyRequest} from '@shopify/koa-shopify-auth';
import Shopify, {ApiVersion} from '@shopify/shopify-api';

// Initialize the library
Shopify.Context.initialize({
  API_KEY: 'Your API_KEY',
  API_SECRET_KEY: 'Your API_SECRET_KEY',
  SCOPES: ['Your scopes'],
  HOST_NAME: 'Your HOST_NAME (omit the https:// part)',
  API_VERSION: ApiVersion.October20,
  IS_EMBEDDED_APP: true,
  // More information at https://github.com/Shopify/shopify-node-api/blob/main/docs/issues.md#notes-on-session-handling
  SESSION_STORAGE: new Shopify.Session.MemorySessionStorage(),
});

shopifyAuth

Returns an authentication middleware taking up (by default) the routes /auth and /auth/callback.

app.use(
  shopifyAuth({
    // if specified, mounts the routes off of the given path
    // eg. /shopify/auth, /shopify/auth/callback
    // defaults to ''
    prefix: '/shopify',
    // set access mode, default is 'online'
    accessMode: 'offline',
    // callback for when auth is completed
    afterAuth(ctx) {
      const { shop, accessToken } = ctx.state.shopify;

      console.log('We did it!', accessToken);

      ctx.redirect('/');
    },
  }),
);

/auth

This route starts the oauth process. It expects a ?shop parameter and will error out if one is not present. To install it in a store just go to /auth?shop=myStoreSubdomain.

/auth/callback

You should never have to manually go here. This route is purely for shopify to send data back during the oauth process.

verifyRequest

Returns a middleware to verify requests before letting them further in the chain.

Note: if you're using a prefix for shopifyAuth, that prefix needs to be present in the paths for authRoute and fallbackRoute below.

app.use(
  verifyRequest({
    // path to redirect to if verification fails
    // defaults to '/auth'
    authRoute: '/foo/auth',
    // path to redirect to if verification fails and there is no shop on the query
    // defaults to '/auth'
    fallbackRoute: '/install',
    // which access mode is being used
    // defaults to 'online'
    accessMode: 'offline',
    // if false, redirect the user to OAuth. If true, send back a 403 with the following headers:
    //  - X-Shopify-API-Request-Failure-Reauthorize: '1'
    //  - X-Shopify-API-Request-Failure-Reauthorize-Url: '<auth_url_path>'
    // defaults to false
    returnHeader: true,
  }),
);

Migrating from cookie-based authentication to session tokens

Versions prior to v4 of this package used cookies to store session information for your app. However, internet browsers have been moving to block 3rd party cookies, which creates issues for embedded apps.

If you have an app using this package, you can migrate from cookie-based authentication to session tokens by performing a few steps:

  • Upgrade your @shopify/koa-shopify-auth dependency to v4+
  • Update your server as per the Usage instructions to properly initialize the @shopify/shopify-api library
  • If you are using accessMode: 'offline' in shopifyAuth, make sure to pass the same value in verifyRequest
  • Install @shopify/app-bridge-utils in your frontend app
  • In your frontend app, replace fetch calls with authenticatedFetch from App Bridge Utils

Note: the backend steps need to be performed to fully migrate your app to v4, even if your app is not embedded.

You can learn more about session tokens in our authentication tutorial. Go to the frontend changes section under Setup for instructions and examples on how to update your frontend code.

Example app

This example will enable you to quickly set up the backend for a working development app. Please read the Gotchas session below to make sure you are ready for production use.

import 'isomorphic-fetch';

import Koa from 'koa';
import Router from "koa-router";
import shopifyAuth, {verifyRequest} from '@shopify/koa-shopify-auth';
import Shopify, {ApiVersion} from '@shopify/shopify-api';

// Loads the .env file into process.env. This is usually done using actual environment variables in production
import dotenv from "dotenv";
dotenv.config();

const port = parseInt(process.env.PORT, 10) || 8081;

// initializes the library
Shopify.Context.initialize({
  API_KEY: process.env.SHOPIFY_API_KEY,
  API_SECRET_KEY: process.env.SHOPIFY_API_SECRET,
  SCOPES: process.env.SHOPIFY_APP_SCOPES,
  HOST_NAME: process.env.SHOPIFY_APP_URL.replace(/^https:\/\//, ''),
  API_VERSION: ApiVersion.October20,
  IS_EMBEDDED_APP: true,
  // More information at https://github.com/Shopify/shopify-node-api/blob/main/docs/issues.md#notes-on-session-handling
  SESSION_STORAGE: new Shopify.Session.MemorySessionStorage(),
});

// Storing the currently active shops in memory will force them to re-login when your server restarts. You should
// persist this object in your app.
const ACTIVE_SHOPIFY_SHOPS = {};

const app = new Koa();
const router = new Router();
app.keys = [Shopify.Context.API_SECRET_KEY];

// Sets up shopify auth
app.use(
  shopifyAuth({
    async afterAuth(ctx) {
      const { shop, accessToken } = ctx.state.shopify;
      ACTIVE_SHOPIFY_SHOPS[shop] = true;

      // Your app should handle the APP_UNINSTALLED webhook to make sure merchants go through OAuth if they reinstall it
      const response = await Shopify.Webhooks.Registry.register({
        shop,
        accessToken,
        path: "/webhooks",
        topic: "APP_UNINSTALLED",
        webhookHandler: async (topic, shop, body) => delete ACTIVE_SHOPIFY_SHOPS[shop],
      });

      if (!response.success) {
        console.log(
          `Failed to register APP_UNINSTALLED webhook: ${response.result}`
        );
      }

      // Redirect to app with shop parameter upon auth
      ctx.redirect(`/?shop=${shop}`);
    },
  }),
);

router.get("/", async (ctx) => {
  const shop = ctx.query.shop;

  // If this shop hasn't been seen yet, go through OAuth to create a session
  if (ACTIVE_SHOPIFY_SHOPS[shop] === undefined) {
    ctx.redirect(`/auth?shop=${shop}`);
  } else {
    // Load app skeleton. Don't include sensitive information here!
    ctx.body = '��';
  }
});

router.post("/webhooks", async (ctx) => {
  try {
    await Shopify.Webhooks.Registry.process(ctx.req, ctx.res);
    console.log(`Webhook processed, returned status code 200`);
  } catch (error) {
    console.log(`Failed to process webhook: ${error}`);
  }
});

// Everything else must have sessions
router.get("(.*)", verifyRequest(), async (ctx) => {
  // Your application code goes here
});

app.use(router.allowedMethods());
app.use(router.routes());
app.listen(port, () => {
  console.log(`> Ready on http://localhost:${port}`);
});

Gotchas

Session

The provided MemorySessionStorage class may not be scalable for production use. You can implement your own strategy by creating a class that implements a few key methods. Learn more about how the Shopify Library handles sessions.

Testing locally

By default this app requires that you use a myshopify.com host in the shop parameter. You can modify this to test against a local/staging environment via the myShopifyDomain option to shopifyAuth (e.g. myshopify.io).

  • Spring Oauth2-Authorization-Server Opaque token 认证 基于 spring-security-oauth2-authorization-server 0.2.3 如果我们采用 opaque 方式进行token 认证,那我们会这样配置: spring: security: oauth2: resourceserver:

  •   前后端未分离以前,页面都是通过后台来渲染的,能不能访问到页面直接由后台逻辑判断。前后端分离以后,页面的元素由页面本身来控制,所以页面间的路由是由前端来控制了。当然,仅有前端做权限控制是远远不够的,后台还需要对每个接口做验证。   为什么前端做权限控制是不够的呢?因为前端的路由控制仅仅是视觉上的控制,前端可以隐藏某个页面或者某个按钮,但是发送请求的方式还是有很多,完全可以跳过操作页面来发送某个请

  • Kube-apiserver 认证鉴权插件Authenticator和Authorizer 原文链接:https://note.youdao.com/ynoteshare1/index.html?id=9d0b804336ce5f4009d35848bc3acded&type=note 一、初始化入口 cmd/kube-apiserver/app/server.go中的BuildAuthentic

  • Koa集成权限认证中间件之Passport 前言        你还在为koa2的权限管理问题烦恼吗?那么这篇文章你解决的忧愁!!! 对于express框架的权限框架passport大家可能不陌生,但是koa2的权限管理中间件缺很少,尤其是最2.0版本以上Koa,其生态目前完全出于一个起步阶段,对比目前express大量稳定可用的中间件,的确是有许多的不足。但是开源的力量永远是最强大的,只要有需求

  • 需求:远程服务使用HTTPS连接,并需要Basic Auth认证 在配置类里面注入一个自定义OkHttpClient @Value("${sign.httpName}") private String rtspName; @Value("${sign.httpPwd}") private String rtspPwd; @Bean pub

  • 生成token 下载 npm i jsonwebtoken -S //生成token cosnt jwt=require('jsonwebtoken')//1、引入 //2、在登录接口生成token let token=jwt.sign( //携带信息 {user,pas} 'abc',//秘钥 {//有效期 expiresIn:'1h'//1h一小

 相关资料
  • Dawn 代表了一种以 HTML 为先,只需要 JavaScript 的主题开发方法。它是 Shopify 第一个内置性能、灵活性和 Online Store 2.0 功能的可用主题源,并作为构建 Shopify 主题的参考。 特性: 最纯粹形式的网络原生 精益、快速和可靠 JavaScript 不是必需的 服务器呈现 功能性 入门 Fork 存储库并克隆它: git clone git@gith

  • Shopify Packer Modern development tool for Shopify using Webpack 5. Easy to extend and customize, zero build config, comes with starter themes and compatible with existing Shopify sites. Features Webp

  • Laravel Shopify App A full-featured Laravel package for aiding in Shopify App development, similar to shopify_app for Rails. Works for Laravel 7 and up. Table of Contents * Wiki pages Goals Documentat

  • Polaris 是 Shopify 的体验平台,该存储库专注于集中系统、文档和基础。 如何使用这个 repo 确保计算机上安装了 Git 和 Node.js,然后运行以下命令开始: $ git clone https://github.com/Shopify/polaris.git # git clone repository$ cd polaris

  • Shopify ThemeKit - Webpack Development tool for Shopify using webpack and themekit. Check out the node package version: Shopify Packer Requirements Getting Started Theme files Commands Features Ready

  • generator-shopify-nextjs A Yeoman generator for Serverless Shopify apps using Next.js, Koa, Prisma GraphQL & Shopify's Polaris The Stack next.js koa koa-shopify-auth koa-shopify-graphql-proxy Polaris