最新消息:雨落星辰是一个专注网站SEO优化、网站SEO诊断、搜索引擎研究、网络营销推广、网站策划运营及站长类的自媒体原创博客

reactjs - I am facing an issue with Google Sign-Up using Clerk authentication - Stack Overflow

programmeradmin0浏览0评论

When I attempt to sign up directly with Google, I receive a 422 Unprocessable Content error in the network response. The error message states: "oauth_callback does not match one of the allowed values for parameter strategy" It seems to be related to the OAuth strategy parameter. How can I resolve this issue?

Error Status Code: 422 Unprocessable Content

{
    "errors": [
        {
            "message": "is invalid",
            "long_message": "oauth_callback does not match one of the allowed values for parameter strategy",
            "code": "form_param_value_invalid",
            "meta": {
                "param_name": "strategy"
            }
        }
    ],
    "meta": {
        "client": {
            "object": "client",
            "id": "client_2tTgzvKTyiBajmMGpVs8tgpj8ja",
            "sessions": [
                {
                    "object": "session",
                    "id": "sess_2vABlgwAEo4l2Kom0XV0wZx9s4c",
                    "status": "active",
                    "expire_at": 1744182950769,
                    "abandon_at": 1746170150769,
                    "last_active_at": 1743662041331,
                    "last_active_anization_id": null,
                    "actor": null,
                    "user": {
                        "id": "user_2tTn8tl62bzi3IUqxkfENzL7GYQ",
                        "object": "user",
                        "username": null,
                        "first_name": "test",
                        "last_name": "test",
                        "image_url": ";,
                        "has_image": false,
                        "primary_email_address_id": "idn_2tTn6tCVOOvVj0kaPSKh5z6NWlw",
                        "primary_phone_number_id": null,
                        "primary_web3_wallet_id": null,
                        "password_enabled": true,
                        "two_factor_enabled": false,
                        "totp_enabled": false,
                        "backup_code_enabled": false,
                        "email_addresses": [
                            {
                                "id": "idn_2tTn6tCVOOvVj0kaPSKh5z6NWlw",
                                "object": "email_address",
                                "email_address": "[email protected]",
                                "reserved": false,
                                "verification": {
                                    "status": "verified",
                                    "strategy": "email_code",
                                    "attempts": 1,
                                    "expire_at": 1740385360128
                                },
                                "linked_to": [
                                    {
                                        "type": "oauth_google",
                                        "id": "idn_2tZB3BkzNqIFCCu7hwgP2rkUuI9"
                                    }
                                ],
                                "matches_sso_connection": false,
                                "created_at": 1740384759370,
                                "updated_at": 1740384776004
                            }
                        ],
                        "phone_numbers": [],
                        "web3_wallets": [],
                        "passkeys": [],
                        "external_accounts": [
                            {
                                "object": "external_account",
                                "id": "eac_2tZB3B2DlWnDwOtp3PqPnnOVQm9",
                                "provider": "oauth_google",
                                "identification_id": "idn_2tZB3BkzNqIFCCu7hwgP2rkUuI9",
                                "provider_user_id": "109294911885927750031",
                                "approved_scopes": "email .email .profile openid profile",
                                "email_address": "[email protected]",
                                "first_name": "test",
                                "last_name": "test",
                                "avatar_url": ";,
                                "image_url": ";,
                                "username": "",
                                "public_metadata": {},
                                "label": null,
                                "created_at": 1740549514944,
                                "updated_at": 1743662026097,
                                "verification": {
                                    "status": "verified",
                                    "strategy": "oauth_google",
                                    "attempts": null,
                                    "expire_at": 1740550104974
                                }
                            }
                        ],
                        "saml_accounts": [],
                        "enterprise_accounts": [],
                        "public_metadata": {},
                        "unsafe_metadata": {},
                        "external_id": null,
                        "last_sign_in_at": 1743598210672,
                        "banned": false,
                        "locked": false,
                        "lockout_expires_in_seconds": null,
                        "verification_attempts_remaining": 100,
                        "created_at": 1740384775994,
                        "updated_at": 1743598210699,
                        "delete_self_enabled": true,
                        "create_anization_enabled": true,
                        "last_active_at": 1743598210735,
                        "mfa_enabled_at": null,
                        "mfa_disabled_at": null,
                        "legal_accepted_at": null,
                        "profile_image_url": ";,
                        "anization_memberships": []
                    },
                    "public_user_data": {
                        "first_name": "test",
                        "last_name": "test",
                        "image_url": ";,
                        "has_image": false,
                        "identifier": "[email protected]",
                        "profile_image_url": ";
                    },
                    "factor_verification_age": [
                        1398,
                        -1
                    ],
                    "created_at": 1743578150769,
                    "updated_at": 1743662041331,
                    "last_active_token": {
                        ....token
                    }
                }
            ],
            "sign_in": null,
            "sign_up": {
                "object": "sign_up_attempt",
                "id": "sua_2vCvp4nSViErK1xDHB0e7xLVQwv",
                "status": "missing_requirements",
                "required_fields": [
                    "email_address",
                    "username",
                    "password"
                ],
                "optional_fields": [
                    "web3_wallet",
                    "last_name",
                    "first_name",
                    "oauth_google",
                    "oauth_linkedin_oidc",
                    "oauth_facebook"
                ],
                "missing_fields": [
                    "username"
                ],
                "unverified_fields": [],
                "verifications": {
                    "email_address": {
                        "status": "verified",
                        "strategy": "from_oauth_google",
                        "attempts": null,
                        "expire_at": null,
                        "next_action": "",
                        "supported_strategies": [
                            "from_oauth_google"
                        ]
                    },
                    "phone_number": null,
                    "web3_wallet": null,
                    "external_account": {
                        "status": "verified",
                        "strategy": "oauth_google",
                        "attempts": null,
                        "expire_at": 1743662655536
                    }
                },
                "username": null,
                "email_address": "[email protected]",
                "phone_number": null,
                "web3_wallet": null,
                "password_enabled": false,
                "first_name": "test",
                "last_name": "test",
                "unsafe_metadata": {},
                "public_metadata": {},
                "custom_action": false,
                "external_id": null,
                "created_session_id": null,
                "created_user_id": null,
                "abandon_at": 1743748449240,
                "legal_accepted_at": null
            },
            "last_active_session_id": "sess_2vABlgwAEo4l2Kom0XV0wZx9s4c",
            "cookie_expires_at": null,
            "captcha_bypass": false,
            "created_at": 1740381743403,
            "updated_at": 1743662049244
        }
    },
    "clerk_trace_id": "b75d08cfc07794bbebfdbc9863dd3b5d"
}

Signup component code:

import { useState } from "react";
import { Link, useNavigate } from 'react-router-dom';
import backgroundImg from "../../assets/login.png";
import { SlSocialGoogle } from "react-icons/sl";
import { FiFacebook } from "react-icons/fi";
import { useSignUp } from "@clerk/clerk-react";

function Signup() {
  const [username, setUsername] = useState("");
  const [email, setEmail] = useState("");
  const [password, setPassword] = useState("");
  const [showPassword, setShowPassword] = useState(false);
  const [message, setMessage] = useState("");
  const navigate = useNavigate();
  const { signUp, isLoaded } = useSignUp();

  const handleSignup = async (e) => {
    e.preventDefault();
    
    if (!isLoaded) {
      return;
    }

    try {
      // Start the sign-up process with Clerk
      const result = await signUp.create({
        username,
        email_address: email,
        password,
      });

      // Verify the email if Clerk requires it
      if (result.status === "complete") {
        // Successfully created account
        setMessage("Signup successful!");
        navigate("/login");
      } else if (result.status === "needs_email_verification") {
        // If email verification is enabled in Clerk
        await signUp.prepareEmailAddressVerification({ strategy: "email_code" });
        navigate("/verify"); // You would need to create a verification page
        setMessage("Please check your email for verification instructions.");
      }
    } catch (error) {
      console.error("Error during signup:", error);
      setMessage(error.errors?.[0]?.message || "Signup failed. Please try again.");
    }
  };

  // Handle OAuth providers
  const handleGoogleSignup = async () => {
    if (!isLoaded) return;
    try {
      await signUp.authenticateWithRedirect({
        strategy: "oauth_google",
        redirectUrl: "/sso-callback",
        redirectUrlComplete: "/login"
      });
    } catch (error) {
      console.error("Error with Google signup:", error);
      setMessage("Google signup failed. Please try again.");
    }
  };

  const handleFacebookSignup = async () => {
    if (!isLoaded) return;
    try {
      await signUp.authenticateWithRedirect({
        strategy: "oauth_facebook",
        redirectUrl: "/sso-callback",
        redirectUrlComplete: "/login"
      });
    } catch (error) {
      console.error("Error with Facebook signup:", error);
      setMessage("Facebook signup failed. Please try again.");
    }
  };

  return (
    <div className="flex items-center justify-center min-h-screen bg-cover bg-center" style={{ backgroundImage: `url(${backgroundImg})` }}>
      <div className="bg-[#171717] text-white p-12 rounded-3xl shadow-lg w-1/2">
        <h1 className="text-left text-3xl font-extrabold mb-1">Create your account</h1>
        <div className="text-sm mb-6 text-slate-300">Harness the power of AI content creation, in seconds. Get started now.</div>
        <form onSubmit={handleSignup}>
          <div className="mb-6 flex bg-[#1E1E1E] rounded-2xl px-4 pt-3 pb-3 flex-col">
            <label className="block mb-1 text-white font-extrabold">Full Name</label>
            <input
              type="text"
              placeholder="Enter your Name here"
              value={username}
              onChange={(e) => setUsername(e.target.value)}
              required
              className="w-full bg-[#1E1E1E] text-white rounded-lg focus:outline-none placeholder-gray-400 italic"
            />
          </div>
          <div className="mb-6 flex bg-[#1E1E1E] rounded-2xl px-4 pt-3 pb-3 flex-col">
            <label className="block mb-1 text-white font-extrabold">Email</label>
            <input
              type="email"
              placeholder="Enter your email here"
              value={email}
              onChange={(e) => setEmail(e.target.value)}
              required
              className="w-full bg-[#1E1E1E] text-white rounded-lg focus:outline-none placeholder-gray-400 italic"
            />
          </div>
          <div className="flex bg-[#1E1E1E] rounded-2xl pl-4 pt-3 pb-0.5 flex-col">
            <label className="block text-white font-extrabold">Password</label>
            <div className="flex items-center bg-[#1E1E1E] rounded-lg">
              <input
                type={showPassword ? "text" : "password"}
                placeholder="Enter your password"
                value={password}
                onChange={(e) => setPassword(e.target.value)}
                required
                className="w-full bg-[#1E1E1E] text-white rounded-lg focus:outline-none placeholder-gray-400 italic"
              />
              <button
                type="button"
                className="text-white text-sm font-semibold"
                onClick={() => setShowPassword(!showPassword)}
              >
                {showPassword ? "Hide" : "Show"}
              </button>
            </div>
          </div>
          <div className="w-full flex justify-center mb-6 mt-6">
            <button type="submit" className="flex px-8 py-2 bg-[#F16C71] hover:bg-[#ec565b] text-white font-extrabold rounded-xl">Sign Up</button>
          </div>
        </form>
        {message && <p className="text-center text-red-500 mt-2">{message}</p>}

        <div className="flex gap-8 mb-4">
          <button 
            onClick={handleGoogleSignup}
            className="flex items-center gap-2 px-6 py-3 bg-[#212121] text-white rounded-lg w-full justify-center border border-neutral-700"
          >
            <SlSocialGoogle/>
            <span className="text-sm font-extrabold">Continue with Google</span>
          </button>
          <button 
            onClick={handleFacebookSignup}
            className="flex items-center gap-2 px-6 py-3 bg-[#212121] text-white rounded-lg w-full justify-center border border-neutral-700"
          >
            <FiFacebook />
            <span className="text-sm font-extrabold">Continue with Facebook</span>
          </button>
        </div>
        <p className="text-center space-x-2">
          <span className="text-[#444444] font-extrabold">Already have an account?</span> <Link to="/login" className=" font-bold">Log in</Link>
        </p>
        <div className="text-center mt-4 text-xs">
          By clicking "Sign up", you agree to the Terms of Use and Privacy Policy
        </div>
      </div>
    </div>
  );
}

export default Signup;

SSOCallback Component

import { useEffect } from "react";
import { useNavigate } from "react-router-dom";
import { useSignIn } from "@clerk/clerk-react";

function SSOCallback() {
  const { signIn, isLoaded } = useSignIn();
  const navigate = useNavigate();

  useEffect(() => {
    if (!isLoaded) {
      return;
    }

    // Complete the OAuth flow
    async function completeSignIn() {
      try {
        const result = await signIn.attemptFirstFactor({
          strategy: "oauth_callback",
        });
        
        if (result.status === "complete") {
          navigate("/CreateCompany");
        } else {
          navigate("/login");
        }
      } catch (err) {
        console.error("Error completing OAuth flow", err);
        navigate("/login");
      }
    }

    completeSignIn();
  }, [isLoaded, signIn, navigate]);

  return (
    <div className="flex items-center justify-center min-h-screen">
      <div className="text-center">
        <h2 className="text-xl font-bold mb-4">Completing authentication...</h2>
        <p>Please wait while we finish logging you in.</p>
      </div>
    </div>
  );
}

export default SSOCallback;
发布评论

评论列表(0)

  1. 暂无评论