pka / actix-web-oauth2

Actix web Oauth2 examples
MIT License
55 stars 9 forks source link

How to share pkce verifier with auth redirect endpoint #2

Open himat opened 4 years ago

himat commented 4 years ago

I ran the example, and on the redirect page, I get

Google returned the following state:
<some string>

Google returned the following token:
CodeTokenRequest { auth_type: BasicAuth, client_id: ClientId("something-string.apps.googleusercontent.com"), client_secret: Some(ClientSecret([redacted])), code: AuthorizationCode([redacted]), extra_params: [], pkce_verifier: None, token_url: Some(TokenUrl("https://www.googleapis.com/oauth2/v3/token")), redirect_url: Some(RedirectUrl("http://localhost:8080/auth-redir-google")), _phantom: PhantomData }

But I want to get the actual access token from this.

In the code, we have

// Exchange the code for a token.
let token = &data.oauth.exchange_code(code);

and this token variable is the 2nd thing that is printed above.

token is of type oauth2::CodeTokenRequest.

So I want to call .request on the CodeTokenRequest. But I get an error here because to call .request, we have to do this:

let token_result =
    client
        .exchange_code(AuthorizationCode::new("some authorization code".to_string()))
        // Set the PKCE code verifier.
        .set_pkce_verifier(pkce_verifier)
        .request(http_client)?;

But the pkce_verifier was generated in the login route, whereas we call .exchange_code in the redirect route.

let (pkce_code_challenge, pkce_code_verifier) = PkceCodeChallenge::new_random_sha256() // happens in login

So how do I set the pkce verifier in the auth route which is handled by a different function than the login route?

brozansk commented 3 years ago

You could share it via an encrypted Cookie (with SameSite:Lax set so that you get it when auth redirect endpoint is hit back). However, I think that using PKCE, in this case, is not required at all. PKCE is required when the client is public (i.e. it's a mobile app or a single-page website) and there is a risk that the auth code would be intercepted. Basically, your secret key is no more secret. See: https://tools.ietf.org/html/rfc7636 and https://medium.com/identity-beyond-borders/what-the-heck-is-pkce-40662e801a76.

Btw, the example is missing checking of CSRF that is returned in query parameter on the redirect endpoint. It should be shared via a cookie as well.