Romolo  Morelli

Romolo Morelli

1660971000

Come ottenere dati dinamici nell'app Next.js con percorsi API

Questo tutorial mostra come utilizzare l'API del router di Next.js per ottenere dati dinamici nelle tue applicazioni. Ottieni dati in un'applicazione che richiede l'autenticazione o l'autorizzazione con Next.js.

I dati sono tra le cose più importanti che compongono un'applicazione Web o un'app nativa convenzionale. Abbiamo bisogno di dati per poter vedere e forse capire lo scopo di un'applicazione. In questo articolo, esamineremo un altro approccio per ottenere dati in un'applicazione che richiede l'autenticazione o l'autorizzazione tramite Next.js.

Next.js dispone di cinque tipi di modelli di recupero dati per determinare come si desidera visualizzare i contenuti nell'applicazione: generazione di siti statici (SSG), rendering lato server (SSR), rendering lato client (CSR), statico incrementale rigenerazione (ISR) e routing dinamico.

Puoi scegliere uno di questi modelli che si adatta alla struttura della tua applicazione. Per saperne di più su questi modelli, leggili nella documentazione ufficiale .

Questo articolo è incentrato sulla generazione di siti statici e sul routing dinamico. L'uso di questi modelli richiede l'uso dei metodi getStaticPropse getStaticPathsdi recupero dei dati. Questi metodi svolgono ruoli unici nell'ottenimento dei dati.

È da un po' che parliamo di dati dinamici. Capiamo cosa significa veramente.

Supponiamo di avere un elenco di utenti in un'applicazione che viene visualizzata su una pagina Web e di voler ottenere informazioni univoche per un utente quando facciamo clic sul suo nome: le informazioni che otteniamo cambierebbero in base all'azione che eseguiamo (facendo clic sul nome utente).

Vogliamo un modo per eseguire il rendering di tali dati su una pagina (o schermata) univoca nell'applicazione e il getStaticPathsmetodo di recupero dei dati ci consente di ottenere dati univoci per un utente. Questo è solitamente comune in una matrice di oggetti utente con una chiave univoca ( ido _id), a seconda di come è strutturato l'oggetto risposta.

export async function getStaticPaths() {
  return {
    paths: {
      [{
        params: {
          uniqueId: id.toString()
        }
      }],
      fallback: false
    }
  }
}

La chiave univoca ottenuta dal getStaticPathsmetodo (comunemente denominata parametro, o in breve params) viene passata come argomento tramite il contextparametro in getStaticProps.

Questo ci riporta al fatto che getStaticPathssenza getStaticProps. Entrambi funzionano insieme, perché dovrai passare l'univoco iddal percorso generato staticamente come argomento al contextparametro in getStaticProps. Il frammento di codice seguente illustra questo:

export async function getStaticProps(context) {
  return {
    props: {
      userData: data,
    },
  }
}

I contro dell'utilizzo dei metodi nativi di recupero dei dati di Next.Js 

Ora che comprendiamo un po' il recupero dinamico dei dati in Next.js, diamo un'occhiata ai contro dell'utilizzo dei due metodi di recupero dei dati sopra menzionati.

È possibile ottenere dati da un'API pubblica che non richiede autorizzazione con una sorta di chiave API durante il recupero dei dati con getStaticPropse getStaticPaths.

Dai un'occhiata a entrambi di seguito:

// getStaticPaths
export async function getStaticPaths() {
  const response = fetch("https://jsonplaceholder.typicode.com/users")
  const userData = await response.json()

 // Getting the unique key of the user from the response
 // with the map method of JavaScript.
  const uniqueId = userData.map((data) => {
    return data.id
  })

  return {
    paths: {
      [{
        params: {
          uniqueId: uniqueId.toString()
        }
      }],
      fallback: false
    }
  }
}

Noterai che l'univocativo idè ottenuto dal mapmetodo di JavaScript e lo assegneremo come valore tramite il contextparametro di getStaticProps.

export async function getStaticProps(context) {
  // Obtain the user’s unique ID.
  const userId = context.params.uniqueId

  // Append the ID as a parameter to the API endpoint.
  const response = fetch(`https://jsonplaceholder.typicode.com/users/${userId}`)
  const userData = await response.json()
  return {
    props: {
      userData,
    },
  }
}

Nello snippet sopra, vedrai che una variabile denominata userIdè stata inizializzata e il suo valore è stato ottenuto dal contextparametro.

Tale valore viene quindi aggiunto come parametro all'URL di base dell'API.

Nota: i metodi getStaticPropse getStaticPathsdi recupero dati possono essere esportati solo da un file nella pagescartella di Next.js.

Praticamente lo fa per un'API pubblica. Ma quando crei un'applicazione che richiede all'utente di accedere, disconnettersi e magari eseguire alcune operazioni di recupero dei dati nell'applicazione quando accede con il proprio account, il flusso dell'applicazione è diverso.

Recupero dei dati in un sistema autenticato. 

Il flusso di ottenimento dei dati in un sistema autenticato è abbastanza diverso dal normale modo in cui otteniamo i dati da un'API pubblica.

Immagina questo scenario: un utente accede a un'app Web e quindi visita il proprio profilo. Sulla loro pagina del profilo (una volta che è stata renderizzata), sono in grado di vedere e modificare le informazioni che hanno fornito al momento della registrazione.

Affinché ciò avvenga, deve esserci una sorta di verifica dei dati inviati all'utente dallo sviluppatore che ha creato l'interfaccia. Fortunatamente, esiste un modello comune per autorizzare un utente quando accede a un sistema: JSON Web Tokens (JWT).

Quando un utente si iscrive per utilizzare l'applicazione per la prima volta, i suoi dettagli vengono archiviati nel database e un JWT univoco viene assegnato allo schema di quell'utente (a seconda di come è stata progettata l'API back-end).

Quando l'utente tenta di accedere alla tua app e le sue credenziali corrispondono a quelle con cui si è registrato originariamente, la prossima cosa che gli ingegneri front-end devono fare è fornire uno stato di autenticazione per l'utente, in modo da poter ottenere i dettagli richiesti, uno dei quali è il JWT.

Esistono diverse scuole di pensiero su come preservare un utente auth-state, incluso l'utilizzo di Redux, Composition in React e l'API Context di React (consiglierei l'API Context). L'articolo di Átila Fassina esamina i paradigmi della gestione dello stato in Next.js.

L'approccio comune è archiviare il JWT in localStorage— almeno per iniziare, se stiamo considerando il problema della sicurezza in modo rigoroso. È consigliabile memorizzare il tuo JWT in un httpOnlycookie, per prevenire attacchi alla sicurezza come un cross-site request forgery (CSRF) e cross-site scripting (XSS).

Ancora una volta, questo approccio può essere possibile solo se il middleware dei cookie appropriato viene fornito nell'API creata dagli ingegneri di back-end.

Se non vuoi affrontare la seccatura di capire come gli ingegneri di back-end hanno progettato un'API, un percorso alternativo per l'autenticazione in Next.js consiste nell'utilizzare il progetto di autenticazione open source NextAuth.js.

Una volta che il token è localStoragesul lato client, le chiamate API che richiedono il token utente come mezzo di autorizzazione possono essere eseguite, senza generare un errore 501 (non autorizzato).

headers: {
  "x-auth-token": localStorage.getItem("token")
}

Recupero dei dati con il useRoutergancio 

Nella prima sezione, abbiamo visto come funziona il processo di recupero dinamico dei dati in Next.js per un'applicazione che non richiede l'autenticazione.

In questa sezione, vedremo come aggirare il problema dei metodi getStaticPropse getStaticPathsdi recupero dei dati che generano un referenceError(" localStoragenon è definito") quando proviamo a ottenere il token dell'utente da localStorage.

Questo errore si verifica perché i due metodi di recupero dati sono sempre in esecuzione sul server in background, il che, a sua volta, rende l' localStorageoggetto non disponibile per loro, poiché si trova sul lato client (nel browser).

L'API del router di Next.js crea molte possibilità quando abbiamo a che fare con percorsi e dati dinamici. Con l' useRouterhook, dovremmo essere in grado di ottenere dati univoci per un utente in base al suo ID univoco.

Diamo un'occhiata allo snippet qui sotto per iniziare:

// pages/index.js

import React from "react";
import axios from "axios";
import { userEndpoints } from "../../../routes/endpoints";
import Link from "next/link";

const Users = () => {
  const [data, setData] = React.useState([])
  const [loading, setLoading] = React.useState(false)

  const getAllUsers = async () => {
    try {
      setLoading(true);
      const response = await axios({
        method: "GET",
        url: userEndpoints.getUsers,
        headers: {
          "x-auth-token": localStorage.getItem("token"),
          "Content-Type": "application/json",
        },
      });
      const { data } = response.data;
      setData(data);
    } catch (error) {
      setLoading(false);
      console.log(error);
    }
  };

  return (
    <React.Fragment>
      <p>Users list</p>
      {data.map((user) => {
          return (
            <Link href={`/${user._id}`} key={user._id}>
              <div className="user">
                <p className="fullname">{user.name}</p>
                <p className="position">{user.role}</p>
              </div>  
            </Link>
          );
        })}
    </React.Fragment>
  );
};

export default Users;

Nello snippet sopra, abbiamo usato l' useEffecthook per ottenere i dati una volta che la pagina è stata renderizzata per la prima volta. Noterai anche che il JWT è assegnato alla x-auth-tokenchiave nell'intestazione della richiesta.

Quando facciamo clic su un utente, il Linkcomponente ci indirizzerà a una nuova pagina basata sull'ID univoco dell'utente. Una volta che siamo su quella pagina, vogliamo rendere le informazioni che sono specificamente disponibili per quell'utente con l'estensione id.

L' useRouterhook ci dà accesso alla pathnamescheda URL del browser. Con questo in atto, possiamo ottenere il parametro di query di quel percorso univoco, che è il id.

Lo snippet seguente illustra l'intero processo:

// [id].js

import React from "react";
import Head from "next/head";
import axios from "axios";
import { userEndpoints } from "../../../routes/endpoints";
import { useRouter } from "next/router";

const UniqueUser = () => {
  const [user, setUser] = React.useState({
    fullName: "",
    email: "",
    role: "",
  });
  const [loading, setLoading] = React.useState(false);
  const { query } = useRouter();

  // Obtaining the user’s unique ID with Next.js'
  // useRouter hook.
  const currentUserId = query.id;

  const getUniqueUser = async () => {
    try {
      setLoading(true);
      const response = await axios({
        method: "GET",
        url: `${userEndpoints.getUsers}/${currentUserId}`,
        headers: {
          "Content-Type": "application/json",
          "x-auth-token": localStorage.getItem("token"),
        },
      });
      const { data } = response.data;
      setUser(data);
    } catch (error) {
      setLoading(false);
      console.log(error);
    }
  };

  React.useEffect(() => {
    getUniqueUser();
  }, []);

  return (
    <React.Fragment>
      <Head>
        <title>
          {`${user.fullName}'s Profile | "Profile" `}
        </title>
      </Head>
        <div>
          <div className="user-info">
            <div className="user-details">
              <p className="fullname">{user.fullName}</p>
              <p className="role">{user.role}</p>
              <p className="email">{user.email}</p>
            </div>
          </div>
        </div>
      )}
    </React.Fragment>
  );
};
export default UniqueUser;

Nello snippet sopra, vedrai che abbiamo destrutturato l'oggetto query useRouterdall'hook, che useremo per ottenere l'ID univoco dell'utente e passarlo come argomento all'endpoint API.

const {query} = useRouter()
const userId = query.id

Dopo aver aggiunto l'ID univoco all'endpoint API, i dati destinati a quell'utente verranno visualizzati una volta caricata la pagina.

Conclusione 

Il recupero dei dati in Next.js può diventare complicato se non comprendi appieno il caso d'uso della tua applicazione.

Spero che questo articolo ti abbia aiutato a capire come utilizzare l'API del router di Next.js per ottenere dati dinamici nelle tue applicazioni.

Fonte dell'articolo originale su https://www.smashingmagazine.com

#nextjs #api #database

What is GEEK

Buddha Community

Come ottenere dati dinamici nell'app Next.js con percorsi API

NBB: Ad-hoc CLJS Scripting on Node.js

Nbb

Not babashka. Node.js babashka!?

Ad-hoc CLJS scripting on Node.js.

Status

Experimental. Please report issues here.

Goals and features

Nbb's main goal is to make it easy to get started with ad hoc CLJS scripting on Node.js.

Additional goals and features are:

  • Fast startup without relying on a custom version of Node.js.
  • Small artifact (current size is around 1.2MB).
  • First class macros.
  • Support building small TUI apps using Reagent.
  • Complement babashka with libraries from the Node.js ecosystem.

Requirements

Nbb requires Node.js v12 or newer.

How does this tool work?

CLJS code is evaluated through SCI, the same interpreter that powers babashka. Because SCI works with advanced compilation, the bundle size, especially when combined with other dependencies, is smaller than what you get with self-hosted CLJS. That makes startup faster. The trade-off is that execution is less performant and that only a subset of CLJS is available (e.g. no deftype, yet).

Usage

Install nbb from NPM:

$ npm install nbb -g

Omit -g for a local install.

Try out an expression:

$ nbb -e '(+ 1 2 3)'
6

And then install some other NPM libraries to use in the script. E.g.:

$ npm install csv-parse shelljs zx

Create a script which uses the NPM libraries:

(ns script
  (:require ["csv-parse/lib/sync$default" :as csv-parse]
            ["fs" :as fs]
            ["path" :as path]
            ["shelljs$default" :as sh]
            ["term-size$default" :as term-size]
            ["zx$default" :as zx]
            ["zx$fs" :as zxfs]
            [nbb.core :refer [*file*]]))

(prn (path/resolve "."))

(prn (term-size))

(println (count (str (fs/readFileSync *file*))))

(prn (sh/ls "."))

(prn (csv-parse "foo,bar"))

(prn (zxfs/existsSync *file*))

(zx/$ #js ["ls"])

Call the script:

$ nbb script.cljs
"/private/tmp/test-script"
#js {:columns 216, :rows 47}
510
#js ["node_modules" "package-lock.json" "package.json" "script.cljs"]
#js [#js ["foo" "bar"]]
true
$ ls
node_modules
package-lock.json
package.json
script.cljs

Macros

Nbb has first class support for macros: you can define them right inside your .cljs file, like you are used to from JVM Clojure. Consider the plet macro to make working with promises more palatable:

(defmacro plet
  [bindings & body]
  (let [binding-pairs (reverse (partition 2 bindings))
        body (cons 'do body)]
    (reduce (fn [body [sym expr]]
              (let [expr (list '.resolve 'js/Promise expr)]
                (list '.then expr (list 'clojure.core/fn (vector sym)
                                        body))))
            body
            binding-pairs)))

Using this macro we can look async code more like sync code. Consider this puppeteer example:

(-> (.launch puppeteer)
      (.then (fn [browser]
               (-> (.newPage browser)
                   (.then (fn [page]
                            (-> (.goto page "https://clojure.org")
                                (.then #(.screenshot page #js{:path "screenshot.png"}))
                                (.catch #(js/console.log %))
                                (.then #(.close browser)))))))))

Using plet this becomes:

(plet [browser (.launch puppeteer)
       page (.newPage browser)
       _ (.goto page "https://clojure.org")
       _ (-> (.screenshot page #js{:path "screenshot.png"})
             (.catch #(js/console.log %)))]
      (.close browser))

See the puppeteer example for the full code.

Since v0.0.36, nbb includes promesa which is a library to deal with promises. The above plet macro is similar to promesa.core/let.

Startup time

$ time nbb -e '(+ 1 2 3)'
6
nbb -e '(+ 1 2 3)'   0.17s  user 0.02s system 109% cpu 0.168 total

The baseline startup time for a script is about 170ms seconds on my laptop. When invoked via npx this adds another 300ms or so, so for faster startup, either use a globally installed nbb or use $(npm bin)/nbb script.cljs to bypass npx.

Dependencies

NPM dependencies

Nbb does not depend on any NPM dependencies. All NPM libraries loaded by a script are resolved relative to that script. When using the Reagent module, React is resolved in the same way as any other NPM library.

Classpath

To load .cljs files from local paths or dependencies, you can use the --classpath argument. The current dir is added to the classpath automatically. So if there is a file foo/bar.cljs relative to your current dir, then you can load it via (:require [foo.bar :as fb]). Note that nbb uses the same naming conventions for namespaces and directories as other Clojure tools: foo-bar in the namespace name becomes foo_bar in the directory name.

To load dependencies from the Clojure ecosystem, you can use the Clojure CLI or babashka to download them and produce a classpath:

$ classpath="$(clojure -A:nbb -Spath -Sdeps '{:aliases {:nbb {:replace-deps {com.github.seancorfield/honeysql {:git/tag "v2.0.0-rc5" :git/sha "01c3a55"}}}}}')"

and then feed it to the --classpath argument:

$ nbb --classpath "$classpath" -e "(require '[honey.sql :as sql]) (sql/format {:select :foo :from :bar :where [:= :baz 2]})"
["SELECT foo FROM bar WHERE baz = ?" 2]

Currently nbb only reads from directories, not jar files, so you are encouraged to use git libs. Support for .jar files will be added later.

Current file

The name of the file that is currently being executed is available via nbb.core/*file* or on the metadata of vars:

(ns foo
  (:require [nbb.core :refer [*file*]]))

(prn *file*) ;; "/private/tmp/foo.cljs"

(defn f [])
(prn (:file (meta #'f))) ;; "/private/tmp/foo.cljs"

Reagent

Nbb includes reagent.core which will be lazily loaded when required. You can use this together with ink to create a TUI application:

$ npm install ink

ink-demo.cljs:

(ns ink-demo
  (:require ["ink" :refer [render Text]]
            [reagent.core :as r]))

(defonce state (r/atom 0))

(doseq [n (range 1 11)]
  (js/setTimeout #(swap! state inc) (* n 500)))

(defn hello []
  [:> Text {:color "green"} "Hello, world! " @state])

(render (r/as-element [hello]))

Promesa

Working with callbacks and promises can become tedious. Since nbb v0.0.36 the promesa.core namespace is included with the let and do! macros. An example:

(ns prom
  (:require [promesa.core :as p]))

(defn sleep [ms]
  (js/Promise.
   (fn [resolve _]
     (js/setTimeout resolve ms))))

(defn do-stuff
  []
  (p/do!
   (println "Doing stuff which takes a while")
   (sleep 1000)
   1))

(p/let [a (do-stuff)
        b (inc a)
        c (do-stuff)
        d (+ b c)]
  (prn d))
$ nbb prom.cljs
Doing stuff which takes a while
Doing stuff which takes a while
3

Also see API docs.

Js-interop

Since nbb v0.0.75 applied-science/js-interop is available:

(ns example
  (:require [applied-science.js-interop :as j]))

(def o (j/lit {:a 1 :b 2 :c {:d 1}}))

(prn (j/select-keys o [:a :b])) ;; #js {:a 1, :b 2}
(prn (j/get-in o [:c :d])) ;; 1

Most of this library is supported in nbb, except the following:

  • destructuring using :syms
  • property access using .-x notation. In nbb, you must use keywords.

See the example of what is currently supported.

Examples

See the examples directory for small examples.

Also check out these projects built with nbb:

API

See API documentation.

Migrating to shadow-cljs

See this gist on how to convert an nbb script or project to shadow-cljs.

Build

Prequisites:

  • babashka >= 0.4.0
  • Clojure CLI >= 1.10.3.933
  • Node.js 16.5.0 (lower version may work, but this is the one I used to build)

To build:

  • Clone and cd into this repo
  • bb release

Run bb tasks for more project-related tasks.

Download Details:
Author: borkdude
Download Link: Download The Source Code
Official Website: https://github.com/borkdude/nbb 
License: EPL-1.0

#node #javascript

Top 10 API Security Threats Every API Team Should Know

As more and more data is exposed via APIs either as API-first companies or for the explosion of single page apps/JAMStack, API security can no longer be an afterthought. The hard part about APIs is that it provides direct access to large amounts of data while bypassing browser precautions. Instead of worrying about SQL injection and XSS issues, you should be concerned about the bad actor who was able to paginate through all your customer records and their data.

Typical prevention mechanisms like Captchas and browser fingerprinting won’t work since APIs by design need to handle a very large number of API accesses even by a single customer. So where do you start? The first thing is to put yourself in the shoes of a hacker and then instrument your APIs to detect and block common attacks along with unknown unknowns for zero-day exploits. Some of these are on the OWASP Security API list, but not all.

Insecure pagination and resource limits

Most APIs provide access to resources that are lists of entities such as /users or /widgets. A client such as a browser would typically filter and paginate through this list to limit the number items returned to a client like so:

First Call: GET /items?skip=0&take=10 
Second Call: GET /items?skip=10&take=10

However, if that entity has any PII or other information, then a hacker could scrape that endpoint to get a dump of all entities in your database. This could be most dangerous if those entities accidently exposed PII or other sensitive information, but could also be dangerous in providing competitors or others with adoption and usage stats for your business or provide scammers with a way to get large email lists. See how Venmo data was scraped

A naive protection mechanism would be to check the take count and throw an error if greater than 100 or 1000. The problem with this is two-fold:

  1. For data APIs, legitimate customers may need to fetch and sync a large number of records such as via cron jobs. Artificially small pagination limits can force your API to be very chatty decreasing overall throughput. Max limits are to ensure memory and scalability requirements are met (and prevent certain DDoS attacks), not to guarantee security.
  2. This offers zero protection to a hacker that writes a simple script that sleeps a random delay between repeated accesses.
skip = 0
while True:    response = requests.post('https://api.acmeinc.com/widgets?take=10&skip=' + skip),                      headers={'Authorization': 'Bearer' + ' ' + sys.argv[1]})    print("Fetched 10 items")    sleep(randint(100,1000))    skip += 10

How to secure against pagination attacks

To secure against pagination attacks, you should track how many items of a single resource are accessed within a certain time period for each user or API key rather than just at the request level. By tracking API resource access at the user level, you can block a user or API key once they hit a threshold such as “touched 1,000,000 items in a one hour period”. This is dependent on your API use case and can even be dependent on their subscription with you. Like a Captcha, this can slow down the speed that a hacker can exploit your API, like a Captcha if they have to create a new user account manually to create a new API key.

Insecure API key generation

Most APIs are protected by some sort of API key or JWT (JSON Web Token). This provides a natural way to track and protect your API as API security tools can detect abnormal API behavior and block access to an API key automatically. However, hackers will want to outsmart these mechanisms by generating and using a large pool of API keys from a large number of users just like a web hacker would use a large pool of IP addresses to circumvent DDoS protection.

How to secure against API key pools

The easiest way to secure against these types of attacks is by requiring a human to sign up for your service and generate API keys. Bot traffic can be prevented with things like Captcha and 2-Factor Authentication. Unless there is a legitimate business case, new users who sign up for your service should not have the ability to generate API keys programmatically. Instead, only trusted customers should have the ability to generate API keys programmatically. Go one step further and ensure any anomaly detection for abnormal behavior is done at the user and account level, not just for each API key.

Accidental key exposure

APIs are used in a way that increases the probability credentials are leaked:

  1. APIs are expected to be accessed over indefinite time periods, which increases the probability that a hacker obtains a valid API key that’s not expired. You save that API key in a server environment variable and forget about it. This is a drastic contrast to a user logging into an interactive website where the session expires after a short duration.
  2. The consumer of an API has direct access to the credentials such as when debugging via Postman or CURL. It only takes a single developer to accidently copy/pastes the CURL command containing the API key into a public forum like in GitHub Issues or Stack Overflow.
  3. API keys are usually bearer tokens without requiring any other identifying information. APIs cannot leverage things like one-time use tokens or 2-factor authentication.

If a key is exposed due to user error, one may think you as the API provider has any blame. However, security is all about reducing surface area and risk. Treat your customer data as if it’s your own and help them by adding guards that prevent accidental key exposure.

How to prevent accidental key exposure

The easiest way to prevent key exposure is by leveraging two tokens rather than one. A refresh token is stored as an environment variable and can only be used to generate short lived access tokens. Unlike the refresh token, these short lived tokens can access the resources, but are time limited such as in hours or days.

The customer will store the refresh token with other API keys. Then your SDK will generate access tokens on SDK init or when the last access token expires. If a CURL command gets pasted into a GitHub issue, then a hacker would need to use it within hours reducing the attack vector (unless it was the actual refresh token which is low probability)

Exposure to DDoS attacks

APIs open up entirely new business models where customers can access your API platform programmatically. However, this can make DDoS protection tricky. Most DDoS protection is designed to absorb and reject a large number of requests from bad actors during DDoS attacks but still need to let the good ones through. This requires fingerprinting the HTTP requests to check against what looks like bot traffic. This is much harder for API products as all traffic looks like bot traffic and is not coming from a browser where things like cookies are present.

Stopping DDoS attacks

The magical part about APIs is almost every access requires an API Key. If a request doesn’t have an API key, you can automatically reject it which is lightweight on your servers (Ensure authentication is short circuited very early before later middleware like request JSON parsing). So then how do you handle authenticated requests? The easiest is to leverage rate limit counters for each API key such as to handle X requests per minute and reject those above the threshold with a 429 HTTP response. There are a variety of algorithms to do this such as leaky bucket and fixed window counters.

Incorrect server security

APIs are no different than web servers when it comes to good server hygiene. Data can be leaked due to misconfigured SSL certificate or allowing non-HTTPS traffic. For modern applications, there is very little reason to accept non-HTTPS requests, but a customer could mistakenly issue a non HTTP request from their application or CURL exposing the API key. APIs do not have the protection of a browser so things like HSTS or redirect to HTTPS offer no protection.

How to ensure proper SSL

Test your SSL implementation over at Qualys SSL Test or similar tool. You should also block all non-HTTP requests which can be done within your load balancer. You should also remove any HTTP headers scrub any error messages that leak implementation details. If your API is used only by your own apps or can only be accessed server-side, then review Authoritative guide to Cross-Origin Resource Sharing for REST APIs

Incorrect caching headers

APIs provide access to dynamic data that’s scoped to each API key. Any caching implementation should have the ability to scope to an API key to prevent cross-pollution. Even if you don’t cache anything in your infrastructure, you could expose your customers to security holes. If a customer with a proxy server was using multiple API keys such as one for development and one for production, then they could see cross-pollinated data.

#api management #api security #api best practices #api providers #security analytics #api management policies #api access tokens #api access #api security risks #api access keys

Autumn  Blick

Autumn Blick

1601381326

Public ASX100 APIs: The Essential List

We’ve conducted some initial research into the public APIs of the ASX100 because we regularly have conversations about what others are doing with their APIs and what best practices look like. Being able to point to good local examples and explain what is happening in Australia is a key part of this conversation.

Method

The method used for this initial research was to obtain a list of the ASX100 (as of 18 September 2020). Then work through each company looking at the following:

  1. Whether the company had a public API: this was found by googling “[company name] API” and “[company name] API developer” and “[company name] developer portal”. Sometimes the company’s website was navigated or searched.
  2. Some data points about the API were noted, such as the URL of the portal/documentation and the method they used to publish the API (portal, documentation, web page).
  3. Observations were recorded that piqued the interest of the researchers (you will find these below).
  4. Other notes were made to support future research.
  5. You will find a summary of the data in the infographic below.

Data

With regards to how the APIs are shared:

#api #api-development #api-analytics #apis #api-integration #api-testing #api-security #api-gateway

Eva  Murphy

Eva Murphy

1625751960

Laravel API and React Next JS frontend development - 28

In this video, I wanted to touch upon the functionality of adding Chapters inside a Course. The idea was to not think much and start the development and pick up things as they come.

There are places where I get stuck and trying to find answers to it up doing what every developer does - Google and get help. I hope this will help you understand the flow and also how developers debug while doing development.

App url: https://video-reviews.vercel.app
Github code links below:
Next JS App: https://github.com/amitavroy/video-reviews
Laravel API: https://github.com/amitavdevzone/video-review-api

You can find me on:
Twitter: https://twitter.com/amitavroy7​
Discord: https://discord.gg/Em4nuvQk

#next js #api #react next js #next #frontend #development

An API-First Approach For Designing Restful APIs | Hacker Noon

I’ve been working with Restful APIs for some time now and one thing that I love to do is to talk about APIs.

So, today I will show you how to build an API using the API-First approach and Design First with OpenAPI Specification.

First thing first, if you don’t know what’s an API-First approach means, it would be nice you stop reading this and check the blog post that I wrote to the Farfetchs blog where I explain everything that you need to know to start an API using API-First.

Preparing the ground

Before you get your hands dirty, let’s prepare the ground and understand the use case that will be developed.

Tools

If you desire to reproduce the examples that will be shown here, you will need some of those items below.

  • NodeJS
  • OpenAPI Specification
  • Text Editor (I’ll use VSCode)
  • Command Line

Use Case

To keep easy to understand, let’s use the Todo List App, it is a very common concept beyond the software development community.

#api #rest-api #openai #api-first-development #api-design #apis #restful-apis #restful-api