Initial
This commit is contained in:
commit
e67dfc067d
10 files changed
+817
No files matched your search
@@ -0,0 +1,37 @@
|
||||
# Keycloak Probe 0.1.0
|
||||
|
||||
Тестовое Android-приложение для проверки получения access token и диагностики HTTPS. Минимальная версия — Android 11 (API 30).
|
||||
|
||||
## Проверка подключения
|
||||
|
||||
1. В поле «HTTPS-адрес Keycloak» введите домен или базовый URL. Поддерживаются `my.domain`, `my.domain:449/auth` и `https://my.domain:449/auth`. При отсутствии схемы используется HTTPS. Стандартный порт — 443.
|
||||
2. Заполните Realm, Client ID, логин и пароль. Для клиента с включённой аутентификацией укажите Client Secret. Для public client оставьте поле пустым.
|
||||
3. В настройках клиента Keycloak включите Direct Access Grants. Приложение выполняет тестовый запрос `grant_type=password` и передаёт секрет клиента в поле `client_secret`.
|
||||
4. Нажмите «Получить токен». Для базового URL `https://my.domain:449/auth` и Realm `demo` запрос пойдёт на `https://my.domain:449/auth/realms/demo/protocol/openid-connect/token`.
|
||||
5. Кнопка «Копировать токен» копирует access token. Кнопка «Сохранить журнал» открывает стандартное окно Android для выбора места сохранения TXT в UTF-8. Журнал доступен после успешного запроса и после ошибки.
|
||||
|
||||
Direct Access Grants предназначен здесь для диагностики тестового клиента. Сервер должен поддерживать аутентификацию пользователя через этот поток. Подробности в [документации Keycloak](https://www.keycloak.org/securing-apps/oidc-layers#_resource_owner_password_credentials).
|
||||
|
||||
## Журнал TLS
|
||||
|
||||
Журнал включает URL запроса, HTTP-статус и длительность. После успешного рукопожатия и получения HTTP-ответа выводятся версия TLS, cipher suite, цепочка сертификатов с Subject, Issuer, сроками действия, SHA-256 и SAN конечного сертификата. При ошибке TLS выводятся тип исключения и доступные причины от Android. Если Android прерывает рукопожатие, цепочка может быть недоступна.
|
||||
|
||||
Пароль, логин, Client Secret, токен, тело запроса и содержимое HTTP-ответа в журнал не записываются. Поля формы и токен хранятся в памяти текущего экрана. Сохранённый журнал может содержать внутренние имена серверов и Realm.
|
||||
|
||||
Android проверяет сертификат и имя хоста. Приложение доверяет системным CA и CA, установленным пользователем Android. Для тестирования с корпоративным CA установите его в хранилище устройства. Приложение работает только через HTTPS. Чтобы учётные данные отправлялись на указанный адрес, HTTP-редиректы не обрабатываются.
|
||||
|
||||
## Установка и сборка
|
||||
|
||||
Установите подписанный тестовый APK через файловый менеджер Android либо выполните:
|
||||
|
||||
```bash
|
||||
adb install keycloak-probe-0.1.0.apk
|
||||
```
|
||||
|
||||
Для сборки исходников откройте каталог проекта в Android Studio с JDK 17 и установленным Android SDK Platform 35. Также можно выполнить из каталога проекта с Gradle 8.9 и настроенным Android SDK:
|
||||
|
||||
```bash
|
||||
gradle :app:assembleDebug
|
||||
```
|
||||
|
||||
Результат Gradle — `app/build/outputs/apk/debug/app-debug.apk`. APK, собранный локально, подписывается вашим отладочным ключом Android, поэтому Android может потребовать удалить тестовую сборку перед его установкой.
|
||||
@@ -0,0 +1,21 @@
|
||||
plugins {
|
||||
id 'com.android.application' version '8.7.3'
|
||||
}
|
||||
|
||||
android {
|
||||
namespace 'net.m9k.keycloakprobe'
|
||||
compileSdk 35
|
||||
|
||||
defaultConfig {
|
||||
applicationId 'net.m9k.keycloakprobe'
|
||||
minSdk 30
|
||||
targetSdk 35
|
||||
versionCode 1
|
||||
versionName '0.1.0'
|
||||
}
|
||||
|
||||
compileOptions {
|
||||
sourceCompatibility JavaVersion.VERSION_1_8
|
||||
targetCompatibility JavaVersion.VERSION_1_8
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,21 @@
|
||||
<?xml version="1.0" encoding="utf-8"?>
|
||||
<manifest xmlns:android="http://schemas.android.com/apk/res/android">
|
||||
<uses-permission android:name="android.permission.INTERNET" />
|
||||
<application
|
||||
android:allowBackup="false"
|
||||
android:label="@string/app_name"
|
||||
android:networkSecurityConfig="@xml/network_security_config"
|
||||
android:theme="@style/AppTheme"
|
||||
android:usesCleartextTraffic="false">
|
||||
<activity
|
||||
android:name=".MainActivity"
|
||||
android:configChanges="orientation|screenSize|keyboardHidden|screenLayout|smallestScreenSize"
|
||||
android:exported="true"
|
||||
android:windowSoftInputMode="adjustResize">
|
||||
<intent-filter>
|
||||
<action android:name="android.intent.action.MAIN" />
|
||||
<category android:name="android.intent.category.LAUNCHER" />
|
||||
</intent-filter>
|
||||
</activity>
|
||||
</application>
|
||||
</manifest>
|
||||
@@ -0,0 +1,227 @@
|
||||
package net.m9k.keycloakprobe;
|
||||
|
||||
import org.json.JSONException;
|
||||
import org.json.JSONObject;
|
||||
|
||||
import java.io.ByteArrayOutputStream;
|
||||
import java.io.IOException;
|
||||
import java.io.InputStream;
|
||||
import java.io.OutputStream;
|
||||
import java.net.HttpURLConnection;
|
||||
import java.nio.charset.StandardCharsets;
|
||||
import java.security.GeneralSecurityException;
|
||||
import java.security.MessageDigest;
|
||||
import java.security.cert.Certificate;
|
||||
import java.security.cert.X509Certificate;
|
||||
import java.time.Instant;
|
||||
import java.util.Arrays;
|
||||
import java.util.Locale;
|
||||
|
||||
import javax.net.ssl.HttpsURLConnection;
|
||||
import javax.net.ssl.SSLException;
|
||||
import javax.net.ssl.SSLSession;
|
||||
|
||||
final class KeycloakClient {
|
||||
private static final int TIMEOUT_MS = 15_000;
|
||||
private static final int MAX_BODY_BYTES = 1024 * 1024;
|
||||
|
||||
static final class Result {
|
||||
final String token;
|
||||
final String summary;
|
||||
final String log;
|
||||
|
||||
Result(String token, String summary, String log) {
|
||||
this.token = token;
|
||||
this.summary = summary;
|
||||
this.log = log;
|
||||
}
|
||||
}
|
||||
|
||||
Result fetch(TokenRequest request) {
|
||||
StringBuilder log = new StringBuilder();
|
||||
long start = System.nanoTime();
|
||||
line(log, "UTC: " + Instant.now());
|
||||
line(log, "POST " + request.endpoint);
|
||||
HttpsURLConnection connection = null;
|
||||
String summary;
|
||||
String token = null;
|
||||
|
||||
try {
|
||||
connection = (HttpsURLConnection) request.endpoint.openConnection();
|
||||
TlsSockets tls = new TlsSockets(connection.getSSLSocketFactory());
|
||||
connection.setSSLSocketFactory(tls);
|
||||
connection.setInstanceFollowRedirects(false);
|
||||
connection.setUseCaches(false);
|
||||
connection.setConnectTimeout(TIMEOUT_MS);
|
||||
connection.setReadTimeout(TIMEOUT_MS);
|
||||
connection.setRequestMethod("POST");
|
||||
connection.setRequestProperty("Connection", "close");
|
||||
connection.setRequestProperty("Content-Type", "application/x-www-form-urlencoded");
|
||||
connection.setRequestProperty("Accept", "application/json");
|
||||
connection.setDoOutput(true);
|
||||
|
||||
byte[] form = request.form();
|
||||
try {
|
||||
connection.setFixedLengthStreamingMode(form.length);
|
||||
try (OutputStream out = connection.getOutputStream()) {
|
||||
out.write(form);
|
||||
}
|
||||
} finally {
|
||||
Arrays.fill(form, (byte) 0);
|
||||
}
|
||||
|
||||
int status = connection.getResponseCode();
|
||||
line(log, "HTTP " + status);
|
||||
describeTls(log, connection, tls);
|
||||
if (status >= 200 && status < 300) {
|
||||
JSONObject response = new JSONObject(readBody(connection.getInputStream()));
|
||||
Object value = response.opt("access_token");
|
||||
if (value instanceof String && !((String) value).trim().isEmpty()) {
|
||||
token = (String) value;
|
||||
long expires = response.optLong("expires_in", -1);
|
||||
summary = expires >= 0
|
||||
? "Токен получен. Срок действия " + expires + " с."
|
||||
: "Токен получен.";
|
||||
line(log, "Токен получен.");
|
||||
} else {
|
||||
summary = "В ответе нет access_token.";
|
||||
line(log, summary);
|
||||
}
|
||||
} else {
|
||||
summary = describeHttpError(log, connection, status);
|
||||
}
|
||||
} catch (BodyLimitException error) {
|
||||
summary = "Ответ сервера превышает 1 МиБ.";
|
||||
line(log, summary);
|
||||
} catch (JSONException error) {
|
||||
summary = "Ответ сервера не является ожидаемым JSON.";
|
||||
line(log, summary);
|
||||
} catch (IOException error) {
|
||||
summary = describeFailure(log, error);
|
||||
} finally {
|
||||
if (connection != null) {
|
||||
connection.disconnect();
|
||||
}
|
||||
}
|
||||
|
||||
line(log, "Длительность: " + (System.nanoTime() - start) / 1_000_000 + " мс");
|
||||
return new Result(token, summary, log.toString());
|
||||
}
|
||||
|
||||
private static void describeTls(StringBuilder log, HttpsURLConnection connection,
|
||||
TlsSockets sockets) {
|
||||
try {
|
||||
SSLSession session = sockets.session();
|
||||
if (session != null && !"NONE".equals(session.getProtocol())) {
|
||||
line(log, "TLS: " + session.getProtocol());
|
||||
}
|
||||
line(log, "Cipher suite: " + connection.getCipherSuite());
|
||||
Certificate[] chain = connection.getServerCertificates();
|
||||
for (int i = 0; i < chain.length; i++) {
|
||||
if (!(chain[i] instanceof X509Certificate)) {
|
||||
continue;
|
||||
}
|
||||
X509Certificate cert = (X509Certificate) chain[i];
|
||||
line(log, "Сертификат " + (i + 1) + " из " + chain.length);
|
||||
line(log, " Subject: " + cert.getSubjectX500Principal().getName());
|
||||
line(log, " Issuer: " + cert.getIssuerX500Principal().getName());
|
||||
line(log, " Valid from: " + cert.getNotBefore().toInstant());
|
||||
line(log, " Valid until: " + cert.getNotAfter().toInstant());
|
||||
line(log, " SHA-256: " + fingerprint(cert));
|
||||
if (i == 0) {
|
||||
line(log, " SAN: " + cert.getSubjectAlternativeNames());
|
||||
}
|
||||
}
|
||||
} catch (GeneralSecurityException | SSLException | IllegalStateException error) {
|
||||
line(log, "TLS metadata: " + error.getClass().getSimpleName());
|
||||
}
|
||||
}
|
||||
|
||||
private static String fingerprint(X509Certificate cert) throws GeneralSecurityException {
|
||||
byte[] hash = MessageDigest.getInstance("SHA-256").digest(cert.getEncoded());
|
||||
StringBuilder output = new StringBuilder(hash.length * 3 - 1);
|
||||
for (byte item : hash) {
|
||||
if (output.length() > 0) {
|
||||
output.append(':');
|
||||
}
|
||||
output.append(String.format(Locale.ROOT, "%02X", item & 0xff));
|
||||
}
|
||||
return output.toString();
|
||||
}
|
||||
|
||||
private static String describeHttpError(StringBuilder log, HttpsURLConnection connection,
|
||||
int status) {
|
||||
if (status >= 300 && status < 400) {
|
||||
return "HTTP " + status + ". Проверьте исходный адрес. Редиректы отключены.";
|
||||
}
|
||||
String code = "";
|
||||
try {
|
||||
code = new JSONObject(readBody(connection.getErrorStream())).optString("error");
|
||||
} catch (IOException | JSONException ignored) {
|
||||
// Reverse proxies also return HTML and plain text.
|
||||
}
|
||||
switch (code) {
|
||||
case "invalid_grant":
|
||||
line(log, "OAuth: invalid_grant");
|
||||
return "HTTP " + status + ". Keycloak отклонил учётные данные или вход пользователя.";
|
||||
case "invalid_client":
|
||||
line(log, "OAuth: invalid_client");
|
||||
return "HTTP " + status + ". Проверьте Client ID и Client Secret.";
|
||||
case "unauthorized_client":
|
||||
line(log, "OAuth: unauthorized_client");
|
||||
return "HTTP " + status + ". Проверьте Direct Access Grants у клиента.";
|
||||
case "invalid_request":
|
||||
case "unsupported_grant_type":
|
||||
case "invalid_scope":
|
||||
case "access_denied":
|
||||
line(log, "OAuth: " + code);
|
||||
return "HTTP " + status + ". " + code;
|
||||
default:
|
||||
return status == HttpURLConnection.HTTP_NOT_FOUND
|
||||
? "HTTP 404. Проверьте базовый URL и Realm."
|
||||
: "Сервер вернул HTTP " + status + ".";
|
||||
}
|
||||
}
|
||||
|
||||
private static String describeFailure(StringBuilder log, IOException failure) {
|
||||
boolean tlsFailure = false;
|
||||
Throwable cause = failure;
|
||||
for (int i = 0; i < 12 && cause != null; i++, cause = cause.getCause()) {
|
||||
String detail = cause.getClass().getSimpleName();
|
||||
if (cause instanceof SSLException || cause instanceof GeneralSecurityException) {
|
||||
tlsFailure = true;
|
||||
if (cause.getMessage() != null) {
|
||||
detail += ": " + cause.getMessage();
|
||||
}
|
||||
}
|
||||
line(log, (i == 0 ? "Ошибка: " : "Причина: ") + detail);
|
||||
}
|
||||
return tlsFailure ? "Ошибка TLS. Подробности в журнале."
|
||||
: "Запрос не выполнен. Подробности в журнале.";
|
||||
}
|
||||
|
||||
private static String readBody(InputStream source) throws IOException {
|
||||
if (source == null) {
|
||||
return "";
|
||||
}
|
||||
try (InputStream input = source; ByteArrayOutputStream body = new ByteArrayOutputStream()) {
|
||||
byte[] buffer = new byte[8192];
|
||||
int count;
|
||||
while ((count = input.read(buffer)) != -1) {
|
||||
if (body.size() + count > MAX_BODY_BYTES) {
|
||||
throw new BodyLimitException();
|
||||
}
|
||||
body.write(buffer, 0, count);
|
||||
}
|
||||
return new String(body.toByteArray(), StandardCharsets.UTF_8);
|
||||
}
|
||||
}
|
||||
|
||||
private static void line(StringBuilder log, String text) {
|
||||
log.append(text).append('\n');
|
||||
}
|
||||
|
||||
private static final class BodyLimitException extends IOException {
|
||||
private static final long serialVersionUID = 1L;
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,333 @@
|
||||
package net.m9k.keycloakprobe;
|
||||
|
||||
import android.app.Activity;
|
||||
import android.content.ClipData;
|
||||
import android.content.ClipboardManager;
|
||||
import android.content.Intent;
|
||||
import android.content.res.ColorStateList;
|
||||
import android.graphics.Color;
|
||||
import android.graphics.Insets;
|
||||
import android.graphics.Typeface;
|
||||
import android.graphics.drawable.GradientDrawable;
|
||||
import android.net.Uri;
|
||||
import android.os.Bundle;
|
||||
import android.os.PersistableBundle;
|
||||
import android.text.InputType;
|
||||
import android.view.View;
|
||||
import android.view.WindowInsets;
|
||||
import android.view.inputmethod.InputMethodManager;
|
||||
import android.widget.Button;
|
||||
import android.widget.EditText;
|
||||
import android.widget.LinearLayout;
|
||||
import android.widget.ScrollView;
|
||||
import android.widget.TextView;
|
||||
import android.widget.Toast;
|
||||
|
||||
import java.io.IOException;
|
||||
import java.io.OutputStream;
|
||||
import java.nio.charset.StandardCharsets;
|
||||
import java.time.LocalDateTime;
|
||||
import java.time.format.DateTimeFormatter;
|
||||
import java.util.Locale;
|
||||
import java.util.concurrent.ExecutorService;
|
||||
import java.util.concurrent.Executors;
|
||||
|
||||
public final class MainActivity extends Activity {
|
||||
private static final int SAVE_LOG = 101;
|
||||
private static final int PAGE = Color.rgb(240, 244, 250);
|
||||
private static final int INK = Color.rgb(22, 37, 61);
|
||||
private static final int MUTED = Color.rgb(72, 92, 119);
|
||||
private static final int ACCENT = Color.rgb(33, 93, 168);
|
||||
private static final int TEXT = InputType.TYPE_CLASS_TEXT | InputType.TYPE_TEXT_FLAG_NO_SUGGESTIONS;
|
||||
private static final int SECRET = InputType.TYPE_CLASS_TEXT | InputType.TYPE_TEXT_VARIATION_PASSWORD;
|
||||
|
||||
private final ExecutorService worker = Executors.newSingleThreadExecutor();
|
||||
private EditText baseUrl;
|
||||
private EditText realm;
|
||||
private EditText clientId;
|
||||
private EditText clientSecret;
|
||||
private EditText username;
|
||||
private EditText password;
|
||||
private Button fetchButton;
|
||||
private Button copyButton;
|
||||
private Button saveButton;
|
||||
private TextView status;
|
||||
private TextView token;
|
||||
private TextView log;
|
||||
private ScrollView scroll;
|
||||
private KeycloakClient.Result result;
|
||||
private String pendingLog;
|
||||
|
||||
@Override protected void onCreate(Bundle state) {
|
||||
super.onCreate(state);
|
||||
getWindow().setDecorFitsSystemWindows(false);
|
||||
buildScreen();
|
||||
}
|
||||
|
||||
private void buildScreen() {
|
||||
scroll = new ScrollView(this);
|
||||
scroll.setFillViewport(true);
|
||||
scroll.setBackgroundColor(PAGE);
|
||||
scroll.setImportantForAutofill(View.IMPORTANT_FOR_AUTOFILL_NO_EXCLUDE_DESCENDANTS);
|
||||
scroll.setSaveFromParentEnabled(false);
|
||||
scroll.setOnApplyWindowInsetsListener((view, insets) -> {
|
||||
Insets bars = insets.getInsets(WindowInsets.Type.systemBars()
|
||||
| WindowInsets.Type.displayCutout() | WindowInsets.Type.ime());
|
||||
view.setPadding(bars.left, bars.top, bars.right, bars.bottom);
|
||||
return insets;
|
||||
});
|
||||
|
||||
LinearLayout page = column();
|
||||
page.setPadding(dp(16), dp(18), dp(16), dp(20));
|
||||
page.setFocusableInTouchMode(true);
|
||||
scroll.addView(page);
|
||||
|
||||
heading(page, getString(R.string.app_name), 29);
|
||||
page.addView(label("Тестовый запрос токена и диагностика TLS", 14, MUTED));
|
||||
|
||||
LinearLayout connection = card(page);
|
||||
heading(connection, "Подключение", 18);
|
||||
baseUrl = field(connection, "HTTPS-адрес Keycloak", "https://my.domain:449/auth",
|
||||
InputType.TYPE_CLASS_TEXT | InputType.TYPE_TEXT_VARIATION_URI);
|
||||
realm = field(connection, "Realm", "master", TEXT);
|
||||
|
||||
LinearLayout credentials = card(page);
|
||||
heading(credentials, "Клиент и пользователь", 18);
|
||||
clientId = field(credentials, "Client ID", "android-test", TEXT);
|
||||
clientSecret = field(credentials, "Client Secret", "Опционально для public client", SECRET);
|
||||
username = field(credentials, "Логин", "", TEXT);
|
||||
password = field(credentials, "Пароль", "", SECRET);
|
||||
|
||||
fetchButton = button("Получить токен", true);
|
||||
page.addView(fetchButton, spaced(12));
|
||||
fetchButton.setOnClickListener(view -> fetch());
|
||||
status = label("", 15, INK);
|
||||
status.setAccessibilityLiveRegion(View.ACCESSIBILITY_LIVE_REGION_POLITE);
|
||||
status.setVisibility(View.GONE);
|
||||
page.addView(status, spaced(8));
|
||||
|
||||
LinearLayout resultCard = card(page);
|
||||
heading(resultCard, "Access token", 18);
|
||||
token = output("Токен появится после успешного входа.", 6);
|
||||
resultCard.addView(token, spaced(8));
|
||||
copyButton = button("Копировать токен", false);
|
||||
resultCard.addView(copyButton, spaced(4));
|
||||
copyButton.setEnabled(false);
|
||||
copyButton.setOnClickListener(view -> copyToken());
|
||||
|
||||
LinearLayout diagnostics = card(page);
|
||||
heading(diagnostics, "Журнал HTTPS / TLS", 18);
|
||||
log = output("Журнал появится после запроса.", 14);
|
||||
diagnostics.addView(log, spaced(8));
|
||||
saveButton = button("Сохранить журнал", false);
|
||||
diagnostics.addView(saveButton, spaced(4));
|
||||
saveButton.setEnabled(false);
|
||||
saveButton.setOnClickListener(view -> chooseLogFile());
|
||||
|
||||
setContentView(scroll);
|
||||
page.requestFocus();
|
||||
}
|
||||
|
||||
private void fetch() {
|
||||
TokenRequest request;
|
||||
try {
|
||||
request = new TokenRequest(value(baseUrl).trim(), value(realm).trim(),
|
||||
value(clientId).trim(), value(clientSecret), value(username), value(password));
|
||||
} catch (IllegalArgumentException error) {
|
||||
showStatus(error.getMessage());
|
||||
return;
|
||||
}
|
||||
|
||||
getSystemService(InputMethodManager.class)
|
||||
.hideSoftInputFromWindow(fetchButton.getWindowToken(), 0);
|
||||
result = null;
|
||||
token.setText("Запрос выполняется.");
|
||||
log.setText("Запрос выполняется.");
|
||||
fetchButton.setEnabled(false);
|
||||
copyButton.setEnabled(false);
|
||||
saveButton.setEnabled(false);
|
||||
showStatus("Подключение к Keycloak…");
|
||||
|
||||
worker.execute(() -> {
|
||||
KeycloakClient.Result response = new KeycloakClient().fetch(request);
|
||||
runOnUiThread(() -> {
|
||||
if (isDestroyed()) {
|
||||
return;
|
||||
}
|
||||
result = response;
|
||||
showStatus(response.summary);
|
||||
token.setText(response.token == null ? "Токен не получен." : response.token);
|
||||
log.setText(response.log.trim());
|
||||
fetchButton.setEnabled(true);
|
||||
copyButton.setEnabled(response.token != null);
|
||||
saveButton.setEnabled(true);
|
||||
scroll.post(() -> scroll.smoothScrollTo(0, fetchButton.getTop()));
|
||||
});
|
||||
});
|
||||
}
|
||||
|
||||
private void copyToken() {
|
||||
if (result == null || result.token == null) {
|
||||
return;
|
||||
}
|
||||
ClipData data = ClipData.newPlainText("Keycloak access_token", result.token);
|
||||
PersistableBundle flags = new PersistableBundle();
|
||||
flags.putBoolean("android.content.extra.IS_SENSITIVE", true);
|
||||
data.getDescription().setExtras(flags);
|
||||
getSystemService(ClipboardManager.class).setPrimaryClip(data);
|
||||
if (android.os.Build.VERSION.SDK_INT < 33) {
|
||||
Toast.makeText(this, "Токен скопирован", Toast.LENGTH_SHORT).show();
|
||||
}
|
||||
}
|
||||
|
||||
private void chooseLogFile() {
|
||||
if (result == null) {
|
||||
return;
|
||||
}
|
||||
pendingLog = result.log;
|
||||
String stamp = LocalDateTime.now()
|
||||
.format(DateTimeFormatter.ofPattern("yyyyMMdd-HHmmss", Locale.ROOT));
|
||||
Intent intent = new Intent(Intent.ACTION_CREATE_DOCUMENT)
|
||||
.addCategory(Intent.CATEGORY_OPENABLE)
|
||||
.setType("text/plain")
|
||||
.putExtra(Intent.EXTRA_TITLE, "keycloak-tls-" + stamp + ".txt");
|
||||
startActivityForResult(intent, SAVE_LOG);
|
||||
}
|
||||
|
||||
@Override protected void onActivityResult(int requestCode, int resultCode, Intent data) {
|
||||
super.onActivityResult(requestCode, resultCode, data);
|
||||
if (requestCode != SAVE_LOG) {
|
||||
return;
|
||||
}
|
||||
String snapshot = pendingLog;
|
||||
pendingLog = null;
|
||||
if (resultCode == RESULT_OK && data != null && data.getData() != null) {
|
||||
if (snapshot == null) {
|
||||
showStatus("Журнал утрачен. Выполните запрос ещё раз.");
|
||||
return;
|
||||
}
|
||||
Uri destination = data.getData();
|
||||
worker.execute(() -> writeLog(destination, snapshot));
|
||||
}
|
||||
}
|
||||
|
||||
private void writeLog(Uri destination, String snapshot) {
|
||||
String message = "Журнал сохранён.";
|
||||
try (OutputStream out = getContentResolver().openOutputStream(destination, "wt")) {
|
||||
if (out == null) {
|
||||
throw new IOException("Document unavailable");
|
||||
}
|
||||
out.write(snapshot.getBytes(StandardCharsets.UTF_8));
|
||||
} catch (IOException | SecurityException error) {
|
||||
message = "Не удалось сохранить журнал.";
|
||||
}
|
||||
String notification = message;
|
||||
runOnUiThread(() -> {
|
||||
if (!isDestroyed()) {
|
||||
Toast.makeText(this, notification, Toast.LENGTH_LONG).show();
|
||||
}
|
||||
});
|
||||
}
|
||||
|
||||
@Override protected void onDestroy() {
|
||||
worker.shutdownNow();
|
||||
super.onDestroy();
|
||||
}
|
||||
|
||||
private void showStatus(String message) {
|
||||
status.setText(message);
|
||||
status.setVisibility(View.VISIBLE);
|
||||
}
|
||||
|
||||
private LinearLayout column() {
|
||||
LinearLayout layout = new LinearLayout(this);
|
||||
layout.setOrientation(LinearLayout.VERTICAL);
|
||||
return layout;
|
||||
}
|
||||
|
||||
private LinearLayout card(LinearLayout parent) {
|
||||
LinearLayout layout = column();
|
||||
layout.setPadding(dp(14), dp(12), dp(14), dp(12));
|
||||
layout.setBackground(surface(Color.WHITE, 14));
|
||||
parent.addView(layout, spaced(12));
|
||||
return layout;
|
||||
}
|
||||
|
||||
private void heading(LinearLayout parent, String text, int size) {
|
||||
TextView view = label(text, size, INK);
|
||||
view.setTypeface(Typeface.DEFAULT, Typeface.BOLD);
|
||||
view.setAccessibilityHeading(true);
|
||||
parent.addView(view);
|
||||
}
|
||||
|
||||
private EditText field(LinearLayout parent, String title, String hint, int inputType) {
|
||||
EditText edit = new EditText(this);
|
||||
edit.setId(View.generateViewId());
|
||||
edit.setSaveEnabled(false);
|
||||
edit.setTextColor(INK);
|
||||
edit.setHintTextColor(MUTED);
|
||||
edit.setTextSize(16);
|
||||
edit.setSingleLine(true);
|
||||
edit.setInputType(inputType);
|
||||
edit.setImeOptions(android.view.inputmethod.EditorInfo.IME_FLAG_NO_PERSONALIZED_LEARNING);
|
||||
edit.setHint(hint);
|
||||
|
||||
TextView fieldLabel = label(title, 13, MUTED);
|
||||
fieldLabel.setLabelFor(edit.getId());
|
||||
parent.addView(fieldLabel, spaced(8));
|
||||
parent.addView(edit);
|
||||
return edit;
|
||||
}
|
||||
|
||||
private TextView label(String text, int textSize, int color) {
|
||||
TextView view = new TextView(this);
|
||||
view.setText(text);
|
||||
view.setTextSize(textSize);
|
||||
view.setTextColor(color);
|
||||
return view;
|
||||
}
|
||||
|
||||
private TextView output(String placeholder, int minimumLines) {
|
||||
TextView view = label(placeholder, 13, INK);
|
||||
view.setTypeface(Typeface.MONOSPACE);
|
||||
view.setTextIsSelectable(true);
|
||||
view.setMinLines(minimumLines);
|
||||
view.setPadding(dp(10), dp(10), dp(10), dp(10));
|
||||
view.setBackground(surface(PAGE, 8));
|
||||
return view;
|
||||
}
|
||||
|
||||
private Button button(String title, boolean primary) {
|
||||
Button button = new Button(this);
|
||||
button.setAllCaps(false);
|
||||
button.setText(title);
|
||||
if (primary) {
|
||||
int[][] states = {{-android.R.attr.state_enabled}, {}};
|
||||
button.setTextColor(Color.WHITE);
|
||||
button.setBackgroundTintList(new ColorStateList(states, new int[] {MUTED, ACCENT}));
|
||||
}
|
||||
return button;
|
||||
}
|
||||
|
||||
private GradientDrawable surface(int color, int radius) {
|
||||
GradientDrawable shape = new GradientDrawable();
|
||||
shape.setCornerRadius(dp(radius));
|
||||
shape.setColor(color);
|
||||
return shape;
|
||||
}
|
||||
|
||||
private LinearLayout.LayoutParams spaced(int top) {
|
||||
LinearLayout.LayoutParams params = new LinearLayout.LayoutParams(
|
||||
LinearLayout.LayoutParams.MATCH_PARENT, LinearLayout.LayoutParams.WRAP_CONTENT);
|
||||
params.topMargin = dp(top);
|
||||
return params;
|
||||
}
|
||||
|
||||
private int dp(int value) {
|
||||
return Math.round(value * getResources().getDisplayMetrics().density);
|
||||
}
|
||||
|
||||
private static String value(EditText edit) {
|
||||
return edit.getText().toString();
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,64 @@
|
||||
package net.m9k.keycloakprobe;
|
||||
|
||||
import java.io.IOException;
|
||||
import java.net.InetAddress;
|
||||
import java.net.Socket;
|
||||
import javax.net.ssl.SSLSession;
|
||||
import javax.net.ssl.SSLSocket;
|
||||
import javax.net.ssl.SSLSocketFactory;
|
||||
|
||||
final class TlsSockets extends SSLSocketFactory {
|
||||
private final SSLSocketFactory platform;
|
||||
private volatile SSLSocket socket;
|
||||
|
||||
TlsSockets(SSLSocketFactory platform) {
|
||||
this.platform = platform;
|
||||
}
|
||||
|
||||
SSLSession session() {
|
||||
SSLSocket current = socket;
|
||||
return current == null ? null : current.getSession();
|
||||
}
|
||||
|
||||
private Socket record(Socket created) {
|
||||
if (created instanceof SSLSocket) {
|
||||
socket = (SSLSocket) created;
|
||||
}
|
||||
return created;
|
||||
}
|
||||
|
||||
@Override public String[] getDefaultCipherSuites() {
|
||||
return platform.getDefaultCipherSuites();
|
||||
}
|
||||
|
||||
@Override public String[] getSupportedCipherSuites() {
|
||||
return platform.getSupportedCipherSuites();
|
||||
}
|
||||
|
||||
@Override public Socket createSocket() throws IOException {
|
||||
return record(platform.createSocket());
|
||||
}
|
||||
|
||||
@Override public Socket createSocket(Socket socket, String host, int port, boolean autoClose)
|
||||
throws IOException {
|
||||
return record(platform.createSocket(socket, host, port, autoClose));
|
||||
}
|
||||
|
||||
@Override public Socket createSocket(String host, int port) throws IOException {
|
||||
return record(platform.createSocket(host, port));
|
||||
}
|
||||
|
||||
@Override public Socket createSocket(String host, int port, InetAddress local, int localPort)
|
||||
throws IOException {
|
||||
return record(platform.createSocket(host, port, local, localPort));
|
||||
}
|
||||
|
||||
@Override public Socket createSocket(InetAddress host, int port) throws IOException {
|
||||
return record(platform.createSocket(host, port));
|
||||
}
|
||||
|
||||
@Override public Socket createSocket(InetAddress host, int port, InetAddress local, int localPort)
|
||||
throws IOException {
|
||||
return record(platform.createSocket(host, port, local, localPort));
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,75 @@
|
||||
package net.m9k.keycloakprobe;
|
||||
|
||||
import java.io.UnsupportedEncodingException;
|
||||
import java.net.MalformedURLException;
|
||||
import java.net.URI;
|
||||
import java.net.URISyntaxException;
|
||||
import java.net.URL;
|
||||
import java.net.URLEncoder;
|
||||
import java.nio.charset.StandardCharsets;
|
||||
|
||||
final class TokenRequest {
|
||||
final URL endpoint;
|
||||
private final String clientId;
|
||||
private final String clientSecret;
|
||||
private final String username;
|
||||
private final String password;
|
||||
|
||||
TokenRequest(String baseUrl, String realm, String clientId, String clientSecret,
|
||||
String username, String password) {
|
||||
if (clientId.isEmpty() || username.isEmpty() || password.isEmpty()) {
|
||||
throw new IllegalArgumentException("Заполните Client ID, логин и пароль.");
|
||||
}
|
||||
endpoint = endpoint(baseUrl.trim(), realm.trim());
|
||||
this.clientId = clientId;
|
||||
this.clientSecret = clientSecret;
|
||||
this.username = username;
|
||||
this.password = password;
|
||||
}
|
||||
|
||||
private static URL endpoint(String baseUrl, String realm) {
|
||||
if (baseUrl.isEmpty() || realm.isEmpty()) {
|
||||
throw new IllegalArgumentException("Укажите адрес Keycloak и Realm.");
|
||||
}
|
||||
if (realm.equals(".") || realm.equals("..") || realm.indexOf('/') >= 0
|
||||
|| realm.indexOf('\\') >= 0) {
|
||||
throw new IllegalArgumentException("Введите имя Realm без разделителей пути.");
|
||||
}
|
||||
String address = baseUrl.contains("://") ? baseUrl : "https://" + baseUrl;
|
||||
try {
|
||||
URI uri = new URI(address);
|
||||
if (!"https".equalsIgnoreCase(uri.getScheme()) || uri.getHost() == null
|
||||
|| uri.getRawUserInfo() != null || uri.getRawQuery() != null
|
||||
|| uri.getRawFragment() != null || uri.getRawAuthority().endsWith(":")
|
||||
|| uri.getPort() == 0 || uri.getPort() > 65535) {
|
||||
throw new IllegalArgumentException(
|
||||
"Укажите HTTPS-адрес без логина, запроса и фрагмента.");
|
||||
}
|
||||
String prefix = uri.normalize().getRawPath().replaceFirst("/+$", "");
|
||||
return new URI("https://" + uri.getRawAuthority() + prefix + "/realms/"
|
||||
+ encode(realm).replace("+", "%20")
|
||||
+ "/protocol/openid-connect/token").toURL();
|
||||
} catch (URISyntaxException | MalformedURLException error) {
|
||||
throw new IllegalArgumentException("Проверьте HTTPS-адрес и порт.");
|
||||
}
|
||||
}
|
||||
|
||||
byte[] form() {
|
||||
String fields = "grant_type=password"
|
||||
+ "&client_id=" + encode(clientId)
|
||||
+ "&username=" + encode(username)
|
||||
+ "&password=" + encode(password);
|
||||
if (!clientSecret.isEmpty()) {
|
||||
fields += "&client_secret=" + encode(clientSecret);
|
||||
}
|
||||
return fields.getBytes(StandardCharsets.UTF_8);
|
||||
}
|
||||
|
||||
private static String encode(String value) {
|
||||
try {
|
||||
return URLEncoder.encode(value, StandardCharsets.UTF_8.name());
|
||||
} catch (UnsupportedEncodingException error) {
|
||||
throw new AssertionError(error);
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,12 @@
|
||||
<?xml version="1.0" encoding="utf-8"?>
|
||||
<resources>
|
||||
<string name="app_name">Keycloak Probe</string>
|
||||
<style name="AppTheme" parent="android:style/Theme.Material.Light.NoActionBar">
|
||||
<item name="android:fontFamily">sans</item>
|
||||
<item name="android:colorAccent">#215DA8</item>
|
||||
<item name="android:windowActionModeOverlay">true</item>
|
||||
<item name="android:windowLightStatusBar">true</item>
|
||||
<item name="android:windowLightNavigationBar">true</item>
|
||||
<item name="android:windowBackground">#F0F4FA</item>
|
||||
</style>
|
||||
</resources>
|
||||
@@ -0,0 +1,9 @@
|
||||
<?xml version="1.0" encoding="utf-8"?>
|
||||
<network-security-config>
|
||||
<base-config cleartextTrafficPermitted="false">
|
||||
<trust-anchors>
|
||||
<certificates src="system" />
|
||||
<certificates src="user" />
|
||||
</trust-anchors>
|
||||
</base-config>
|
||||
</network-security-config>
|
||||
@@ -0,0 +1,18 @@
|
||||
pluginManagement {
|
||||
repositories {
|
||||
google()
|
||||
mavenCentral()
|
||||
gradlePluginPortal()
|
||||
}
|
||||
}
|
||||
|
||||
dependencyResolutionManagement {
|
||||
repositoriesMode.set(RepositoriesMode.FAIL_ON_PROJECT_REPOS)
|
||||
repositories {
|
||||
google()
|
||||
mavenCentral()
|
||||
}
|
||||
}
|
||||
|
||||
rootProject.name = 'KeycloakProbe'
|
||||
include ':app'
|
||||
Reference in new issue
Block a user