简体   繁体   中英

How to implement PKCE OAuth2 with React and Doorkeeper?

I created a Rails app with Devise and Doorkeeper for authentication to be used as an API with OAuth2 PKCE for a React Native app.

Expected behavior:

Return the authentication token when I send a POST request with the code received in step B of the PKCE Flow

Actual behavior

It returns this error instead of the token:

{
  "error": "invalid_grant",
  "error_description": "The provided authorization grant is invalid, expired, revoked, does not match the redirection URI used in the authorization request, or was issued to another client.",
}

How to reproduce the error:

  • For the React Native App:
  1. expo init auth-pkce-app --> select Typescrit Blank template

  2. expo install expo-linking expo-web-browser js-sha256

  3. Then replace the code inside of App.tsx with this:

import React, { useEffect, useState } from "react";
import { Button, StyleSheet, Text, View } from "react-native";
import * as Linking from "expo-linking";
import * as WebBrowser from "expo-web-browser";
import { sha256 } from "js-sha256";

const CLIENT_ID = "Ox8_PbOB3g9kBy1HsuEWm6ieePS35jQWcaP_a2D6EmU";
const CLIENT_SECRET = "Z2TJo0AZeseyVvpua7piCPTBXA2v2pIAI3aBKpP1n8c";

const CODE_VERIFIER = "Antante";
const code_challenge = sha256(CODE_VERIFIER);
const code_chanllenge_method = "S256";
const AUTHORIZE_URL =
  `http://localhost:3000/oauth/authorize` +
  `?client_id=${CLIENT_ID}` +
  `&redirect_uri=${Linking.createURL("")}` +
  `&response_type=code` +
  `&scope=write` +
  `&code_challenge=${code_challenge}` +
  `&code_challenge_method=${code_chanllenge_method}`;
  
const TOKEN_URL =
  "http://localhost:3000/oauth/token" +
  `?client_id=${CLIENT_ID}` +
  `&client_secret=${CLIENT_SECRET}` +
  "&grant_type=authorization_code" +
  `&code_verifier=${CODE_VERIFIER}` +
  `&redirect_uri=${Linking.createURL("")}`;

const App: React.FC<{}> = () => {
  const [state, setState] = useState<{
    redirectData?: Linking.ParsedURL | null;
    result?: WebBrowser.WebBrowserAuthSessionResult;
  }>({
    redirectData: null,
  });

  useEffect(() => {
    fetchToken();
  }, [state]);

  const fetchToken = async () => {
    try {
      const response = await fetch(
        TOKEN_URL + `&code=${state.redirectData?.queryParams.code}`,
        {
          method: "POST",
        }
      );
      const data = await response.json();
      console.log(data);
    } catch (err) {
      console.log(err);
    }
  };

  const openAuthSessionAsync = async () => {
    try {
      let result = await WebBrowser.openAuthSessionAsync(
        AUTHORIZE_URL,
        Linking.createURL("")
      );
      let redirectData;
      if (result.type === "success") {
        redirectData = Linking.parse(result.url);
      }
      setState({ result, redirectData });
    } catch (error) {
      alert(error);
      console.log(error);
    }
  };

  const maybeRenderRedirectData = () => {
    if (!state.redirectData) {
      return;
    }
    console.log(state.redirectData);

    return (
      <Text style={{ marginTop: 30 }}>
        {JSON.stringify(state.redirectData)}
      </Text>
    );
  };

  return (
    <View style={styles.container}>
      <Button onPress={openAuthSessionAsync} title="Go to login" />
      <Text>{Linking.createURL("")}</Text>
      {maybeRenderRedirectData()}
    </View>
  );
};

export default App;

const styles = StyleSheet.create({
  container: {
    flex: 1,
    backgroundColor: "#fff",
    alignItems: "center",
    justifyContent: "center",
    paddingBottom: 40,
  },
  header: {
    fontSize: 25,
    marginBottom: 25,
  },
});


  1. Start the app using yarn start and << keep in mind the redirect link under the button labeled 'Go to login' >>
  • For the Rails application with Doorkeeper
  1. git clone git@github.com:dogaruemiliano/pkce-auth.git rails-pkce-auth

  2. bundle install

  3. Go to db/seeds.rb and replace the link at the top of the file ( REDIRECT_URI = 'exp://192.168.0.107:19000' ) with the link we talked about above.

  4. rails db:migrate db:seed

^ this will output in the terminal the Doorkeeper::Applications details (id, secret)

  1. rails g webpacker:install

  2. rails s

The problem lies in the sha256 encoding. The one returned from js-sha256 in your example is hex based but we need to match the urlsafe base64 encoded sha256 from doorkeeper :

def generate_code_challenge(code_verifier)
  Base64.urlsafe_encode64(Digest::SHA256.digest(code_verifier), padding: false)
end

It's perhaps easier to achieve that by using expo-crypto , eg

var code_challenge = await Crypto.digestStringAsync(
  Crypto.CryptoDigestAlgorithm.SHA256,
  CODE_VERIFIER,
  {encoding: Crypto.CryptoEncoding.BASE64}
).then(
  digest => digest.replace(/\+/g, '-').replace(/\//g, '_').replace(/=+$/, '')
)

Hope it helps.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM