How to configure CouchDB to only accept JWTs with a specific aud (audience) claim? - couchdb

The title says it all, really. If you have a JWT from google, for example, it have an aud claim with the id of your app. Otherwise any site owner could use any JWT to log into any other site.

You should configure this in required_claims, the provided example of a claim with a parameter is an iss claim:
;[jwt_auth]
; List of claims to validate
; can be the name of a claim like "exp" or a tuple if the claim requires
; a parameter
; required_claims = exp, {iss, "IssuerNameHere"}
but that could be changed to different claims, i.e.:
[jwt_auth]
required_claims = iat, exp, {aud, "my-project"}

Related

Are the MSAL claims constants available in a package somewhere?

I've moved my authentication to MSAL and I want to examine my claims on the client side to see, for example, the object ID that I have in Azure B2C (and thus, give my client an identity).
On the server, the objectId claim appears to be returned as:
{http://schemas.xmlsoap.org/ws/2005/05/identity/claims/nameidentifier: 63fd3d89-26ff-4934-907c-5e6c9da07c45}
The URI "http://schemas.xmlsoap.org/ws/2005/05/identity/claims/nameidentifier" is a known claim and can be accessed using Claims.Name and I can use a statement like this to extract the objectId from the claims:
Guid userId = new(this.User.FindFirstValue(ClaimTypes.NameIdentifier));
But on the client, the objectId claim is returned using the 'oid' URI and I can't use the same kind of pre-defined claims that I can on the server.
Obviously I can define these as constants in a shared module, but I can't be the only one trying to parse claims from the client side. Is there an analog of 'ClaimTypes' for MSAL on the client side?
I was searching for the same thing and found the ClaimConstants.ObjectId (see here) to match the oid claim type (http://schemas.microsoft.com/identity/claims/objectidentifier).
Guid userId = new(this.User.FindFirstValue(ClaimConstants.ObjectId));
It's part of the Microsoft.Identity.Web package.

Azure Active Directory JWT aud value

In JWT from AAD there is a key 'aud'. https://jwt.io/, says it is 'Audience. (Who or what the the token is intended for)'. My question is, Are aud values website specific - can I check the aud and expect it to be same to check if the token is intended for my specific site?
In Azure AD, the audience value always indicates the resource the token is targeted on.
You can acquire an access token by using either the API's client id or Application ID URI.
What you use will be the audience in the token.
So if you make an API, you should check the audience is either the API's client id or Application ID URI.
You can know for sure it will always be one of those if the token is meant for your API.
EDIT: The below information is not correct.
If I know your API's identifier + your tenant id,
I can acquire an access token for your API using client credentials!
The token will not contain scopes or roles, it cannot.
So it is critical that you check for the presence of valid delegated permissions (aka scopes) or valid app permissions (in roles claim).
THIS IS WRONG: If I tried to acquire an access token using your API's identifier from my AAD tenant, it would not give me a token.
Any app that passes an access token with the correct audience had rights to call your API when it acquired the token.
You already got a good explanation of the audience value from juunas.
I'm adding here a specific code example from Azure-Samples on Github which shows how to validate the JWT Token manually and checks among other things audience value. (It's pretty important to validate issuer as well)
Look at this particular code and especially near the comment "We accept both the App Id URI and the AppId of this service application"
JwtSecurityTokenHandler tokenHandler = new JwtSecurityTokenHandler();
TokenValidationParameters validationParameters = new TokenValidationParameters
{
// We accept both the App Id URI and the AppId of this service application
ValidAudiences = new[] { audience, clientId },
// Supports both the Azure AD V1 and V2 endpoint
ValidIssuers = new[] { issuer, $"{issuer}/v2.0" },
IssuerSigningKeys = signingKeys
};
Code Sample:
Specific file with code excerpt shown above
Azure-Samples: Manually validating a JWT access token in a web API

Azure AD Multi-tenant Applications - How to implement Token Validation?

I have a multi tenant Web app / API registered in Azure ad and that connected to an API App. The API App has Active Directory Authentication setup. At the moment only one other tenant needs access to api. I made sure only they can get access by putting https://sts.windows.net/<third party tenant>/ in the Issuer URL. My question is: How would I go about giving a second (or more) tenants access to the api? I can't add anymore tenant ids in the Issuer URL so I'm kinda at a loss
Thanks
The approach you are using currently will work only in a single tenant scenario, i.e. Automatic validation of tenant by setting IssuerURL works only in a single tenant scenario.
In case of multi-tenant applications, the application is responsible for storing and validating all possible issuers. This is by design and exact guidance on this topic from Microsoft is available here:
Work with claims-based identities in Azure AD: Issuer Validation
For a single-tenant application, you can just check that the issuer is
your own tenant. In fact, the OIDC middleware does this automatically
by default. In a multi-tenant app, you need to allow for multiple
issuers, corresponding to the different tenants. Here is a general
approach to use:
In the OIDC middleware options, set ValidateIssuer to false. This turns off the automatic check.
When a tenant signs up, store the tenant and the issuer in your user DB.
Whenever a user signs in, look up the issuer in the database.If the issuer isn't found, it means that tenant hasn't signed up. You
can redirect them to a sign up page.
You could also blacklist certain tenants; for example, for customers that didn't pay their subscription.
So, in case of a .NET based web application the code in your startup class would change to something like this.. notice the new TokenValidationParameters { ValidateIssuer = false }
Authenticate using Azure AD and OpenID Connect
app.UseOpenIdConnectAuthentication(new OpenIdConnectOptions {
ClientId = configOptions.AzureAd.ClientId,
ClientSecret = configOptions.AzureAd.ClientSecret, // for code flow
Authority = Constants.AuthEndpointPrefix,
ResponseType = OpenIdConnectResponseType.CodeIdToken,
PostLogoutRedirectUri = configOptions.AzureAd.PostLogoutRedirectUri,
SignInScheme = CookieAuthenticationDefaults.AuthenticationScheme,
TokenValidationParameters = new TokenValidationParameters { ValidateIssuer = false },
Events = new SurveyAuthenticationEvents(configOptions.AzureAd, loggerFactory),
});
Once you have disabled the Validate issuer, you will need to handle the validation yourself. Here is a sample with some guidance around how to do this validation yourself
Update your code to handle multiple issuer values
You will at least need to check the "tid" claim which captures the Azure AD Tenant Id against your own list of valid tenant IDs, before you let the call go through.
When a single tenant application validates a token, it checks the
signature of the token against the signing keys from the metadata
document, and makes sure the issuer value in the token matches the one
that was found in the metadata document.
Since the /common endpoint doesn’t correspond to a tenant and isn’t an
issuer, when you examine the issuer value in the metadata for /common
it has a templated URL instead of an actual value:
https://sts.windows.net/{tenantid}/
Therefore, a multi-tenant application can’t validate tokens just by
matching the issuer value in the metadata with the issuer value in the
token. A multi-tenant application needs logic to decide which issuer
values are valid and which are not, based on the tenant ID portion of
the issuer value.
For example, if a multi-tenant application only allows sign in from
specific tenants who have signed up for their service, then it must
check either the issuer value or the tid claim value in the token to
make sure that tenant is in their list of subscribers. If a
multi-tenant application only deals with individuals and doesn’t make
any access decisions based on tenants, then it can ignore the issuer
value altogether.
(EDIT) More information on Validating Tokens
I'm trying to answer your questions from comments here.
Here is sample code which does the task of manually validating JWT tokens.
Manually validating a JWT access token in a web API
A useful excerpt..
Validating the claims When an application receives an access token
upon user sign-in, it should also perform a few checks against the
claims in the access token. These verifications include but are not
limited to:
audience claim, to verify that the ID token was intended to be given
to your application not before and "expiration time" claims, to verify
that the ID token has not expired issuer claim, to verify that the
token was issued to your app by the v2.0 endpoint nonce, as a token
replay attack mitigation You are advised to use standard library
methods like JwtSecurityTokenHandler.ValidateToken Method
(JwtSecurityToken) to do most of the aforementioned heavy lifting. You
can further extend the validation process by making decisions based on
claims received in the token. For example, multi-tenant applications
can extend the standard validation by inspecting value of the tid
claim (Tenant ID) against a set of pre-selected tenants to ensure they
only honor token from tenants of their choice.
Sample Access Token, just for understanding: Access Token and Id_token are both simple base64 encoded JSON Web Tokens (JWT). You can decode these to find the claims and then validate them. I'm sharing a sample which has code to do just that. Before that here is a sample access token from one of Microsoft Docs. I just took one for example from here
Actual Value: eyJ0eXAiOiJKV1QiLCJhbGciOiJSUzI1N... (a long encoded string continues)
Decoded Value (you can check this easily using a website like https://jwt.io):
{
"aud": "https://service.contoso.com/",
"iss": "https://sts.windows.net/7fe81447-da57-4385-becb-6de57f21477e/",
"iat": 1388440863,
"nbf": 1388440863,
"exp": 1388444763,
"ver": "1.0",
"tid": "7fe81447-da57-4385-becb-6de57f21477e",
"oid": "68389ae2-62fa-4b18-91fe-53dd109d74f5",
"upn": "frankm#contoso.com",
"unique_name": "frankm#contoso.com",
"sub": "deNqIj9IOE9PWJWbHsftXt2EabPVl0Cj8QAmefRLV98",
"family_name": "Miller",
"given_name": "Frank",
"appid": "2d4d11a2-f814-46a7-890a-274a72a7309e",
"appidacr": "0",
"scp": "user_impersonation",
"acr": "1"
}
As you can see the decoded value has many claims including "tid" which you're about to validate.
Hope this helps!

What is the purpose of claims request parameter on OAuth 2.0?

OpenID specification 5.5 explain RP can request claims using claims request parameter. http://openid.net/specs/openid-connect-core-1_0.html#ClaimsParameter
What is the purpose of this feature?
Is it this feature create security vulnerabilities as user able to set claims?
For example user can modify URL on browser into:
https://op.example.com/authorize?
response_type=code
&client_id=client
&redirect_uri=https://client.example.com
&scope=openid
&claims={“userinfo” : {“sub”: { “value” : “superuser”}} , “id_token” : {“sub”: { “value” : “superuser” }}}
If OP implements this feature, then OP put that claims into id token and user info.
The purpose of this feature is to request claims, possibly with a certain desired value. It does not mean that the RP is able to set claim values. Instead the OP should verify which of the requested claims and values match for the authenticated user and return only those claims that are valid.

Using JWT audience field for authorization roles

I'm considering using the JWT audience field to implement role-based authorization in my app.
So I'd have ServiceA which requires 'RoleA' audience to be present, ServiceB requires 'RoleB' etc. Then when I issue the JWT, I include the appropriate audience(s).
Relevant section from the JWT draft spec:
The aud (audience) claim identifies the recipients that the JWT is intended for. Each principal intended to process the JWT MUST identify itself with a value in the audience claim. If the principal processing the claim does not identify itself with a value in the aud claim when this claim is present, then the JWT MUST be rejected... The interpretation of audience values is generally application specific.
So it appears that would work but since I'm new to JWT I'm wondering: is role-based authorization an appropriate use case for the audience field? Or should I roll my own logic using a payload with custom roles array etc?
Thanks
I understand audience rather then list of consumers/applications who can authorize the user.
In my application I put roles into own array in the payload. For example like that.
{
"sub": 1234567890,
"exp": 9876543210,
"name": "John Doe",
"roles": ["USER", "EDITOR"]
}
On the server I am authorized using spring security and user loaded from "sub".
And on the client I can use these roles to show proper buttons and fields.

Resources