Reauthentication
Authgear provides an easy method to reauthenticate the end-users. You can use this as a security measure to protect sensitive operations.

Overview

Reauthentication in Authgear is built on top of the OIDC ID token. The ID token is a JWT.
Your sensitive operation server endpoint MUST require the ID token. When you receive the ID token, you MUST verify the signature of it. If the signature is valid, you can trust the claims inside the ID token.
The auth_time claim in the ID token tells when was the end-user last authenticated. You should check the auth_time claim to see if the end-user was authenticated recently enough.
The https://authgear.com/claims/user/can_reauthenticate claim in the ID token tells whether the end-user can be reauthenticated. If the value of this claim is false, then depending on your business needs, you can either allow the end-user to proceed, or forbid the end-user to perform sensitive operations. The flows are illustrated by the following diagrams.
Sequence diagram for end-user who CANNOT reauthenticate
Sequence diagram for end-user who CAN reauthenticate

SDK Integration

The following code snippets illustrate the interaction between the SDK and Authgear.
React Native
Web
iOS
Android
1
async function onClickPerformSensitiveOperation() {
2
// Step 1: Refresh the ID token to ensure the claims are up-to-date.
3
await authgear.refreshIDToken();
4
5
// Step 2: Check if the end-user can be reauthenticated.
6
const canReauthenticate = authgear.canReauthenticate();
7
if (!canReauthenticate) {
8
// Step 2.1: Depending on your business need, you may want to allow
9
// the end-user to proceed.
10
// Here we assume you want to proceed.
11
12
const idTokenHint = authgear.getIDTokenHint();
13
14
// Step 2.2: Call the sensitive endpoint with the ID token.
15
// It is still required to pass the ID token to the endpoint so that
16
// the endpoint can know the end-user CANNOT be reauthenticated.
17
return callMySensitiveEndpoint(idTokenHint);
18
}
19
20
// Step 3: The end-user can be reauthenticated.
21
await authgear.reauthenticate({
22
redirectURI: THE_REDIRECT_URI,
23
});
24
25
// Step 4: If we reach here, the reauthentication was done.
26
// The ID token have up-to-date auth_time claim.
27
const idTokenHint = authgear.getIDTokenHint();
28
29
return callMySensitiveEndpoint(idTokenHint);
30
}
Copied!
1
async function onClickPerformSensitiveOperation() {
2
// Step 1: Refresh the ID token to ensure the claims are up-to-date.
3
await authgear.refreshIDToken();
4
5
// Step 2: Check if the end-user can be reauthenticated.
6
const canReauthenticate = authgear.canReauthenticate();
7
if (!canReauthenticate) {
8
// Step 2.1: Depending on your business need, you may want to allow
9
// the end-user to proceed.
10
// Here we assume you want to proceed.
11
12
const idTokenHint = authgear.getIDTokenHint();
13
14
// Step 2.2: Call the sensitive endpoint with the ID token.
15
// It is still required to pass the ID token to the endpoint so that
16
// the endpoint can know the end-user CANNOT be reauthenticated.
17
return callMySensitiveEndpoint(idTokenHint);
18
}
19
20
// Step 3: The end-user can be reauthenticated.
21
// The end-user will be redirected to Authgear.
22
// When the reauthentication finishes,
23
// The end-user will be redirected back to the given redirect URI.
24
await authgear.startReauthentication({
25
redirectURI: THE_REDIRECT_URI
26
});
27
}
28
29
// Suppose the following function is run when the end-user is redirected to
30
// the redirect URI
31
async function onRedirectAfterReauthentication() {
32
// You HAVE to configure authgear again
33
// because your website have been visited freshly.
34
await authgear.finishReauthentication();
35
await authgear.refreshIDToken();
36
const idTokenHint = authgear.getIDTokenHint();
37
return callMySensitiveEndpoint(idTokenHint);
38
}
Copied!
1
func onClickPerformSensitiveOperation() {
2
// Step 1: Refresh the ID token to ensure the claims are up-to-date.
3
authgear.refreshIDToken() { result in
4
switch result {
5
case .success:
6
// Step 2: Check if the end-user can be reauthenticated.
7
let canReauthenticate = authgear.canReauthenticate
8
if !canReauthenticate {
9
// Step 2.1: Depending on your business need, you may want to allow
10
// the end-user to proceed.
11
// Here we assume you want to proceed.
12
let idTokenHint = authgear.idTokenHint
13
// Step 2.2: Call the sensitive endpoint with the ID token.
14
// It is still required to pass the ID token to the endpoint
15
// so that the endpoint can know the end-user CANNOT
16
// be reauthenticated.
17
callMySensitiveEndpoint(idTokenHint)
18
return
19
}
20
21
// Step 3: The end-user can be reauthenticated.
22
authgear.reauthenticate(redirectURI: THE_REDIRECT_URI) { result in
23
switch result {
24
case .success:
25
// Step 4: If we reach here, the reauthentication was done.
26
// The ID token have up-to-date auth_time claim.
27
let idTokenHint = authgear.idTokenHint
28
callMySensitiveEndpoint(idTokenHint)
29
return
30
case let .failure(error):
31
// Handle the error
32
}
33
}
34
case let .failure(error):
35
// Handle the error
36
}
37
}
38
}
Copied!
1
public void onClickPerformSensitiveOperation() {
2
// Step 1: Refresh the ID token to ensure the claims are up-to-date.
3
authgear.refreshIDToken(new OnRefreshIDTokenListener() {
4
@Override
5
public void onFailed(Throwable throwable) {
6
// Handle error
7
}
8
@Override
9
public void onFinished() {
10
// Step 2: Check if the end-user can be reauthenticated.
11
boolean canReauthenticate = authgear.getCanReauthenticate();
12
if (!canReauthenticate) {
13
// Step 2.1: Depending on your business need, you may want to allow
14
// the end-user to proceed.
15
// Here we assume you want to proceed.
16
String idTokenHint = authgear.getIDTokenHint();
17
// Step 2.2: Call the sensitive endpoint with the ID token.
18
// It is still required to pass the ID token to the endpoint
19
// so that the endpoint can know the end-user CANNOT
20
// be reauthenticated.
21
callMySensitiveEndpoint(idTokenHint);
22
return;
23
}
24
25
// Step 3: The end-user can be reauthenticated.
26
ReauthenticateOptions options =
27
new ReauthenticateOptions(THE_REDIRECT_URI);
28
authgear.reauthenticate(options, null, new OnReauthenticateListener() {
29
@Override
30
public void onFailed(Throwable throwable) {
31
// Handle error
32
}
33
@Override
34
public void onFinished(ReauthenticateResult) {
35
// Step 4: If we reach here, the reauthentication was done.
36
// The ID token have up-to-date auth_time claim.
37
String idTokenHint = authgear.getIDTokenHint();
38
callMySensitiveEndpoint(idTokenHint);
39
return;
40
}
41
});
42
}
43
});
44
}
Copied!

Reauthenticate conditionally by the last authentication time

If the end-users in your application often perform a series of sensitive operation, it is annoying that they have to reauthenticate themselves repeatedly before every operation. To allow the end-users to skip reauthentication if they have just reauthenticated themselves recently, the SDK allows you to inspect the last authentication time of the end-user.
JavaScript
iOS
Android
1
async function onClickPerformSensitiveOperation() {
2
await authgear.refreshIDToken();
3
// Before you trigger reauthentication, check authTime first.
4
const authTime = authgear.getAuthTime();
5
if (authTime != null) {
6
const now = new Date();
7
const timeDelta = now.getTime() - authTime.getTime();
8
if (timeDelta < 5 * 60 * 1000 /* 5 minutes */) {
9
const idTokenHint = authgear.getIDTokenHint();
10
return callMySensitiveEndpoint(idTokenHint);
11
}
12
}
13
14
// Otherwise trigger authentication.
15
}
Copied!
1
func onClickPerformSensitiveOperation() {
2
authgear.refreshIDToken() { result in
3
switch result {
4
case .success:
5
// Before you trigger reauthentication, check authTime first.
6
if let authTime = authgear.authTime {
7
let now = Date()
8
let timeDelta = now.timeIntervalSince(authTime)
9
if timeDelta < 5 * 60 {
10
let idTokenHint = authgear.idTokenHint
11
callMySensitiveEndpoint(idTokenHint)
12
return
13
}
14
}
15
// Otherwise trigger authentication.
16
case let .failure(error):
17
// Handle the error
18
}
19
}
20
}
Copied!
1
public void onClickPerformSensitiveOperation() {
2
authgear.refreshIDToken(new OnRefreshIDTokenListener() {
3
@Override
4
public void onFailed(Throwable throwable) {
5
// Handle error
6
}
7
@Override
8
public void onFinished() {
9
// Before you trigger reauthentication, check authTime first.
10
Date authTime = authgear.getAuthTime();
11
if (authTime != null) {
12
Date now = new Date();
13
long timedelta = now.getTime() - authTime.getTime();
14
if (timedelta < 5 * 60 * 1000) {
15
String idTokenHint = authgear.getIDTokenHint();
16
callMySensitiveEndpoint(idTokenHint);
17
return;
18
}
19
}
20
// Otherwise trigger authentication.
21
}
22
});
23
}
Copied!

Backend Integration

Finally in your backend, you have to verify the signature of the ID token, and then validate the claims inside.
Python
Go
1
import json
2
from contextlib import closing
3
from urllib.request import urlopen
4
from datetime import datetime, timezone, timedelta
5
6
import jwt
7
from jwt import PyJWKClient
8
9
base_address = "https://<your_app_endpoint>"
10
11
def fetch_jwks_uri(base_address):
12
doc_url = base_address + "/.well-known/openid-configuration"
13
with closing(urlopen(doc_url)) as f:
14
doc = json.load(f)
15
jwks_uri = doc["jwks_uri"]
16
if not jwks_uri:
17
raise Exception('Failed to fetch jwks uri.')
18
return jwks_uri
19
20
def my_endpoint():
21
id_token = GET_ID_TOKEN_FROM_HTTP_REQUEST_SOMEHOW()
22
try:
23
jwks_uri = fetch_jwks_uri(base_address)
24
# Reuse PyJWKClient for better performance
25
jwks_client = PyJWKClient(jwks_uri)
26
signing_key = jwks_client.get_signing_key_from_jwt(id_token)
27
claims = jwt.decode(
28
id_token,
29
signing_key.key,
30
algorithms=["RS256"],
31
audience=base_address,
32
options={"verify_exp": True},
33
)
34
auth_time = claims["auth_time"]
35
dt = datetime.fromtimestamp(auth_time)
36
now = datetime.utcnow()
37
delta = now - dt
38
if delta > timedelta(minutes=5):
39
raise ValueError("auth_time is not recent enough")
40
except:
41
# Handle error
42
raise
Copied!
1
package main
2
3
import (
4
"context"
5
"encoding/json"
6
"fmt"
7
"net/http"
8
"time"
9
10
"github.com/lestrrat-go/jwx/jwk"
11
"github.com/lestrrat-go/jwx/jwt"
12
)
13
14
var (
15
baseAddress = "https://<your_app_endpoint>"
16
)
17
18
type OIDCDiscoveryDocument struct {
19
JWKSURI string `json:"jwks_uri"`
20
}
21
22
func FetchOIDCDiscoveryDocument(endpoint string) (*OIDCDiscoveryDocument, error) {
23
resp, err := http.DefaultClient.Get(endpoint)
24
if err != nil {
25
return nil, err
26
}
27
defer resp.Body.Close()
28
29
if resp.StatusCode != http.StatusOK {
30
return nil, fmt.Errorf(
31
"failed to fetch discovery document: unexpected status code: %d",
32
resp.StatusCode,
33
)
34
}
35
36
var document OIDCDiscoveryDocument
37
err = json.NewDecoder(resp.Body).Decode(&document)
38
if err != nil {
39
return nil, err
40
}
41
return &document, nil
42
}
43
44
func FetchJWK(baseAddress string) (jwk.Set, error) {
45
doc, err := FetchOIDCDiscoveryDocument(
46
baseAddress + "/.well-known/openid-configuration",
47
)
48
if err != nil {
49
return nil, err
50
}
51
52
set, err := jwk.Fetch(context.Background(), doc.JWKSURI)
53
return set, err
54
}
55
56
func CheckIDToken(idToken string) error {
57
// fetch jwks_uri from Authgear
58
// you can cache the value of jwks to have better performance
59
set, err := FetchJWK(baseAddress)
60
if err != nil {
61
return fmt.Errorf("failed to fetch JWK: %s", err)
62
}
63
64
// parse jwt token
65
token, err := jwt.ParseString(idToken, jwt.WithKeySet(set))
66
if err != nil {
67
return fmt.Errorf("invalid token: %s", err)
68
}
69
70
// validate jwt token
71
err = jwt.Validate(token,
72
jwt.WithClock(jwt.ClockFunc(
73
func() time.Time { return time.Now().UTC() },
74
)),
75
jwt.WithIssuer(baseAddress),
76
)
77
if err != nil {
78
return fmt.Errorf("invalid token: %s", err)
79
}
80
81
authTimeAny, ok := token.Get("auth_time")
82
if !ok {
83
return fmt.Errorf("no auth_time")
84
}
85
86
authTimeUnix, ok := authTimeAny.(float64)
87
if !ok {
88
return fmt.Errorf("auth_time is not number")
89
}
90
91
authTime := time.Unix(int64(authTimeUnix), 0)
92
now := time.Now().UTC()
93
94
diff := now.Sub(authTime)
95
if diff > 5*time.Minute {
96
return fmt.Errorf("auth_time is not recent enough")
97
}
98
99
return nil
100
}
Copied!
Last modified 3mo ago