working on key management
Signed-off-by: Stephan Richter <s.richter@srsoftware.de>
This commit is contained in:
@@ -11,6 +11,7 @@ import de.srsoftware.oidc.api.*;
|
||||
import java.io.IOException;
|
||||
import java.time.Duration;
|
||||
import java.time.Instant;
|
||||
import java.util.Arrays;
|
||||
import java.util.HashSet;
|
||||
import java.util.Map;
|
||||
import java.util.UUID;
|
||||
@@ -29,8 +30,11 @@ public class ClientController extends Controller {
|
||||
|
||||
|
||||
private boolean authorize(HttpExchange ex, Session session) throws IOException {
|
||||
var user = session.user();
|
||||
var json = json(ex);
|
||||
var user = session.user();
|
||||
var json = json(ex);
|
||||
var scope = json.getString(SCOPE);
|
||||
if (!Arrays.asList(scope.split(" ")).contains(OPENID)) return sendContent(ex, HTTP_BAD_REQUEST, Map.of(ERROR, "openid scope missing in request"));
|
||||
|
||||
var clientId = json.getString(CLIENT_ID);
|
||||
var redirect = json.getString(REDIRECT_URI);
|
||||
var optClient = clients.getClient(clientId);
|
||||
@@ -74,8 +78,7 @@ public class ClientController extends Controller {
|
||||
case "/":
|
||||
return deleteClient(ex, session);
|
||||
}
|
||||
LOG.log(ERROR, "not implemented");
|
||||
return sendEmptyResponse(HTTP_NOT_FOUND, ex);
|
||||
return notFound(ex);
|
||||
}
|
||||
|
||||
|
||||
|
||||
@@ -0,0 +1,20 @@
|
||||
/* © SRSoftware 2024 */
|
||||
package de.srsoftware.oidc.backend;
|
||||
|
||||
import com.sun.net.httpserver.HttpExchange;
|
||||
import de.srsoftware.oidc.api.KeyStorage;
|
||||
import de.srsoftware.oidc.api.PathHandler;
|
||||
import java.io.IOException;
|
||||
|
||||
public class KeyStoreController extends PathHandler {
|
||||
private final KeyStorage keyStore;
|
||||
|
||||
public KeyStoreController(KeyStorage keyStorage) {
|
||||
keyStore = keyStorage;
|
||||
}
|
||||
|
||||
@Override
|
||||
public boolean doGet(String path, HttpExchange ex) throws IOException {
|
||||
return super.doGet(path, ex);
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,39 @@
|
||||
/* © SRSoftware 2024 */
|
||||
package de.srsoftware.oidc.backend;
|
||||
|
||||
import static org.jose4j.jws.AlgorithmIdentifiers.RSA_USING_SHA256;
|
||||
|
||||
import de.srsoftware.oidc.api.KeyManager;
|
||||
import de.srsoftware.oidc.api.KeyStorage;
|
||||
import java.io.IOException;
|
||||
import java.util.UUID;
|
||||
import org.jose4j.jwk.PublicJsonWebKey;
|
||||
import org.jose4j.jwk.RsaJwkGenerator;
|
||||
import org.jose4j.lang.JoseException;
|
||||
|
||||
public class RotatingKeyManager implements KeyManager {
|
||||
private static final System.Logger LOG = System.getLogger(RotatingKeyManager.class.getSimpleName());
|
||||
private final KeyStorage store;
|
||||
|
||||
public RotatingKeyManager(KeyStorage keyStore) {
|
||||
store = keyStore;
|
||||
}
|
||||
|
||||
@Override
|
||||
public PublicJsonWebKey getKey() throws KeyCreationException, IOException {
|
||||
var list = store.listKeys();
|
||||
return list.isEmpty() ? createNewKey() : store.load(list.get(0));
|
||||
}
|
||||
|
||||
private PublicJsonWebKey createNewKey() throws KeyCreationException, IOException {
|
||||
try {
|
||||
var key = RsaJwkGenerator.generateJwk(2048);
|
||||
key.setAlgorithm(RSA_USING_SHA256);
|
||||
key.setKeyId(UUID.randomUUID().toString());
|
||||
store.store(key);
|
||||
return key;
|
||||
} catch (JoseException e) {
|
||||
throw new KeyCreationException(e);
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -12,10 +12,10 @@ import java.net.URLDecoder;
|
||||
import java.nio.charset.StandardCharsets;
|
||||
import java.util.*;
|
||||
import java.util.stream.Collectors;
|
||||
import org.jose4j.jws.AlgorithmIdentifiers;
|
||||
import org.jose4j.jwk.PublicJsonWebKey;
|
||||
import org.jose4j.jws.JsonWebSignature;
|
||||
import org.jose4j.jwt.JwtClaims;
|
||||
import org.jose4j.keys.HmacKey;
|
||||
import org.jose4j.jwt.MalformedClaimException;
|
||||
import org.jose4j.lang.JoseException;
|
||||
import org.json.JSONObject;
|
||||
|
||||
@@ -23,11 +23,13 @@ public class TokenController extends PathHandler {
|
||||
private final ClientService clients;
|
||||
private final AuthorizationService authorizations;
|
||||
private final UserService users;
|
||||
private final KeyManager keyManager;
|
||||
|
||||
public TokenController(AuthorizationService authorizationService, ClientService clientService, UserService userService) {
|
||||
authorizations = authorizationService;
|
||||
clients = clientService;
|
||||
users = userService;
|
||||
public TokenController(AuthorizationService authorizationService, ClientService clientService, KeyManager keyManager, UserService userService) {
|
||||
authorizations = authorizationService;
|
||||
clients = clientService;
|
||||
this.keyManager = keyManager;
|
||||
users = userService;
|
||||
}
|
||||
|
||||
private Map<String, String> deserialize(String body) {
|
||||
@@ -45,7 +47,9 @@ public class TokenController extends PathHandler {
|
||||
}
|
||||
|
||||
private boolean provideToken(HttpExchange ex) throws IOException {
|
||||
var map = deserialize(body(ex));
|
||||
var map = deserialize(body(ex));
|
||||
// TODO: check data, → https://openid.net/specs/openid-connect-core-1_0.html#TokenEndpoint
|
||||
|
||||
var grantType = map.get(GRANT_TYPE);
|
||||
if (!AUTH_CODE.equals(grantType)) return sendContent(ex, HTTP_BAD_REQUEST, Map.of(ERROR, "unknown grant type", GRANT_TYPE, grantType));
|
||||
|
||||
@@ -66,8 +70,8 @@ public class TokenController extends PathHandler {
|
||||
var uri = URLDecoder.decode(map.get(REDIRECT_URI), StandardCharsets.UTF_8);
|
||||
if (!client.redirectUris().contains(uri)) sendContent(ex, HTTP_BAD_REQUEST, Map.of(ERROR, "unknown redirect uri", REDIRECT_URI, uri));
|
||||
|
||||
var secretFromClient = map.get(CLIENT_SECRET);
|
||||
if (!client.secret().equals(secretFromClient)) return sendContent(ex, HTTP_BAD_REQUEST, Map.of(ERROR, "client secret mismatch"));
|
||||
var secretFromClient = URLDecoder.decode(map.get(CLIENT_SECRET));
|
||||
if (secretFromClient != null && !client.secret().equals(secretFromClient)) return sendContent(ex, HTTP_BAD_REQUEST, Map.of(ERROR, "client secret mismatch"));
|
||||
|
||||
String jwToken = createJWT(client, user.get());
|
||||
ex.getResponseHeaders().add("Cache-Control", "no-store");
|
||||
@@ -76,42 +80,52 @@ public class TokenController extends PathHandler {
|
||||
response.put(TOKEN_TYPE, BEARER);
|
||||
response.put(EXPIRES_IN, 3600);
|
||||
response.put(ID_TOKEN, jwToken);
|
||||
LOG.log(DEBUG, jwToken);
|
||||
return sendContent(ex, response);
|
||||
}
|
||||
|
||||
private String createJWT(Client client, User user) {
|
||||
try {
|
||||
byte[] secretBytes = client.secret().getBytes(StandardCharsets.UTF_8);
|
||||
HmacKey hmacKey = new HmacKey(secretBytes);
|
||||
PublicJsonWebKey key = keyManager.getKey();
|
||||
|
||||
JwtClaims claims = getJwtClaims(user);
|
||||
JwtClaims claims = getJwtClaims(user, client);
|
||||
|
||||
// A JWT is a JWS and/or a JWE with JSON claims as the payload.
|
||||
// In this example it is a JWS so we create a JsonWebSignature object.
|
||||
JsonWebSignature jws = new JsonWebSignature();
|
||||
if (secretBytes.length * 8 < 256) {
|
||||
LOG.log(WARNING, "Using secret with less than 256 bits! You will go to hell for this!");
|
||||
jws.setDoKeyValidation(false); // TODO: this is dangerous! Better: enforce key length of 256bits!
|
||||
}
|
||||
|
||||
jws.setHeader("typ", "JWT");
|
||||
jws.setPayload(claims.toJson());
|
||||
jws.setKey(hmacKey);
|
||||
jws.setAlgorithmHeaderValue(AlgorithmIdentifiers.HMAC_SHA256);
|
||||
jws.setKey(key.getPrivateKey());
|
||||
jws.setKeyIdHeaderValue(key.getKeyId());
|
||||
jws.setAlgorithmHeaderValue(key.getAlgorithm());
|
||||
return jws.getCompactSerialization();
|
||||
} catch (JoseException e) {
|
||||
} catch (JoseException | KeyManager.KeyCreationException | IOException e) {
|
||||
throw new RuntimeException(e);
|
||||
}
|
||||
}
|
||||
|
||||
private static JwtClaims getJwtClaims(User user) {
|
||||
private static JwtClaims getJwtClaims(User user, Client client) {
|
||||
JwtClaims claims = new JwtClaims();
|
||||
claims.setIssuer(APP_NAME); // who creates the token and signs it
|
||||
claims.setExpirationTimeMinutesInTheFuture(10); // time when the token will expire (10 minutes from now)
|
||||
claims.setGeneratedJwtId(); // a unique identifier for the token
|
||||
claims.setIssuedAtToNow(); // when the token was issued/created (now)
|
||||
claims.setNotBeforeMinutesInThePast(2); // time before which the token is not yet valid (2 minutes ago)
|
||||
claims.setSubject(user.uuid()); // the subject/principal is whom the token is about
|
||||
claims.setClaim("email", user.email()); // additional claims/attributes about the subject can be added
|
||||
claims.setAudience(client.id(), "test");
|
||||
claims.setClaim("client_id", client.id());
|
||||
claims.setClaim("email", user.email()); // additional claims/attributes about the subject can be added
|
||||
claims.setExpirationTimeMinutesInTheFuture(10); // time when the token will expire (10 minutes from now)
|
||||
claims.setIssuedAtToNow(); // when the token was issued/created (now)
|
||||
claims.setIssuer("https://lightoidc.srsoftware.de"); // who creates the token and signs it
|
||||
claims.setGeneratedJwtId(); // a unique identifier for the token
|
||||
claims.setSubject(user.uuid()); // the subject/principal is whom the token is about
|
||||
|
||||
// die nachfolgenden Claims sind nur Spielerei, ich habe versucht, das System mit Umbrella zum Laufen zu bekommen
|
||||
claims.setClaim("scope", "openid");
|
||||
claims.setStringListClaim("amr", "pwd");
|
||||
claims.setClaim("at_hash", Base64.getEncoder().encodeToString("Test".getBytes(StandardCharsets.UTF_8)));
|
||||
claims.setClaim("azp", client.id());
|
||||
claims.setClaim("email_verified", true);
|
||||
try {
|
||||
claims.setClaim("rat", claims.getIssuedAt().getValue());
|
||||
} catch (MalformedClaimException e) {
|
||||
}
|
||||
return claims;
|
||||
}
|
||||
}
|
||||
|
||||
@@ -2,7 +2,6 @@
|
||||
package de.srsoftware.oidc.backend;
|
||||
|
||||
import static de.srsoftware.oidc.api.User.*;
|
||||
import static java.lang.System.Logger.Level.WARNING;
|
||||
import static java.net.HttpURLConnection.*;
|
||||
|
||||
import com.sun.net.httpserver.HttpExchange;
|
||||
@@ -31,8 +30,7 @@ public class UserController extends Controller {
|
||||
return logout(ex, session);
|
||||
}
|
||||
|
||||
LOG.log(WARNING, "not implemented");
|
||||
return sendEmptyResponse(HTTP_NOT_FOUND, ex);
|
||||
return notFound(ex);
|
||||
}
|
||||
|
||||
|
||||
|
||||
@@ -1,8 +1,6 @@
|
||||
/* © SRSoftware 2024 */
|
||||
package de.srsoftware.oidc.backend;
|
||||
|
||||
import static java.lang.System.Logger.Level.WARNING;
|
||||
import static java.net.HttpURLConnection.HTTP_NOT_FOUND;
|
||||
|
||||
import com.sun.net.httpserver.HttpExchange;
|
||||
import de.srsoftware.oidc.api.PathHandler;
|
||||
@@ -16,12 +14,11 @@ public class WellKnownController extends PathHandler {
|
||||
case "/openid-configuration":
|
||||
return openidConfig(ex);
|
||||
}
|
||||
LOG.log(WARNING, "not implemented");
|
||||
return sendEmptyResponse(HTTP_NOT_FOUND, ex);
|
||||
return notFound(ex);
|
||||
}
|
||||
|
||||
private boolean openidConfig(HttpExchange ex) throws IOException {
|
||||
var host = hostname(ex);
|
||||
return sendContent(ex, Map.of("token_endpoint", host + "/api/token", "authorization_endpoint", host + "/web/authorization.html", "userinfo_endpoint", host + "/api/userinfo", "jwks_uri", host + "/api/jwks"));
|
||||
return sendContent(ex, Map.of("token_endpoint", host + "/api/token", "authorization_endpoint", host + "/web/authorization.html", "userinfo_endpoint", host + "/api/userinfo", "jwks_uri", host + "/api/jwks", "issuer", "https://lightoidc.srsoftware.de"));
|
||||
}
|
||||
}
|
||||
|
||||
Reference in New Issue
Block a user