Authorising my backend API

Solved

Authorising my backend API

surfacenathan
Shopify Partner
4 0 1

I have a built a Shopify APP using RemixJS, I have also written a python app in Flask to use as my backend, How do i authenticate with the Shopify API using the same Credentials as my RemixJS app, Do i need to go through the whole Oauth flow again. 

 

If so, will the user of my app need to install the RemixJS app + the Python API app? 

 

Thanks in advance

Accepted Solution (1)

BSSCommerce-B2B
Shopify Expert
551 110 133

This is an accepted solution.

Hi @surfacenathan,

 

No, user dont need to re-authenticate your API. You can use session info from app bridge, and attach it as 'Session-Token' header in your request to Python API. Addtional, you need implement middleware to authorize that header (a simple JWT validator)

 

1. This is example code I am using in Remix App

 

import axios from 'axios';
import { useAppBridge } from '@shopify/app-bridge-react';

class Api {
    constructor(path) {

        this.instance = axios.create({
            headers: {
                'Content-Type': 'application/json',
            }
        });

        this.instance.interceptors.response.use(this.handleResponse, this.handleError);
        this.instance.interceptors.request.use(async (config) => {
            if (typeof window !== "undefined") {
                config.baseURL = `${window.ENV.API_URL}/${path}`
                this.app = useAppBridge();
                config.headers['x-session-token'] = await this.app.idToken()
            } else {
                config.baseURL = `${process.env.API_URL}/${path}`;
            }
            if (!config.headers['x-session-token']) {
                console.log(`Can't find session token`) // eslint-disable-line
            }
            return config
        }, this.handleError);
    }
    async handleResponse(response) {
        const { code } = response.data;
        if (code === 401 || code === 403) {
            console.log('==code === 403==') //eslint-disable-line
        }
        return response.data;
    }
    handleError = (error) => {
        return P

 

 

2. This is the example code to authorize request but in Javascript (koa.js), SHOPIFY_API_SECRET_KEY is your app secret key in partner app API access section.

 

module.exports = async (ctx, next) => {
    const token = ctx.request.headers['x-session-token'];
    if (token) {
        try {
            const payload = jwt.verify(token, SHOPIFY_API_SECRET_KEY);
            await next();
        } catch (err) {
            console.error(err.toString());
            return ctx.body = {
                code: 401,
                error: true,
                message: 'Unauthorized access.',
                err
            }
        }
    } else {
        console.error("No token provided.");
        return ctx.body = {
            code: 403,
            error: true,
            message: 'No token provided.'
        }
    }
}

 

 

Here the Shopify doc about session tokens: https://shopify.dev/docs/apps/build/authentication-authorization/session-tokens

Hope this can help you somehow.

If our suggestions are useful, please let us know by giving it a like, marking it as a solution.


B2B Solution & Custom Pricing |BSS: B2B Portal, Quote, Net 30 | BSS: B2B Login Lock Hide Price


Need help from our expert? Kindly share your request with us via community@bsscommerce.com


BSS Commerce - Full-service eCommerce Agency

View solution in original post

Replies 3 (3)

BSSCommerce-B2B
Shopify Expert
551 110 133

This is an accepted solution.

Hi @surfacenathan,

 

No, user dont need to re-authenticate your API. You can use session info from app bridge, and attach it as 'Session-Token' header in your request to Python API. Addtional, you need implement middleware to authorize that header (a simple JWT validator)

 

1. This is example code I am using in Remix App

 

import axios from 'axios';
import { useAppBridge } from '@shopify/app-bridge-react';

class Api {
    constructor(path) {

        this.instance = axios.create({
            headers: {
                'Content-Type': 'application/json',
            }
        });

        this.instance.interceptors.response.use(this.handleResponse, this.handleError);
        this.instance.interceptors.request.use(async (config) => {
            if (typeof window !== "undefined") {
                config.baseURL = `${window.ENV.API_URL}/${path}`
                this.app = useAppBridge();
                config.headers['x-session-token'] = await this.app.idToken()
            } else {
                config.baseURL = `${process.env.API_URL}/${path}`;
            }
            if (!config.headers['x-session-token']) {
                console.log(`Can't find session token`) // eslint-disable-line
            }
            return config
        }, this.handleError);
    }
    async handleResponse(response) {
        const { code } = response.data;
        if (code === 401 || code === 403) {
            console.log('==code === 403==') //eslint-disable-line
        }
        return response.data;
    }
    handleError = (error) => {
        return P

 

 

2. This is the example code to authorize request but in Javascript (koa.js), SHOPIFY_API_SECRET_KEY is your app secret key in partner app API access section.

 

module.exports = async (ctx, next) => {
    const token = ctx.request.headers['x-session-token'];
    if (token) {
        try {
            const payload = jwt.verify(token, SHOPIFY_API_SECRET_KEY);
            await next();
        } catch (err) {
            console.error(err.toString());
            return ctx.body = {
                code: 401,
                error: true,
                message: 'Unauthorized access.',
                err
            }
        }
    } else {
        console.error("No token provided.");
        return ctx.body = {
            code: 403,
            error: true,
            message: 'No token provided.'
        }
    }
}

 

 

Here the Shopify doc about session tokens: https://shopify.dev/docs/apps/build/authentication-authorization/session-tokens

Hope this can help you somehow.

If our suggestions are useful, please let us know by giving it a like, marking it as a solution.


B2B Solution & Custom Pricing |BSS: B2B Portal, Quote, Net 30 | BSS: B2B Login Lock Hide Price


Need help from our expert? Kindly share your request with us via community@bsscommerce.com


BSS Commerce - Full-service eCommerce Agency
surfacenathan
Shopify Partner
4 0 1

Thanks so much 

surfacenathan
Shopify Partner
4 0 1

I can probably figure this out myself but maybe if you know the solution yourself. I'm basically catching on webhook create/order on store A and then processing it in my backend api, so i want to send the order from Store A to Store B