mirror of
https://github.com/foss42/apidash.git
synced 2025-12-09 06:32:45 +08:00
feat: enhance JWT support with private key handling and additional algorithms
This commit is contained in:
@@ -7,6 +7,7 @@ part 'auth_jwt_model.g.dart';
|
||||
class AuthJwtModel with _$AuthJwtModel {
|
||||
const factory AuthJwtModel({
|
||||
required String secret,
|
||||
String? privateKey,
|
||||
required String payload,
|
||||
required String addTokenTo,
|
||||
required String algorithm,
|
||||
|
||||
@@ -22,6 +22,7 @@ AuthJwtModel _$AuthJwtModelFromJson(Map<String, dynamic> json) {
|
||||
/// @nodoc
|
||||
mixin _$AuthJwtModel {
|
||||
String get secret => throw _privateConstructorUsedError;
|
||||
String? get privateKey => throw _privateConstructorUsedError;
|
||||
String get payload => throw _privateConstructorUsedError;
|
||||
String get addTokenTo => throw _privateConstructorUsedError;
|
||||
String get algorithm => throw _privateConstructorUsedError;
|
||||
@@ -49,6 +50,7 @@ abstract class $AuthJwtModelCopyWith<$Res> {
|
||||
@useResult
|
||||
$Res call({
|
||||
String secret,
|
||||
String? privateKey,
|
||||
String payload,
|
||||
String addTokenTo,
|
||||
String algorithm,
|
||||
@@ -75,6 +77,7 @@ class _$AuthJwtModelCopyWithImpl<$Res, $Val extends AuthJwtModel>
|
||||
@override
|
||||
$Res call({
|
||||
Object? secret = null,
|
||||
Object? privateKey = freezed,
|
||||
Object? payload = null,
|
||||
Object? addTokenTo = null,
|
||||
Object? algorithm = null,
|
||||
@@ -89,6 +92,10 @@ class _$AuthJwtModelCopyWithImpl<$Res, $Val extends AuthJwtModel>
|
||||
? _value.secret
|
||||
: secret // ignore: cast_nullable_to_non_nullable
|
||||
as String,
|
||||
privateKey: freezed == privateKey
|
||||
? _value.privateKey
|
||||
: privateKey // ignore: cast_nullable_to_non_nullable
|
||||
as String?,
|
||||
payload: null == payload
|
||||
? _value.payload
|
||||
: payload // ignore: cast_nullable_to_non_nullable
|
||||
@@ -134,6 +141,7 @@ abstract class _$$AuthJwtModelImplCopyWith<$Res>
|
||||
@useResult
|
||||
$Res call({
|
||||
String secret,
|
||||
String? privateKey,
|
||||
String payload,
|
||||
String addTokenTo,
|
||||
String algorithm,
|
||||
@@ -159,6 +167,7 @@ class __$$AuthJwtModelImplCopyWithImpl<$Res>
|
||||
@override
|
||||
$Res call({
|
||||
Object? secret = null,
|
||||
Object? privateKey = freezed,
|
||||
Object? payload = null,
|
||||
Object? addTokenTo = null,
|
||||
Object? algorithm = null,
|
||||
@@ -173,6 +182,10 @@ class __$$AuthJwtModelImplCopyWithImpl<$Res>
|
||||
? _value.secret
|
||||
: secret // ignore: cast_nullable_to_non_nullable
|
||||
as String,
|
||||
privateKey: freezed == privateKey
|
||||
? _value.privateKey
|
||||
: privateKey // ignore: cast_nullable_to_non_nullable
|
||||
as String?,
|
||||
payload: null == payload
|
||||
? _value.payload
|
||||
: payload // ignore: cast_nullable_to_non_nullable
|
||||
@@ -211,6 +224,7 @@ class __$$AuthJwtModelImplCopyWithImpl<$Res>
|
||||
class _$AuthJwtModelImpl implements _AuthJwtModel {
|
||||
const _$AuthJwtModelImpl({
|
||||
required this.secret,
|
||||
this.privateKey,
|
||||
required this.payload,
|
||||
required this.addTokenTo,
|
||||
required this.algorithm,
|
||||
@@ -226,6 +240,8 @@ class _$AuthJwtModelImpl implements _AuthJwtModel {
|
||||
@override
|
||||
final String secret;
|
||||
@override
|
||||
final String? privateKey;
|
||||
@override
|
||||
final String payload;
|
||||
@override
|
||||
final String addTokenTo;
|
||||
@@ -242,7 +258,7 @@ class _$AuthJwtModelImpl implements _AuthJwtModel {
|
||||
|
||||
@override
|
||||
String toString() {
|
||||
return 'AuthJwtModel(secret: $secret, payload: $payload, addTokenTo: $addTokenTo, algorithm: $algorithm, isSecretBase64Encoded: $isSecretBase64Encoded, headerPrefix: $headerPrefix, queryParamKey: $queryParamKey, header: $header)';
|
||||
return 'AuthJwtModel(secret: $secret, privateKey: $privateKey, payload: $payload, addTokenTo: $addTokenTo, algorithm: $algorithm, isSecretBase64Encoded: $isSecretBase64Encoded, headerPrefix: $headerPrefix, queryParamKey: $queryParamKey, header: $header)';
|
||||
}
|
||||
|
||||
@override
|
||||
@@ -251,6 +267,8 @@ class _$AuthJwtModelImpl implements _AuthJwtModel {
|
||||
(other.runtimeType == runtimeType &&
|
||||
other is _$AuthJwtModelImpl &&
|
||||
(identical(other.secret, secret) || other.secret == secret) &&
|
||||
(identical(other.privateKey, privateKey) ||
|
||||
other.privateKey == privateKey) &&
|
||||
(identical(other.payload, payload) || other.payload == payload) &&
|
||||
(identical(other.addTokenTo, addTokenTo) ||
|
||||
other.addTokenTo == addTokenTo) &&
|
||||
@@ -270,6 +288,7 @@ class _$AuthJwtModelImpl implements _AuthJwtModel {
|
||||
int get hashCode => Object.hash(
|
||||
runtimeType,
|
||||
secret,
|
||||
privateKey,
|
||||
payload,
|
||||
addTokenTo,
|
||||
algorithm,
|
||||
@@ -296,6 +315,7 @@ class _$AuthJwtModelImpl implements _AuthJwtModel {
|
||||
abstract class _AuthJwtModel implements AuthJwtModel {
|
||||
const factory _AuthJwtModel({
|
||||
required final String secret,
|
||||
final String? privateKey,
|
||||
required final String payload,
|
||||
required final String addTokenTo,
|
||||
required final String algorithm,
|
||||
@@ -311,6 +331,8 @@ abstract class _AuthJwtModel implements AuthJwtModel {
|
||||
@override
|
||||
String get secret;
|
||||
@override
|
||||
String? get privateKey;
|
||||
@override
|
||||
String get payload;
|
||||
@override
|
||||
String get addTokenTo;
|
||||
|
||||
@@ -9,6 +9,7 @@ part of 'auth_jwt_model.dart';
|
||||
_$AuthJwtModelImpl _$$AuthJwtModelImplFromJson(Map<String, dynamic> json) =>
|
||||
_$AuthJwtModelImpl(
|
||||
secret: json['secret'] as String,
|
||||
privateKey: json['privateKey'] as String?,
|
||||
payload: json['payload'] as String,
|
||||
addTokenTo: json['addTokenTo'] as String,
|
||||
algorithm: json['algorithm'] as String,
|
||||
@@ -21,6 +22,7 @@ _$AuthJwtModelImpl _$$AuthJwtModelImplFromJson(Map<String, dynamic> json) =>
|
||||
Map<String, dynamic> _$$AuthJwtModelImplToJson(_$AuthJwtModelImpl instance) =>
|
||||
<String, dynamic>{
|
||||
'secret': instance.secret,
|
||||
'privateKey': instance.privateKey,
|
||||
'payload': instance.payload,
|
||||
'addTokenTo': instance.addTokenTo,
|
||||
'algorithm': instance.algorithm,
|
||||
|
||||
@@ -1,94 +1,95 @@
|
||||
import 'dart:convert';
|
||||
import 'dart:typed_data';
|
||||
import 'dart:developer';
|
||||
import 'package:better_networking/models/auth/auth_jwt_model.dart';
|
||||
import 'package:crypto/crypto.dart';
|
||||
import 'package:dart_jsonwebtoken/dart_jsonwebtoken.dart';
|
||||
|
||||
String generateJWT(AuthJwtModel jwtAuth) {
|
||||
try {
|
||||
Map<String, dynamic> header;
|
||||
// Parse header if provided
|
||||
Map<String, dynamic> headerMap = {};
|
||||
if (jwtAuth.header.isNotEmpty) {
|
||||
try {
|
||||
header = json.decode(jwtAuth.header) as Map<String, dynamic>;
|
||||
headerMap = json.decode(jwtAuth.header) as Map<String, dynamic>;
|
||||
} catch (e) {
|
||||
header = {};
|
||||
// If header parsing fails, use empty header
|
||||
headerMap = {};
|
||||
}
|
||||
} else {
|
||||
header = {};
|
||||
}
|
||||
header['typ'] = header['typ'] ?? 'JWT';
|
||||
header['alg'] = jwtAuth.algorithm;
|
||||
Map<String, dynamic> payload;
|
||||
|
||||
// Parse payload if provided
|
||||
Map<String, dynamic> payloadMap = {};
|
||||
if (jwtAuth.payload.isNotEmpty) {
|
||||
try {
|
||||
payload = json.decode(jwtAuth.payload) as Map<String, dynamic>;
|
||||
payloadMap = json.decode(jwtAuth.payload) as Map<String, dynamic>;
|
||||
} catch (e) {
|
||||
payload = {};
|
||||
// If payload parsing fails, use empty payload
|
||||
payloadMap = {};
|
||||
}
|
||||
} else {
|
||||
payload = {};
|
||||
}
|
||||
if (!payload.containsKey('iat')) {
|
||||
payload['iat'] = DateTime.now().millisecondsSinceEpoch ~/ 1000;
|
||||
}
|
||||
|
||||
// Encode header and payload
|
||||
final encodedHeader = _base64UrlEncode(utf8.encode(json.encode(header)));
|
||||
final encodedPayload = _base64UrlEncode(utf8.encode(json.encode(payload)));
|
||||
// Add issued at time if not present
|
||||
if (!payloadMap.containsKey('iat')) {
|
||||
payloadMap['iat'] = DateTime.now().millisecondsSinceEpoch ~/ 1000;
|
||||
}
|
||||
final jwt = JWT(payloadMap, header: headerMap);
|
||||
|
||||
// Create signature
|
||||
final signature = _createSignature(
|
||||
'$encodedHeader.$encodedPayload',
|
||||
final key = _createKey(
|
||||
jwtAuth.secret,
|
||||
jwtAuth.algorithm,
|
||||
jwtAuth.isSecretBase64Encoded,
|
||||
jwtAuth.privateKey,
|
||||
);
|
||||
final token = jwt.sign(
|
||||
key,
|
||||
algorithm: JWTAlgorithm.fromName(jwtAuth.algorithm),
|
||||
);
|
||||
|
||||
return '$encodedHeader.$encodedPayload.$signature';
|
||||
return token;
|
||||
} catch (e) {
|
||||
throw Exception('Failed to generate JWT: $e');
|
||||
log(e.toString());
|
||||
throw Exception('Failed to generate JSON Wweb Token: $e');
|
||||
}
|
||||
}
|
||||
|
||||
String _createSignature(
|
||||
String data, String secret, String algorithm, bool isSecretBase64Encoded) {
|
||||
try {
|
||||
Uint8List secretBytes;
|
||||
JWTKey _createKey(
|
||||
String secret,
|
||||
String algorithm,
|
||||
bool isSecretBase64Encoded,
|
||||
String? privateKey,
|
||||
) {
|
||||
if (algorithm.startsWith('HS')) {
|
||||
if (isSecretBase64Encoded) {
|
||||
secretBytes = base64.decode(secret);
|
||||
final decodedSecret = base64.decode(secret);
|
||||
return SecretKey(String.fromCharCodes(decodedSecret));
|
||||
} else {
|
||||
secretBytes = utf8.encode(secret);
|
||||
return SecretKey(secret);
|
||||
}
|
||||
|
||||
final dataBytes = utf8.encode(data);
|
||||
|
||||
switch (algorithm) {
|
||||
case 'HS256':
|
||||
final hmac = Hmac(sha256, secretBytes);
|
||||
final digest = hmac.convert(dataBytes);
|
||||
return _base64UrlEncode(digest.bytes);
|
||||
|
||||
case 'HS384':
|
||||
final hmac = Hmac(sha384, secretBytes);
|
||||
final digest = hmac.convert(dataBytes);
|
||||
return _base64UrlEncode(digest.bytes);
|
||||
|
||||
case 'HS512':
|
||||
final hmac = Hmac(sha512, secretBytes);
|
||||
final digest = hmac.convert(dataBytes);
|
||||
return _base64UrlEncode(digest.bytes);
|
||||
|
||||
default:
|
||||
// Default to HS256
|
||||
final hmac = Hmac(sha256, secretBytes);
|
||||
final digest = hmac.convert(dataBytes);
|
||||
return _base64UrlEncode(digest.bytes);
|
||||
}
|
||||
} catch (e) {
|
||||
// Return placeholder signature if creation fails
|
||||
return _base64UrlEncode(utf8.encode('signature_generation_failed'));
|
||||
}
|
||||
}
|
||||
if (algorithm.startsWith('RS') || algorithm.startsWith('PS')) {
|
||||
if (privateKey == null) {
|
||||
throw Exception(
|
||||
'Failed to generate JSON Wweb Token: Private Key not Found',
|
||||
);
|
||||
}
|
||||
return RSAPrivateKey(privateKey);
|
||||
}
|
||||
if (algorithm.startsWith('ES')) {
|
||||
if (privateKey == null) {
|
||||
throw Exception(
|
||||
'Failed to generate JSON Wweb Token: Private Key not Found',
|
||||
);
|
||||
}
|
||||
return ECPrivateKey(privateKey);
|
||||
}
|
||||
|
||||
String _base64UrlEncode(List<int> bytes) {
|
||||
return base64Url.encode(bytes).replaceAll('=', '');
|
||||
if (algorithm == 'EdDSA') {
|
||||
if (privateKey == null) {
|
||||
throw Exception(
|
||||
'Failed to generate JSON Wweb Token: Private Key not Found',
|
||||
);
|
||||
}
|
||||
return EdDSAPrivateKey.fromPEM(privateKey);
|
||||
}
|
||||
|
||||
return SecretKey(secret, isBase64Encoded: isSecretBase64Encoded);
|
||||
}
|
||||
|
||||
Reference in New Issue
Block a user