Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Configure how RabbitMQ determines the username from an OAuth 2.0 token #6247

Closed
wants to merge 3 commits into from
Closed
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
32 changes: 30 additions & 2 deletions deps/rabbitmq_auth_backend_oauth2/README.md
Original file line number Diff line number Diff line change
Expand Up @@ -10,7 +10,6 @@ The plugin supports several identity providers, sometimes with vendor-specific c
* [Keycloak](https://github.com/rabbitmq/rabbitmq-oauth2-tutorial/blob/rich_auth_request/use-cases/keycloak.md)
* [Microsoft AD on Azure](https://github.com/rabbitmq/rabbitmq-oauth2-tutorial/blob/rich_auth_request/use-cases/azure.md)
* [Auth0](https://github.com/rabbitmq/rabbitmq-oauth2-tutorial/blob/rich_auth_request/use-cases/oauth0.md)
* [IdentityServer 4](https://github.com/rabbitmq/rabbitmq-oauth2-tutorial/blob/rich_auth_request/use-cases/identityServer4.md)

An OAuth 2.0 primer is available [elsewhere on the Web](https://auth0.com/blog/oauth2-the-complete-guide/).

Expand Down Expand Up @@ -66,7 +65,7 @@ go over the contentes below and also an example for your service provider:
* [Keycloak](https://github.com/rabbitmq/rabbitmq-oauth2-tutorial/blob/rich_auth_request/use-cases/keycloak.md)
* [Microsoft AD on Azure](https://github.com/rabbitmq/rabbitmq-oauth2-tutorial/blob/rich_auth_request/use-cases/azure.md)
* [Auth0](https://github.com/rabbitmq/rabbitmq-oauth2-tutorial/blob/rich_auth_request/use-cases/oauth0.md)
* [IdentityServer 4](https://github.com/rabbitmq/rabbitmq-oauth2-tutorial/blob/rich_auth_request/use-cases/identityServer4.md)


### UAA

Expand Down Expand Up @@ -175,6 +174,7 @@ Note: if both are configured, `jwks_url` takes precedence over `signing_keys`.
| `auth_oauth2.https.hostname_verification`| Enable wildcard-aware hostname verification for key server. Available values: `wildcard`, `none`. Default is `none`.
| `auth_oauth2.algorithms` | Restrict [the usable algorithms](https://github.com/potatosalad/erlang-jose#algorithm-support).
| `auth_oauth2.verify_aud` | [Verify token's `aud`](#token-validation).
| `auth_oauth2.preferred_username_claims` | [Determine user identity](#determine-user-identity).

Two examples below demonstrate a set of key files and a JWKS key server.

Expand Down Expand Up @@ -212,6 +212,34 @@ client has been granted. The scopes are free form strings.
`resource_server_id` is a prefix used for scopes in UAA to avoid scope collisions (or unintended overlap).
It is an empty string by default.

## Determine user identity

Although OAuth 2.0 is all about authorization there are two situations where we need to determine the
user's identity. One is when we display the user's name in the management ui. And the second one is
when we have to capture the user identity in some logging statement.

By default, RabbitMQ first looks up the JWT claim `sub`. And if it is not present, it uses `client_id`.
Else it uses `unknown`. In other words, RabbitMQ could not figure out the user's identity from the token.

It is quite often that Identity Providers reserve the `sub` claim for the user's internal GUID and it uses instead
a different claim for the actual username such as `username`, `user_name` or `emailaddress` and similar.

For the latter case, RabbitMQ exposes a new configuration setting which can be either a single string or
an array of strings. Given the configuration below, RabbitMQ uses the following claims in the same order to
resolve the user's identity: `username`, `user_name`, `email`, `sub`, `client_id`.

```erlang
[
{rabbitmq_auth_backend_oauth2, [
{resource_server_id, <<"my_rabbit_server">>},
{preferred_username_claims, [ <<"username">>, <<"user_name">>, <<"email">> ]}
{key_config, [
{jwks_url, <<"https://jwt-issuer.my-domain.local/jwks.json">>}
]}
]},
].
```

## Token Verification

When RabbitMQ receives a JWT token, it validates it before accepting it.
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -60,6 +60,29 @@
"rabbitmq_auth_backend_oauth2.verify_aud",
[{datatype, {enum, [true, false]}}]}.

%% Configure the preferred username's JWT claim(s). These are the JWT claims or attributes
%% used to determine the user's identity, a.k.a username.
%% RabbitMQ appends `sub` and `client_id` claims.
%% e.g. RabbitMQ first looks for username claim. If it is not present, it looks for user_name
%% and so forth. If it cannot find any, it defauls to unknown.
%% {preferred_username_claims, [<<"username">>, <<"user_name">>, <<"email">> ]},

{mapping,
"auth_oauth2.preferred_username_claims",
"rabbitmq_auth_backend_oauth2.preferred_username_claims",
[{datatype, string}]}.

{translation,
"rabbitmq_auth_backend_oauth2.preferred_username_claims",
fun(Conf) ->
list_to_binary(cuttlefish:conf_get("auth_oauth2.preferred_username_claims", Conf))
end}.

{mapping,
"auth_oauth2.additional_scopes_key",
"rabbitmq_auth_backend_oauth2.extra_scopes_source",
[{datatype, string}]}.


%% ID of the default signing key
%%
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -42,6 +42,9 @@
-define(COMPLEX_CLAIM_APP_ENV_KEY, extra_scopes_source).
%% scope aliases map "role names" to a set of scopes
-define(SCOPE_MAPPINGS_APP_ENV_KEY, scope_aliases).
%% list of JWT claims (such as <<"sub">>) used to determine the username
-define(PREFERRED_USERNAME_CLAIMS, preferred_username_claims).
-define(DEFAULT_PREFERRED_USERNAME_CLAIMS, [<<"sub">>, <<"client_id">>]).

%%
%% Key JWT fields
Expand Down Expand Up @@ -119,7 +122,7 @@ update_state(AuthUser, NewToken) ->

%%--------------------------------------------------------------------

authenticate(Username0, AuthProps0) ->
authenticate(_, AuthProps0) ->
AuthProps = to_map(AuthProps0),
Token = token_from_context(AuthProps),
case check_token(Token) of
Expand All @@ -131,7 +134,9 @@ authenticate(Username0, AuthProps0) ->
{refused, "Authentication using an OAuth 2/JWT token failed: ~tp", [Err]};
{ok, DecodedToken} ->
Func = fun() ->
Username = username_from(Username0, DecodedToken),
Username = username_from(
application:get_env(?APP, ?PREFERRED_USERNAME_CLAIMS, []),
DecodedToken),
Tags = tags_from(DecodedToken),

{ok, #auth_user{username = Username,
Expand Down Expand Up @@ -542,24 +547,35 @@ token_from_context(AuthProps) ->
%% <<"sub">> => <<"rabbit_client">>,
%% <<"zid">> => <<"uaa">>}

-spec username_from(binary(), map()) -> binary() | undefined.
username_from(ClientProvidedUsername, DecodedToken) ->
ClientId = uaa_jwt:client_id(DecodedToken, undefined),
Sub = uaa_jwt:sub(DecodedToken, undefined),

rabbit_log:debug("Computing username from client's JWT token, client ID: '~ts', sub: '~ts'",
[ClientId, Sub]),
-spec username_from(list(), map()) -> binary() | undefined.
username_from(PreferredUsernameClaims, DecodedToken) ->
UsernameClaims = append_or_return_default(PreferredUsernameClaims, ?DEFAULT_PREFERRED_USERNAME_CLAIMS),
ResolvedUsernameClaims = lists:filtermap(fun(Claim) -> find_claim_in_token(Claim, DecodedToken) end, UsernameClaims),
Username = case ResolvedUsernameClaims of
[ ] -> <<"unknown">>;
[ _One ] -> _One;
[ _One | _ ] -> _One
end,
rabbit_log:debug("Computing username from client's JWT token: ~ts -> ~ts ",
[lists:flatten(io_lib:format("~p",[ResolvedUsernameClaims])), Username]),
Username.

append_or_return_default(ListOrBinary, Default) ->
case ListOrBinary of
undefined -> Default;
<<>> -> Default;
[] -> Default;
VarList when is_list(VarList) -> VarList ++ Default;
VarBinary when is_binary(VarBinary) -> [VarBinary] ++ Default;
_ -> Default
end.

case uaa_jwt:client_id(DecodedToken, Sub) of
undefined ->
case ClientProvidedUsername of
undefined -> undefined;
<<>> -> undefined;
_Other -> ClientProvidedUsername
end;
Value ->
Value
end.
find_claim_in_token(Claim, Token) ->
case maps:get(Claim, Token, undefined) of
undefined -> false;
ClaimValue when is_binary(ClaimValue) -> {true, ClaimValue};
_ -> false
end.

-define(TAG_SCOPE_PREFIX, <<"tag:">>).

Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -87,6 +87,9 @@ token_with_scopes_and_expiration(Scopes, Expiration) ->
fixture_token() ->
fixture_token([]).

token_with_sub(TokenFixture, Sub) ->
maps:put(<<"sub">>, Sub, TokenFixture).

fixture_token(ExtraScopes) ->
Scopes = [<<"rabbitmq.configure:vhost/foo">>,
<<"rabbitmq.write:vhost/foo">>,
Expand Down
Loading