Skip to content

Commit

Permalink
Add credentials for bearer token authentication
Browse files Browse the repository at this point in the history
  • Loading branch information
richirisu committed Feb 4, 2025
1 parent 98e29db commit d3be1b2
Show file tree
Hide file tree
Showing 2 changed files with 36 additions and 1 deletion.
7 changes: 7 additions & 0 deletions sdk/lib/_http/http.dart
Original file line number Diff line number Diff line change
Expand Up @@ -2065,6 +2065,13 @@ abstract final class HttpClientBasicCredentials
_HttpClientBasicCredentials(username, password);
}

/// Represents credentials for bearer token authentication.
abstract final class HttpClientBearerCredentials
implements HttpClientCredentials {
factory HttpClientBearerCredentials(String token) =>
_HttpClientBearerCredentials(token);
}

/// Represents credentials for digest authentication. Digest
/// authentication is only supported for servers using the MD5
/// algorithm and quality of protection (qop) of either "none" or
Expand Down
30 changes: 29 additions & 1 deletion sdk/lib/_http/http_impl.dart
Original file line number Diff line number Diff line change
Expand Up @@ -3900,18 +3900,21 @@ class _AuthenticationScheme {

static const UNKNOWN = _AuthenticationScheme(-1);
static const BASIC = _AuthenticationScheme(0);
static const DIGEST = _AuthenticationScheme(1);
static const BEARER = _AuthenticationScheme(1);
static const DIGEST = _AuthenticationScheme(2);

const _AuthenticationScheme(this._scheme);

factory _AuthenticationScheme.fromString(String scheme) {
if (scheme.toLowerCase() == "basic") return BASIC;
if (scheme.toLowerCase() == "bearer") return BEARER;
if (scheme.toLowerCase() == "digest") return DIGEST;
return UNKNOWN;
}

String toString() {
if (this == BASIC) return "Basic";
if (this == BEARER) return "Bearer";
if (this == DIGEST) return "Digest";
return "Unknown";
}
Expand Down Expand Up @@ -4038,6 +4041,31 @@ final class _HttpClientBasicCredentials extends _HttpClientCredentials
}
}

final class _HttpClientBearerCredentials extends _HttpClientCredentials
implements HttpClientBearerCredentials {
String token;

_HttpClientBearerCredentials(this.token) {
if (RegExp(r'[^0-9A-Za-z\-._~+/=]').hasMatch(token)) {
throw ArgumentError.value(token, "token", "Invalid characters");
}
}

_AuthenticationScheme get scheme => _AuthenticationScheme.BEARER;

String authorization() {
return "Bearer $token";
}

void authorize(_Credentials _, HttpClientRequest request) {
request.headers.set(HttpHeaders.authorizationHeader, authorization());
}

void authorizeProxy(_ProxyCredentials _, HttpClientRequest request) {
request.headers.set(HttpHeaders.proxyAuthorizationHeader, authorization());
}
}

final class _HttpClientDigestCredentials extends _HttpClientCredentials
implements HttpClientDigestCredentials {
String username;
Expand Down

0 comments on commit d3be1b2

Please sign in to comment.