Giter Site home page Giter Site logo

remix-auth-github's Introduction

GitHubStrategy

The GitHub strategy is used to authenticate users against a GitHub account. It extends the OAuth2Strategy.

Supported runtimes

Runtime Has Support
Node.js โœ…
Cloudflare โœ…

Usage

Create an OAuth application

Follow the steps on the GitHub documentation to create a new application and get a client ID and secret.

Create the strategy instance

import { GitHubStrategy } from "remix-auth-github";

let gitHubStrategy = new GitHubStrategy(
  {
    clientID: "YOUR_CLIENT_ID",
    clientSecret: "YOUR_CLIENT_SECRET",
    callbackURL: "https://example.com/auth/github/callback",
  },
  async ({ accessToken, extraParams, profile }) => {
    // Get the user data from your DB or API using the tokens and profile
    return User.findOrCreate({ email: profile.emails[0].value });
  }
);

authenticator.use(gitHubStrategy);

Setup your routes

// app/routes/login.tsx
export default function Login() {
  return (
    <Form action="/auth/github" method="post">
      <button>Login with GitHub</button>
    </Form>
  );
}
// app/routes/auth/github.tsx
import type { ActionFunctionArgs } from "@remix-run/node";
import { redirect } from "@remix-run/node";
import { authenticator } from "~/auth.server";

export async function loader() {
  return redirect("/login");
}

export async function action({ request }: ActionFunctionArgs) {
  return authenticator.authenticate("github", request);
};
// app/routes/auth/github/callback.tsx
import type { LoaderFunctionArgs } from "@remix-run/node";
import { authenticator } from "~/auth.server";

export async function loader({ request }: LoaderFunctionArgs) {
  return authenticator.authenticate("github", request, {
    successRedirect: "/dashboard",
    failureRedirect: "/login",
  });
};

remix-auth-github's People

Contributors

alvaaz avatar danielsteman avatar dependabot[bot] avatar haines avatar jacobparis avatar michaeldeboey avatar nartc avatar puemos avatar sergiodxa avatar sferadev avatar swalker326 avatar therealflyingcoder avatar

Stargazers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

Watchers

 avatar  avatar  avatar

remix-auth-github's Issues

Issue with async call in documentation

When attempting to use the strategy as documented I'm getting the following error:

Argument of type '(accessToken: any, _: any, extraParams: any, profile: any) => Promise' is not assignable to parameter of type 'StrategyVerifyCallback<any, OAuth2StrategyVerifyParams<GitHubProfile, GitHubExtraParams>>'.

How to expand scope after initial auth?

I would like a user to be able to initially authenticate with GitHub with minimum scopes and then within my app click to grant the ones they want so that it is not all or nothing. Is there a good strategy for this?

Similar to these questions:

So far, all I can think of is making a second instance of GitHubStrategy with the expanded scopes, and then have an action that logs out the user and then logs back in using that strategy, but it would be optimal to not have to log them out because logging out (await authenticator.logout(request, { redirectTo: "/" });) redirects and then we will redirect again on login, so it is a bit messy for the dev and user.

github strategy not working with remix-auth-socials

Followed the steps in below link and getting the below mentioned errors
https://github.com/TheRealFlyingCoder/remix-auth-socials

Error: Missing access token.
    at GitHubStrategy2.failure
    at GitHubStrategy2.authenticate
    at async loader
    at async callRouteLoaderRR
    at async callLoaderOrAction
    at async Promise.all (index 0)
    at async loadRouteData
    at async queryImpl
    at async Object.query
    at async handleDocumentRequestRR 

API logs show the below entries for remix dev

[mf:inf] GET /login 200 OK (9ms)
[mf:inf] POST /auth/github 204 No Content (6ms)                                                                                                                           
[mf:inf] GET /auth/github/callback 302 Found (684ms)
[mf:inf] GET /login 200 OK (7ms)

Redirect happens back from github oauth page but after that

authenticate(
    params.provider,
    request,
    {
      successRedirect: "/account",
      failureRedirect: "/login",
    }
  )

function detects sends to failureRedirect.

Release fetch-email feature

Hi,
would it be possible for you to actually release the feature that fetches the email-addresses from the emails endpoint?

Thank you very much,
Best,
Michel

Error installing remix-auth-github

I am getting error when installing remix-auth-github.

$ npm i remix-auth-github
npm ERR! ERESOLVE could not resolve
npm ERR! 
.
.
.
npm ERR! 
npm ERR! Could not resolve dependency:
npm ERR! remix-auth-github@"*" from the root project
npm ERR! 
npm ERR! Conflicting peer dependency: @remix-run/[email protected]
npm ERR! node_modules/@remix-run/server-runtime
npm ERR!   peer @remix-run/server-runtime@"^1.0.0" from [email protected]
npm ERR!   node_modules/remix-auth-github
npm ERR!     remix-auth-github@"*" from the root project
npm ERR! 
npm ERR! Fix the upstream dependency conflict, or retry
npm ERR! this command with --force or --legacy-peer-deps
npm ERR! to accept an incorrect (and potentially broken) dependency resolution.

Feature Request: pass logged in user data for account linking in the callback

This is about a new Feature Request

currently there is no way to detect if a user is logged in or not with the callback that we pass into the GitHubStrategy(config, callback)

if we somehow were able to pass additional data to the callback, we could pass current logged-in user data to the callback and we could link the Google Account of the user to their account in our system.

new GitHubStrategy(
  { clientID, clientSecret, callbackURL },
  async ({ profile }, additionalData) => {

    if (!additionalData?.user) {
      throw new Error("Please Login First");
    }

    const email = profile.emails && profile.emails[0].value;

    invariant(email, "GitHub profile must have an email address");

    const user = await linkGoogleAccountToUser(email, additionalData.user)

    return user;
  }
);

and in our action function that handles account linking

const user = await getUser(request);
await authenticator.authenticate("github", request, {
    additionalData: { user }
});

Support GitHub App with OAuth

GitHub allows apps to optionally add OAuth during the app installation, see step 11 here. In this case, your callback URL is called directly after a user installs the app on GitHub.com with an auth code to exchange for a user token. However, this library fails to handle this because there is no state (relevant code). Below example url signature for this scenario.

Please add support for this auth flow!

http://localhost:3000/auth/github/callback?code=01234567890abcdef012&installation_id=01234567&setup_action=install

Debug error in console: OAuth2Strategy State from URL null

Code being returned rather than token

Maybe I am mis understanding the usage of the library but I have an oauth request set up as follows.

authenticator.use(
new OAuth2Strategy(
{
authorizationURL: "amazon login url",
tokenURL: "amazon token url",
clientID: "client id",
clientSecret: "secret",
callbackURL: "http://localhost:3000/test",
},
async ({ accessToken, refreshToken, extraParams, profile, context, request }) => {

  return { accessToken };
}

),

The authenticator is called in the loader of my home page as below

export async function loader({ request }: LoaderArgs) {
const token = await authenticator.isAuthenticated(request);

if (token) {
console.log("** Authenticated");
return { message: "test" };
} else {
console.log("** Not Authenticated");
await authenticator.authenticate("oauth-provider", request);
}
}

This redirects to an AWS Cognito login, which after entering my credentials returns to the the callbackURL of

"http://localhost:3000/test",

which was specified in the OAuth2Strategy config. When redirecting here the code is returned in the url along with a state param. I was expecting the library to do the call to the token url and to return the token. Which I'm sure it does - I am just getting something wrong?

At is this point calling authenticator.isAuthenticed(request) returns null.

Any help would be much appreciated, thank you.

Update to support Remix v2

The package.json remix-auth lists @remix-run/react": "^1.0.0 || ^2.0.0" as a peerDependency, while remix-auth-github only lists "^1.0.0". This makes it incompatible with Remix v2.

Support use `state` query params to verify auth callback?

When redirect to github auth url, we can bring a state query param and when auth success github will add this state to the callback url query, we can use it to verify if this callback call is valid.

For example we can put a time string in state, and verify if it is outdated in callback

Support for GitHub App Auth?

It seems like this package only supports authentication for GitHub OAuth but there is also GitHub App authentication, which then can be piggybacked on for GitHub App Installation authentication. An example of this in use is when you connect repos to a Vercel account and it lets you select which repos to give access to. This is not possible with simple GitHub OAuth authentication. Would love it if this could be supported.

Recommend Projects

  • React photo React

    A declarative, efficient, and flexible JavaScript library for building user interfaces.

  • Vue.js photo Vue.js

    ๐Ÿ–– Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.

  • Typescript photo Typescript

    TypeScript is a superset of JavaScript that compiles to clean JavaScript output.

  • TensorFlow photo TensorFlow

    An Open Source Machine Learning Framework for Everyone

  • Django photo Django

    The Web framework for perfectionists with deadlines.

  • D3 photo D3

    Bring data to life with SVG, Canvas and HTML. ๐Ÿ“Š๐Ÿ“ˆ๐ŸŽ‰

Recommend Topics

  • javascript

    JavaScript (JS) is a lightweight interpreted programming language with first-class functions.

  • web

    Some thing interesting about web. New door for the world.

  • server

    A server is a program made to process requests and deliver data to clients.

  • Machine learning

    Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.

  • Game

    Some thing interesting about game, make everyone happy.

Recommend Org

  • Facebook photo Facebook

    We are working to build community through open source technology. NB: members must have two-factor auth.

  • Microsoft photo Microsoft

    Open source projects and samples from Microsoft.

  • Google photo Google

    Google โค๏ธ Open Source for everyone.

  • D3 photo D3

    Data-Driven Documents codes.