I am new to ADFS, OAuth and JWT and have been looking at this for a number of days; Sorry if silly question or already been answered.
I read this guide that deals with authenticating a client using a cert: signing a JWT with a certificate and verifying with the certificate manually uploaded to ADFS: https://learn.microsoft.com/en-gb/archive/blogs/cloudpfe/oauth-2-0-confidential-clients-and-active-directory-federation-services-on-windows-server-2016
It's kind of what I want but not quite - I would like to use certs for user authentication; I would like to sign the JWT with a certificate unique to AD user and be able to have ADFS verify the user in AD as according to the certificate - avoiding the need to manually upload a certificate (plus avoiding the need to upload countless number of user certificates!). Is this possible?
The other way of doing it, I was thinking of a JWKS URL with a ton of public certs but that seems mad! (Not sure how I go about producing this endpoint anyway).
I appreciate any guidance or pointing me to read articles...
Cheers!
This sounds like a feature request to have ADFS support your bespoke idea for signature creation on the ADFS side.
To help you understand this in context to how JWT is meant to work:
JWT signatures are either:
a shared-secret (defined by the JWT producer) for the HMAC-based JWT implementation.
JWK (served by JWKS) for the RSA/ECDSA implementation, or;
Or concisely:
HMAC-based; shared secret, no confidentiality, claims are public
RSA/ECDSA; private key generated by the JWT consumer so it can securely decipher (decrypt) claims data that was encrypted by the JWT producer using the public key corresponding to the client private key. Encryption makes claim data confidential. Signatures are therefore (as already described) using public keys (accessed by the client via JWKS URL hosted by the ADFS server) to do the verify method on each end without exposing the private key in more than the location it was intended to be used for decryption purposes.
It seems to me you're after a specific HMAC variation based on sharing a Certificate intended as a shared-secret, and that would undoubtedly require ADFS to sign using your shared-secret rather than generate a shared-secret on the server.
If you are after a Certificate based Authentication (authentic identity) I would strongly suggest you look at a Certificate authentication scheme rather than try make a modified-JWT scheme to fit your ideas, which it was not designed for. Mostly because you do not control the ADFS source code and can not make it perform non-standard methods or use untrusted (client provided) shared-secret for signature generation when the JWT specification does not support this.
(Also you're trying to do Certificate Authentication using JWT that is an Authorization scheme in this ADFS context)
If I get a JWT and I can decode the payload, how is that secure? Couldn't I just grab the token out of the header, decode and change the user information in the payload, and send it back with the same correct encoded secret?
I know they must be secure, but I just would really like to understand the technologies. What am I missing?
JWTs can be either signed, encrypted or both. If a token is signed, but not encrypted, everyone can read its contents, but when you don't know the private key, you can't change it. Otherwise, the receiver will notice that the signature won't match anymore.
Answer to your comment: I'm not sure if I understand your comment the right way. Just to be sure: do you know and understand digital signatures? I'll just briefly explain one variant (HMAC, which is symmetrical, but there are many others).
Let's assume Alice wants to send a JWT to Bob. They both know some shared secret. Mallory doesn't know that secret, but wants to interfere and change the JWT. To prevent that, Alice calculates Hash(payload + secret) and appends this as signature.
When receiving the message, Bob can also calculate Hash(payload + secret) to check whether the signature matches.
If however, Mallory changes something in the content, she isn't able to calculate the matching signature (which would be Hash(newContent + secret)). She doesn't know the secret and has no way of finding it out.
This means if she changes something, the signature won't match anymore, and Bob will simply not accept the JWT anymore.
Let's suppose, I send another person the message {"id":1} and sign it with Hash(content + secret). (+ is just concatenation here). I use the SHA256 Hash function, and the signature I get is: 330e7b0775561c6e95797d4dd306a150046e239986f0a1373230fda0235bda8c. Now it's your turn: play the role of Mallory and try to sign the message {"id":2}. You can't because you don't know which secret I used. If I suppose that the recipient knows the secret, he CAN calculate the signature of any message and check if it's correct.
You can go to jwt.io, paste your token and read the contents. This is jarring for a lot of people initially.
The short answer is that JWT doesn't concern itself with encryption. It cares about validation. That is to say, it can always get the answer for "Have the contents of this token been manipulated"? This means user manipulation of the JWT token is futile because the server will know and disregard the token. The server adds a signature based on the payload when issuing a token to the client. Later on it verifies the payload and matching signature.
The logical question is what is the motivation for not concerning itself with encrypted contents?
The simplest reason is because it assumes this is a solved problem for the most part. If dealing with a client like the web browser for example, you can store the JWT tokens in a cookie that is secure (is not transmitted via HTTP, only via HTTPS) and httpOnly (can't be read by Javascript) and talks to the server over an encrypted channel (HTTPS). Once you know you have a secure channel between the server and client you can securely exchange JWT or whatever else you want.
This keeps thing simple. A simple implementation makes adoption easier but it also lets each layer do what it does best (let HTTPS handle encryption).
JWT isn't meant to store sensitive data. Once the server receives the JWT token and validates it, it is free to lookup the user ID in its own database for additional information for that user (like permissions, postal address, etc). This keeps JWT small in size and avoids inadvertent information leakage because everyone knows not to keep sensitive data in JWT.
It's not too different from how cookies themselves work. Cookies often contain unencrypted payloads. If you are using HTTPS then everything is good. If you aren't then it's advisable to encrypt sensitive cookies themselves. Not doing so will mean that a man-in-the-middle attack is possible--a proxy server or ISP reads the cookies and then replays them later on pretending to be you. For similar reasons, JWT should always be exchanged over a secure layer like HTTPS.
Let's discuss from the very beginning:
JWT is a very modern, simple and secure approach which extends for Json Web Tokens. Json Web Tokens are a stateless solution for authentication. So there is no need to store any session state on the server, which of course is perfect for restful APIs.
Restful APIs should always be stateless, and the most widely used alternative to authentication with JWTs is to just store the user's log-in state on the server using sessions. But then of course does not follow the principle that says that restful APIs should be stateless and that's why solutions like JWT became popular and effective.
So now let's know how authentication actually works with Json Web Tokens. Assuming we already have a registered user in our database. So the user's client starts by making a post request with the username and the password, the application then checks if the user exists and if the password is correct, then the application will generate a unique Json Web Token for only that user.
The token is created using a secret string that is stored on a server. Next, the server then sends that JWT back to the client which will store it either in a cookie or in local storage.
Just like this, the user is authenticated and basically logged into our application without leaving any state on the server.
So the server does in fact not know which user is actually logged in, but of course, the user knows that he's logged in because he has a valid Json Web Token which is a bit like a passport to access protected parts of the application.
So again, just to make sure you got the idea. A user is logged in as soon as he gets back his unique valid Json Web Token which is not saved anywhere on the server. And so this process is therefore completely stateless.
Then, each time a user wants to access a protected route like his user profile data, for example. He sends his Json Web Token along with a request, so it's a bit like showing his passport to get access to that route.
Once the request hits the server, our app will then verify if the Json Web Token is actually valid and if the user is really who he says he is, well then the requested data will be sent to the client and if not, then there will be an error telling the user that he's not allowed to access that resource.
All this communication must happen over https, so secure encrypted Http in order to prevent that anyone can get access to passwords or Json Web Tokens. Only then we have a really secure system.
So a Json Web Token looks like left part of this screenshot which was taken from the JWT debugger at jwt.io. So essentially, it's an encoding string made up of three parts. The header, the payload and the signature Now the header is just some metadata about the token itself and the payload is the data that we can encode into the token, any data really that we want. So the more data we want to encode here the bigger the JWT. Anyway, these two parts are just plain text that will get encoded, but not encrypted.
So anyone will be able to decode them and to read them, we cannot store any sensitive data in here. But that's not a problem at all because in the third part, so in the signature, is where things really get interesting. The signature is created using the header, the payload, and the secret that is saved on the server.
And this whole process is then called signing the Json Web Token. The signing algorithm takes the header, the payload, and the secret to create a unique signature. So only this data plus the secret can create this signature, all right?
Then together with the header and the payload, these signature forms the JWT,
which then gets sent to the client.
Once the server receives a JWT to grant access to a protected route, it needs to verify it in order to determine if the user really is who he claims to be. In other words, it will verify if no one changed the header and the payload data of the token. So again, this verification step will check if no third party actually altered either the header or the payload of the Json Web Token.
So, how does this verification actually work? Well, it is actually quite straightforward. Once the JWT is received, the verification will take its header and payload, and together with the secret that is still saved on the server, basically create a test signature.
But the original signature that was generated when the JWT was first created is still in the token, right? And that's the key to this verification. Because now all we have to do is to compare the test signature with the original signature.
And if the test signature is the same as the original signature, then it means that the payload and the header have not been modified.
Because if they had been modified, then the test signature would have to be different. Therefore in this case where there has been no alteration of the data, we can then authenticate the user. And of course, if the two signatures
are actually different, well, then it means that someone tampered with the data.
Usually by trying to change the payload. But that third party manipulating the payload does of course not have access to the secret, so they cannot sign the JWT.
So the original signature will never correspond to the manipulated data.
And therefore, the verification will always fail in this case. And that's the key to making this whole system work. It's the magic that makes JWT so simple,
but also extremely powerful.
The contents in a json web token (JWT) are not inherently secure, but there is a built-in feature for verifying token authenticity. A JWT is three hashes separated by periods. The third is the signature. In a public/private key system, the issuer signs the token signature with a private key which can only be verified by its corresponding public key.
It is important to understand the distinction between issuer and verifier. The recipient of the token is responsible for verifying it.
There are two critical steps in using JWT securely in a web application: 1) send them over an encrypted channel, and 2) verify the signature immediately upon receiving it. The asymmetric nature of public key cryptography makes JWT signature verification possible. A public key verifies a JWT was signed by its matching private key. No other combination of keys can do this verification, thus preventing impersonation attempts. Follow these two steps and we can guarantee with mathematical certainty the authenticity of a JWT.
More reading: How does a public key verify a signature?
I would explain this with an example.
Say I borrowed $10 from you, then I gave you an IOU with my signature on it. I will pay you back whenever you or someone else bring this IOU back to me, I will check the signature to make sure that is mine.
I can't make sure you don't show the content of this IOU to anyone or even give it to a third person, all I care is that this IOU is signed by me, when someone shows this IOU to me and ask me to pay it.
The way how JWT works is quite the same, the server can only make sure that the token received was issued by itself.
You need other measures to make it secure, like encryption in transfer with HTTPS, making sure that the local storage storing the token is secured, setting up origins.
Ref - JWT Structure and Security
It is important to note that JWT are used for authorization and not authentication.
So a JWT will be created for you only after you have been authenticated by the server by may be specifying the credentials. Once JWT has been created for all future interactions with server JWT can be used. So JWT tells that server that this user has been authenticated, let him access the particular resource if he has the role.
Information in the payload of the JWT is visible to everyone. There can be a "Man in the Middle" attack and the contents of the JWT can be changed. So we should not pass any sensitive information like passwords in the payload. We can encrypt the payload data if we want to make it more secure. If Payload is tampered with server will recognize it.
So suppose a user has been authenticated and provided with a JWT. Generated JWT has a claim specifying role of Admin. Also the Signature is generated with
This JWT is now tampered with and suppose the
role is changed to Super Admin
Then when the server receives this token it will again generate the signature using the secret key(which only the server has) and the payload. It will not match the signature
in the JWT. So the server will know that the JWT has been tampered with.
Only JWT's privateKey, which is on your server will decrypt the encrypted JWT. Those who know the privateKey will be able to decrypt the encrypted JWT.
Hide the privateKey in a secure location in your server and never tell anyone the privateKey.
I am not a cryptography specialist and hence (I hope) my answer can help somebody who is neither.
There are two possible ways of using cryptography in programming:
Signing / verifying
Encryption / decryption
We use Signing when we want to ensure that data comes from a trusted source.
We use Encryption when we want to protect the data.
Signing / verifying uses asymmetrical algorithms i.e. we sign with one key (private) and the data receiver uses the other (public) key to verify.
A symmetric algorithm uses the same key to encrypt and decrypt data.
The encryption can be done using both symmetric and asymmetric algorithms.
relatively simple article on subject
The above is common knowledge below is my opinion.
When JWT is used for simple client-to-server identification there is no need for signing or asymmetric encryption. JWT can be encrypted with AES which is fast and supersecure. If the server can decrypt it, it means the server is the one who encrypted it.
Summary: non-encrypted JWT is not secure. Symmetric encryption can be used instead of signing in case no third party is involved.
I have seen the post with a similar title about Angular JS, but I have been searching for a C# / .net code sample of how to do this presumably common task.
I have found many articles talking about the fact that it must be done, but no straightforward "Here's how you validate an id_token returned from Azure B2C using C# and .net"
Is anyone aware of such a piece of code?
Validating an id_token is similar to the first step of validating an access token - your client should validate that the correct issuer has sent back the token and that it hasn't been tampered with. Because id_tokens are always a JWT, many libraries exist to validate these tokens - we recommend you use one of these rather than doing it yourself.
To manually validate the token, see the steps details in validating an access token. After validating the signature on the token, the following claims should be validated in the id_token (these may also be done by your token validation library):
Timestamps: the iat, nbf, and exp timestamps should all fall before or after the current time, as appropriate.
Audience: the aud claim should match the app ID for your application.
Nonce: the nonce claim in the payload must match the nonce parameter passed into the /authorize endpoint during the initial request.
you can browse through this samples to find one in the language of your choice. For more information on how to explicitly validate a JWT token, see the manual JWT validation sample.
You can check this thread as well for additional reference:
Hope it helps.
I'm trying to implement the JWT Bearer Authentication in my AspNetCore MVC app (Web API only) using the JwtBearerMiddleware but am getting a 401 response with header:
WWW-Authenticate: Bearer error="invalid_token", error_description="The signature key was not found"
The relevant code in Startup.cs looks like this:
app.UseJwtBearerAuthentication(new JwtBearerOptions
{
Authority = "https://example.okta.com",
Audience = "myClientId"
});
With the Authority URL I'd expect the middleware to query my Identity Provider metadata from https://example.okta.com/.well-known/openid-configuration to get the jwks_uri to then get the signature keys from https://example.okta.com/oauth2/v1/keys. I don't think this is happening. What do I need to do to get it to find and use the signature keys? Thanks
After following references and digging into the AspNet Security repo (specifically the JwtBearerHandler and JwtBearerMiddleware classes), which led me to the Microsoft.IdentityModel namespace which is in an Azure Extensions repo (first the ConfigurationManager<T> class, then to the OpenIdConnectConfigurationRetriever class (GetAsync method), then to the JsonWebKeySet.GetSigningKeys() method), I finally discovered that the JwtBearerMiddleware does indeed get the keys from the jwks_uri in the metadata. Phew.
So why wasn't it working? What I should've checked earlier is that the kid in the header of the Bearer JWT did not in fact match either of the kid's from the jwks_uri, hence it wasn't found. It was the access_code that I was sending as the bearer token. The id_token on the other hand does have a kid that matches, so using that instead it worked!
I've since read:
The OIDC Access Token is applicable only for the Okta
/oauth2/v1/userinfo endpoint and thus should be treated as opaque by
the application. The application does not need to validate it since it
should not be used against other resource servers. The format of it
and the key used to sign it are subject to change without prior
notice.
source
...so I can't use the access token.
I'm trying to work with the OAuth bearer tokens Web API 2 supplies but I don't know how to unencrypt them or get the data out.
What I'd really like to do is either find or write myself an equivalent tool to this Google Tool https://developers.google.com/wallet/digital/docs/jwtdecoder for the tokens I am getting from Web API. The Google tool allows you to paste in the string of text representing a JWT token and it splits it up and unencodes the JSON within.
In Visual Studio 2013 if you choose New ASP.NET project, and then choose the Web API template with individual user accounts you get a sample project that contains a token endpoint. If you start the project, you can then POST a request "grant_type=password&username=joe&password=joe" to /token on the built in webserver and you get a token back:
{
"access_token":"x3vHm40WUXBiMZi_3EmdmCWLLuv4fsgjsg4S5Ya8kppDY_-2ejn7qF5Y_nbQ0bYVIKl6MNzL2GtXv-MAuwjippAAv5VDaxoKdxEVxeFrQ_eXsKNaQK7IvmVs1rIZ9eeRfRGK2AQ59wWQcyTtYO0dPJx9K7PGrSKz4ADAZ9SEZqQ4IesVhYbRCwToyxoyU5L9qdU8jXdHumkIrULRQhf68rIaBrEA_Be-V0rzWJ644fRLvv3z69XoHs3Az7PineILyNwbDck9uU2jkaXnwxoCTa4qlK8bR-lEI9-VXPNdbCvfgb5H9wfYsJcw2CMzNxNhV8v9YVZEt90evylwtTCEpXq4T3zRCQvrpbCvZrXqJ8uvlFeqCsvvhlIkSfPhBY8nm2ocWtBGPZm58zLe5FMi1jept0B54U38ZxkZlrGQKar47jkmnc6gpLrkpDBp7cWz",
"token_type":"bearer",
"expires_in":1209599,
"userName":"joe",
".issued":"Fri, 01 Aug 2014 16:16:02 GMT",
".expires":"Fri, 15 Aug 2014 16:16:02 GMT"
}
What I want to find out is what format the access_token is in and what information is contained.
A clue I found was: you can choose what kind of tokens Web API uses by setting the OAuthAuthorizationServerOptions.AccessTokenFormat property in Startup.Auth.cs. The documentation for OAuthAuthorizationServerOptions says:
"The data format used to protect the information contained in the access token. If not provided by the application the default data protection provider depends on the host server. The SystemWeb host on IIS will use ASP.NET machine key data protection, and HttpListener and other self-hosted servers will use DPAPI data protection. If a different access token provider or format is assigned, a compatible instance must be assigned to the OAuthBearerAuthenticationOptions.AccessTokenProvider or OAuthBearerAuthenticationOptions.AccessTokenFormat property of the resource server."
So it's probably encoded using the MachineKey. That's fine, I can set the Machine Key OK but if I know the machine key that the token was created with, how do I decrypt it?
You are correct about the generation of the token. This token is an encrypted or signed string contains the de-serialized version of all the claims and ticket properties for the signed in user. If in IIS mode (SystemWeb), the encryption and signing is done via the "decryptionKey" and "validationKey" key values in machineKey node. If running as a self-host OWIN application, the encryption uses the DPAPI to protect it and that actually uses the 3DES algorithm.
To decrypt it you need to invoke this code in your API controller action method (not necessary but if you want to see what inside this encrypted token) :
string token = "Your token goes here";
Microsoft.Owin.Security.AuthenticationTicket ticket= Startup.OAuthBearerOptions.AccessTokenFormat.Unprotect(token);
If you need to configure your AuthZ server to issue JWT signed tokens so you can deconde them using someone line tool such as Google JWT decoder; then I recommend you to read my blog post here about JSON Web Token in ASP.NET Web API 2 using Owin