Get hands-on experience with 20+ free Google Cloud products and $300 in free credit for new customers.

Extract bearer token from Authorization when separated by multiple spaces

Not applicable

How do you capture an OAuth access token into a variable when the token is separated from the Bearer authentication scheme keyword by multiple spaces?

The Authorization header has this ABNF:

credentials = auth-scheme [ 1*SP ( token68 / [ ( "," / auth-param )
    *( OWS "," [ OWS auth-param ] ) ] ) ]

RFC 6750 says that the auth-scheme in that ABNF is "bearer" (case insensitive), so I have to extract the token from the value after that with any amount of spaces.

I have found only one way to do this and it is very kludgey: Extract the token with preceding spaces and use a bit of JavaScript to trim it. So, this means I have an Extract like this:

<ExtractVariables name="Extract-Access-Token">
    <DisplayName>Extract access token from Authorization request header</DisplayName>
    <Header name="Authorization">
        <!-- No space between "Bearer" and the accessToken variable -->
        <Pattern ignoreCase="true">Bearer{accessToken}</Pattern>
    </Header>
    <IgnoreUnresolvedVariables>true</IgnoreUnresolvedVariables>
    <VariablePrefix>clientRequest</VariablePrefix>
</ExtractVariables>

Then, I can use a bit of JavaScript to trim the leading spaces. This is less than ideal. Is there no better way?

TIA!

Solved Solved
1 18 17K
1 ACCEPTED SOLUTION

HI @Travis Spencer

Welcome to the community !!!

I am assuming you are passing the bearer token to Apigee and validating that using the VerifyAccessToken operation that is available within the OAuth policy

If this policy executes correctly, the token is actually stored in a flow variable called "access_token". It automatically removes the "Bearer" from it. You can use this variable anywhere in the flow context. The only condition is that this variable gets populated if the policy executes correctly. The policy should handle the spaces and just store the token in that variable.

View solution in original post

18 REPLIES 18
Top Solution Authors