Skip to content

proposal: net/http: add methods to Request for setting and getting Bearer tokens #70522

Open
@jub0bs

Description

@jub0bs

Proposal Details

I propose the addition of the following two methods:

// SetBearerAuth, if the provided token is valid, sets the request's
// Authorization header to use the Bearer authentication scheme with that token
// and returns true.
// Otherwise, it leaves the request unchanged and returns false.
// See RFC 6750, Section 2.1.
func (*Request) SetBearerAuth(token string) bool

// BearerAuth returns the token provided in the request's
// Authorization header, if the request uses the Bearer authentication scheme.
func (r *Request) BearerAuth() (token string, ok bool)

Those methods parallel ones related to HTTP Basic Authentication already exported by net/http:

At first, you may think that the logic for getting/setting a Bearer token is so trivial that it doesn't deserve its own methods in the standard library. However, I've come to realise that many implementations out there suffer from correctness issues and/or performance issues; here are two examples (among others):

Moreover, and despite my lack of data to back up the following claim, I believe that Bearer is one of the most popular authentication scheme nowadays (likely even more popular than Basic), given the prominent role it plays in OAuth 2.x and OpenID Connect. Therefore, the logic required for parsing a request's Authorization header that uses Bearer arguably deserves to be enshrined in the standard library.

This playground contains a standalone implementation as well as a test suite. For convenience, SetBearerAuth and BearerAuth are presented there as package-level functions rather than as *Request methods.

Metadata

Metadata

Assignees

No one assigned

    Labels

    Type

    No type

    Projects

    Status

    Incoming

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions