gazelle_jwt 0.4.0
gazelle_jwt: ^0.4.0 copied to clipboard
Plugin for JSON Web Token (JWT) authentication in Gazelle, providing functionality to sign, verify, and handle JWT tokens during HTTP request processing.
example/gazelle_jwt_example.dart
import 'package:gazelle_core/gazelle_core.dart';
import 'package:gazelle_jwt/gazelle_jwt.dart';
import 'package:http/http.dart' as http;
void main() async {
// Initialize your Gazelle app.
final app = GazelleApp(
routes: [
GazelleRoute(
name: "login",
post: GazelleRouteHandler((context, request, response) async {
// Use the request to get data sent from the client.
return GazelleResponse(
statusCode: GazelleHttpStatusCode.success.ok_200,
// Sign a token and send it back to the client.
body: context.getPlugin<GazelleJwtPlugin>().sign({"test": "123"}),
);
}),
),
GazelleRoute(
name: "hello_world",
get: GazelleRouteHandler((context, request, response) async {
return GazelleResponse(
statusCode: GazelleHttpStatusCode.success.ok_200,
body: "Hello, World!",
);
}),
// Add the authentication hook provided by the plugin to guard your routes.
preRequestHooks: (context) => [
context.getPlugin<GazelleJwtPlugin>().authenticationHook,
],
),
],
plugins: [GazelleJwtPlugin(SecretKey("supersecret"))],
);
// Start your server.
await app.start();
// CLIENT SIDE
final baseUrl = app.serverAddress;
// Ask for a token.
final token =
await http.post(Uri.parse("$baseUrl/login")).then((e) => e.body);
// Authenticate your requests.
final result = await http.get(Uri.parse("$baseUrl/hello_world"), headers: {
"Authorization": "Bearer $token",
});
print(result.body); // Prints "Hello, World!"
await app.stop(force: true);
}