Change AWS temporary credential expiry time - swift

I have following code in my iOS application which is integrated with Amazon Cognito identity pool. My identity pool is integrated with criipto which is a third party authentication provider. token parameter is the authentication token that I get from third party provider.
func federateToIdentityPools(token : String) async throws -> Bool{
guard let authCognitoPlugin = try Amplify.Auth.getPlugin(
for: "awsCognitoAuthPlugin") as? AWSCognitoAuthPlugin else {
fatalError("Unable to get the Auth plugin")
}
do {
let result = try await authCognitoPlugin.federateToIdentityPool(
withProviderToken: token, for: .oidc("test.criipto.id"))
print("Federation successful with result: \(result.credentials.accessKeyId)")
print("Federation successful with result: \(result.credentials.secretAccessKey)")
print("Federation successful with result: \( result.credentials.expiration)")
return true
} catch {
print("Failed to federate to identity pools with error: \(error)")
return false
}
}
I get printed the credentials successfully. Now I want to change the expiration time for the credentials. For that what I did is changing the Maximum session duration from IAM roles for Authenticated role in identity pool.
But that doesn't change the credential expiration time.
Question 1 - How to change the expiration time for the temporary AWS credential that I get?
Question 2 - Is there a way that we can refresh the temporary AWS credentials when expired without federated identity provider's token?

You can go directly to the Cognito Authenticated Role within IAM and change the max session time.
Here's how to do this through the Console: https://docs.aws.amazon.com/IAM/latest/UserGuide/roles-managingrole-editing-console.html#roles-modify_max-session-duration
You can also update the role using the CLI (update-role) and updating the max-session-duration parameter.
You can also use the UpdateRole API and you can set this using the MaxSessionDuration parameter.
On your second question, I don't believe this will be possible as is. Maybe there could be some way to cache things, but I would avoid going down this path. The token issued from the IdP must still be valid and therefore you might want to explore how long tokens are valid from the IdP. I'm not familiar with the IdP you're using, but I would look into what's possible there.

Related

NestJS & Passport: Change JWT token on user password change?

I'm trying to reset/change the token (JWT) for users who changed their passwords on NestJS API with PassportJS. Here is a clean example of how this authorization works: https://docs.nestjs.com/security/authentication.
I want to generate a new token on password change to make sure, that on every device on which the user was logged in, after password change they will get unauthorized and so logged out.
This is how I handle the password change in users service:
async changePassword(uId: string, password: any) {
return await this.userRepository.createQueryBuilder()
.update(User)
.set({ password: await bcrypt.hash(password.value, 10) })
.where("userId = :userId", { userId: uId })
.execute();
}
There are no prebuild methods to do this I think. JwtService got only 5 methods: decode, sign (this one is used to generate a token), signAsync, verify and verifyAsync.
So how can I do this properly?
You'd need some sort of way to invalidate the JWT that was already given to the user. As you can't just do that to a token, generally (it's stateless, it holds its own validity) you'd need to create a JWT restrictlist in a database that you check the incoming JWT against. If the JWT is in the restrictlist, reject the request. Otherwise, let it through (if it's valid of course)

Single use secret in Hashicorp vault

Is it possible with any secret engine to have a "single use" password?
I have a command that generates an rsa keypair for users, and would like them to retrieve their private key. I can obviously print it out, or write to file etc, but thought it would be nice if it was stored in a "single use" place in vault? Then the user could retrieve it via the UI, and know that no-one else has viewed it. If someone else viewed it they would need to regenerate.
Basically can we have a vault key that can only be read once?
You can create a policy that only has access to that secret, for example
# policy: rsa
path "secret/rsa" {
capabilities = ["read"]
}
and then create a wrapped token for that policy, for example
$ vault token create -policy=rsa -num_uses=1 -wrap-ttl=120
Key Value
--- -----
wrapping_token: s.9QFJ8mRxGJD0e7kFfFIbdpDM
wrapping_accessor: S0zKNUr2ENbnCtj0YyriO31b
wrapping_token_ttl: 2m
wrapping_token_creation_time: 2019-12-17 09:45:42.537057 -0800 PST
wrapping_token_creation_path: auth/token/create
wrapped_accessor: VmBKXoc19ZLZlHGl0nQCvV6r
This will generate a wrapped token.
You can give that to your end user and they can unwrap it with
VAULT_TOKEN="s.3Kf3Xfn58Asr3bSDkRXATHrw" vault unwrap
which will generate a token.
With that token, the user will be able to login to vault and retrieve the rsa creds only once since the token will be invalid afterwards.
You can now guarantee that the creds have only been used from the target user as the wrapped token can be unwrapped only once.
Note: you might need to adjust num_uses when you create the token if your end user goes through the UI as the UI might use the token to perform more than one actions.
more info

Auth 0 configuration audience

I just found out that I have a problem with auth0 and it relates to the auth0 configuration audience. So when I explicitly write the audience, the JWT verification failed with error The provided Algorithm doesn't match the one defined in the JWT's Header. When I don't write the audience, everything will work fine, except now everytime the token expire and user click on login link it skip the login process and immediately logged in with the previous credential. I don't want this to happen, I want user to still authenticate themselves again after token expire, just like when I write the audience.
So what is audience and why does it affect the behaviour like this?
And How can I fix it to get the behaviour I wanted?
Below is the configuration of the Auth0
auth0 = new auth0.WebAuth({
clientID: environment.auth0ClientId,
domain: environment.auth0Domain,
responseType: 'token id_token',
//Below is the audience I'm talking about
audience: '${constants.MY_APP}/userinfo',
redirectUri: `${constants.ORIGIN_URL}/auth`,
scope: 'openid email'
});
I need to know how I can make the JWT to be verified correctly as well as make the login behaviour correctly when the JWT expire.
Auth0 can issue two types of tokens: opaque and JWT.
When you specify the audience parameter, you will receive a JWT token. JWTs differ from opaque tokens in that they are self-contained and therefore you verify them directly in your application.
In this case, the JWT you have received is signed with an algorithm different to that which you've defined in your verification logic. You can decode the JWT using https://jwt.io and you can see which algorithm it was signed with in the alg attribute of the header.
You can also find out the signing algorithm your API uses in the Auth0 dashboard. Go APIs, click your API, click the Settings tab and then scroll to Token Setting. You will see it listed as the Signing Algorithm.
Judging by the error message, you are using the java-jwt library, in which case you will need change the signing algorithm accordingly per the steps outlined here: https://github.com/auth0/java-jwt#verify-a-token
For HS256:
try {
Algorithm algorithm = Algorithm.HMAC256("secret");
JWTVerifier verifier = JWT.require(algorithm)
.withIssuer("auth0")
.build(); //Reusable verifier instance
DecodedJWT jwt = verifier.verify(token);
} catch (JWTVerificationException exception){
//Invalid signature/claims
}
Where secret is your API's Signing Secret.
For RS256, it's a little more involved. You first need to decode the token to retrieve the kid (key ID) from the header:
String token = "eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXUyJ9.eyJpc3MiOiJhdXRoMCJ9.AbIJTDMFc7yUa5MhvcP03nJPyCPzZtQcGEp-zWfOkEE";
try {
DecodedJWT jwt = JWT.decode(token);
} catch (JWTDecodeException exception){
//Invalid token
}
You then need to construct a JwkProvider using the jwks-rsa-java library:
JwkProvider provider = new UrlJwkProvider("https://your-domain.auth0.com/");
Jwk jwk = provider.get(jwt.getKeyId());
Finally, you can use the public key retrieved from the JWKS and use it to verify the token:
RSAPublicKey publicKey = (RSAPublicKey) jwk.getPublicKey();
try {
Algorithm algorithm = Algorithm.RSA256(publicKey, null);
JWTVerifier verifier = JWT.require(algorithm)
.withIssuer("auth0")
.build(); //Reusable verifier instance
DecodedJWT jwt = verifier.verify(token);
} catch (JWTVerificationException exception) {
//Invalid signature/claims
}
Keep in mind that it's preferred to use RS256 over HS256 for the reasons outlined here: https://auth0.com/docs/apis#signing-algorithms
You may also find this article useful for detailed information on verifying tokens: https://auth0.com/docs/api-auth/tutorials/verify-access-token

Firebase verifyIdToken + NodeJS Express Authentication design

Problem:
Due to legislation I have to store personal information within the EU (Social security number). Therefore I can't store this information in Firebase since there is no guarantee of geographical datacenter location when using Google's cloud services.
My proposed solution:
Having a Redis key value store with the sensitive information that can be accessed via a simple REST api where user authentication would be achieved using the users ID token, sent via HTTP Headers.
Firebase allows for verification of a user via the verifyIdToken method in the NodeJS library. This would allow me to check if the user ID matches any user id in my /admin end point of my Firebase. (Or I could hardcode the userIDs that would be allowed into the server since there aren't that many.)
So, the flow of the request would be as follows:
User signs in client side using the Firebase SDK.
Whenever the user needs access to the sensitive information it first gets the user's ID token
let currentUser = FIRAuth.auth()?.currentUser
currentUser?.getTokenForcingRefresh(true) {idToken, error in
if let error = error {
return
}
let headers = [
"X-FBUser-Token":idToken
]
//build request here to https://myServer.com/myEndpoint
}
Then server side we would retrieve the request
app.get('/myEndpoint', function(req, res) {
let idToken = req.get('X-FBUser-Token')
verifyToken(idToken, function(isAdmin){
if (isAdmin) {
//Fetch the key value pair and send it back to the client here
}
})
})
function verifyToken(idToken, cb) {
firebase.auth().verifyIdToken(idToken).then(function(decodedToken) {
var uid = decodedToken.sub;
firebase.database().ref('admins/' + uid).on('value', function (snap){
cb(snap.val() !== null)
})
}).catch(function(error) {
// Handle error
});
}
And then the client would receive back the response and deal with it. Everything done over HTTPS ofcourse.
Note: I know that the code above is rather crude and would need some refinement, but hopefully you get the concept
My questions:
First of all, is this a safe way of doing things?
Is there a better, more straight forward approach?

How to deal with anonymous login attempts when you allow both anonymous access and logged in users?

I have a framework that allows anonymous access as well as named user accounts. I'm exposing an OData resource on a certain URL. When configured as such, anonymous users can see parts of the resource and logged in users (through basic authentication) can see more.
The problem I'm facing is that some OData clients (like Excel) will initially attempt to access the OData resource anonymously even when you do provide credentials. Only when this fails, they will use the provided credentials. My understanding is that this is because there are many ways to log in and some clients just always try the most basic option first. But this prevents them from ever actually seeing more data, because they never use the provided credentials and also never get the authentication challenge when the resource allows anonymous access.
Is there a way to solve this issue, allowing both anonymous access AND properly sending an authentication challenge when possible? Is there maybe some header that clients will send when they do have credentials but just aren't supplying them initially?
Some (scala) code to make this a bit more tangible:
val (username, password) = getAuthInfo(request)
if (username != null && password != null) {
val regularSession = integration.core.login(username, password)
logger.debug(s"Login OK: User '$username' (Number of concurrent sessions: ${integration.core.getNumberConcurrentSessions}).")
(IMxRuntimeResponse.OK, null, regularSession)
} else if (integration.configuration.getEnableGuestLogin) {
val guestSession = integration.core.initializeGuestSession
logger.debug(s"Anonymous user '${guestSession.getUser.getName}' created " +
"(Number of concurrent sessions: ${integration.core.getNumberConcurrentSessions}).")
(IMxRuntimeResponse.OK, null, guestSession)
} else {
val responseMessage = "No basic authentication in header."
logger.warn(s"Login failed: $responseMessage")
(IMxRuntimeResponse.UNAUTHORIZED, responseMessage, null)
}
Somewhere else outside the surrounding try/catch:
if (httpStatusCode == IMxRuntimeResponse.UNAUTHORIZED)
response.addHeader("WWW-Authenticate", "Basic")
As you can see the challenge is never sent when anonymous access is allowed.
Edit: we investigated and there does not seem to be anything special in the headers of this request that would indicate this is an initial attempt that will result in another request when an authentication challenge is sent, rather than just another anonymous login attempt. We are at a loss here now on how to proceed.