วิธีที่ 6: เชื่อมต่อผ่าน AI Coding Agents & Model Context Protocol (MCP)
ติดตั้ง Login512 MCP Server เข้ากับ Claude Desktop, Cursor, Windsurf, หรือ VS Code Cline เพื่อให้ AI ช่วยสแกนโปรเจกต์ วางแท็กสแกนใบหน้า และตรวจสอบความปลอดภัยให้โดยอัตโนมัติ
MCP Server Config (claude_desktop_config.json / .cursor/mcp.json)
ท่านสามารถติดตามปริมาณการสแกนชีวมิติทั่วโลกและขององค์กรตนเองผ่าน Dashboard หรือยิง API สาธารณะ GET https://login512.com/v1/stats/public เพื่อดูยอด Live Scans และ Developer Workspaces ได้ตลอดเวลา
import os
from fastapi import FastAPI, Depends, HTTPException, status
from login512_fastapi import Login512Bearer
app = FastAPI(title="Secure API with Login512")
# กำหนด Security Guard ด้วย Secret Key
auth_guard = Login512Bearer(secret_key=os.environ.get("LOGIN512_SECRET_KEY"))
# urls.py: login view (POST token -> Django session) and nonce view are included in the package
from django.urls import include, path
urlpatterns = [
path("login512/", include("login512_django.urls")),
]
# Frontend (any Login512 button), after onSuccess(token):
# const { nonce } = await (await fetch('/login512/nonce/')).json() // optional, pass it to the button
# await fetch('/login512/login/', { method: 'POST', body: JSON.stringify({ token }),
# headers: { 'Content-Type': 'application/json', 'X-CSRFToken': csrftoken } })
# -> 200 {"ok": true, "redirect": "..."} with a Django session, or 401 {"ok": false, "error": "TOKEN_ALREADY_USED"}
# In your own view: user = authenticate(request, login512_token=token)
3. ใช้งานใน Django REST Framework (DRF)
PYTHON
from rest_framework.authentication import SessionAuthentication
from rest_framework.permissions import IsAuthenticated
from rest_framework.response import Response
from rest_framework.views import APIView
class SecureProfileView(APIView):
# the session was created by POST /login512/login/
authentication_classes = [SessionAuthentication]
permission_classes = [IsAuthenticated]
def get(self, request):
return Response({'user_id': request.user.username, 'pqc': 'ML-DSA-65'})
namespace App\Http\Controllers;
use Illuminate\Http\Request;
use Login512\Laravel\Facades\Login512;
use App\Models\User;
use Illuminate\Support\Facades\Auth;
class AuthController extends Controller
{
public function verify(Request $request)
{
$token = $request->input('token');
$res = Login512::verifyToken($token);
// session_allowed, not valid: a valid token can still require a step-up
if (empty($res['session_allowed'])) {
return response()->json(['error' => $res['error'] ?? 'STEP_UP_REQUIRED'], 401);
}
// ค้นหาหรือสร้าง User จากรหัสชีวมิติ sub
$user = User::firstOrCreate(
['login512_id' => $res['claims']['sub']],
['name' => 'Biometric User', 'email' => $res['claims']['sub'] . '@login512.me']
);
Auth::login($user);
return response()->json(['success' => true, 'redirect' => route('dashboard')]);
}
}
3. ป้องกัน Route ใน routes/api.php
PHP
use Illuminate\Support\Facades\Route;
// login512.verified needs a FRESH single-use token (header X-Login512-Token) on every request: use it for sensitive actions
Route::middleware(['auth:sanctum', 'login512.verified'])->group(function () {
Route::post('/vip/vault/export', function () {
return response()->json(['vault' => 'Secure PQC Data']);
});
});
# .env.local
# LOGIN512_SECRET_KEY=l512_sk_live_your_secret
# LOGIN512_PUBLISHABLE_KEY=l512_pk_live_your_key
# config/routes/login512.yaml (GET /login512/nonce, POST /login512/verify)
login512:
resource: '@Login512SymfonyBundle/config/routes.php'
# config/packages/security.yaml
security:
providers:
login512:
id: Login512\SymfonyBundle\Security\Login512UserProvider
firewalls:
main:
lazy: true
provider: login512
custom_authenticators:
- Login512\SymfonyBundle\Security\Login512Authenticator
access_control:
- { path: ^/account, roles: ROLE_USER }
# Login page: the nonce stops login CSRF; POST /login512/verify starts the Symfony session.
# const cfg = await (await fetch('/login512/nonce', { credentials: 'same-origin' })).json();
# Login512.init({ publishableKey: cfg.publishableKey, endpoint: cfg.endpoint }).mountButton('#login512', {
# nonce: cfg.nonce,
# onSuccess: async (token) => {
# const r = await fetch(cfg.verifyUrl, { method: 'POST', credentials: 'same-origin',
# headers: { 'Content-Type': 'application/json' }, body: JSON.stringify({ token }) });
# const res = await r.json(); // 200 {ok, user, redirect} | 401 {ok: false, error}
# if (res.ok) location.href = res.redirect;
# },
# });
# The user is a Login512User (identifier = claims.sub, ROLE_USER). To log in your own user class,
# set login512.user_mapper to a Login512UserMapperInterface service (match a login512_sub column, never username/email).
2. เรียกใช้งาน Login512Client ใน Controller
PHP
namespace App\Controller;
use Login512\SymfonyBundle\Login512Client;
use Symfony\Bundle\FrameworkBundle\Controller\AbstractController;
use Symfony\Component\HttpFoundation\JsonResponse;
use Symfony\Component\HttpFoundation\Request;
use Symfony\Component\Routing\Attribute\Route;
class SecurityController extends AbstractController
{
#[Route('/api/verify-token', methods: ['POST'])]
public function verify(Request $request, Login512Client $login512): JsonResponse
{
$res = $login512->verifyToken((string) $request->toArray()['token']); // 2nd argument: expected nonce
// session_allowed, not valid: a valid token can still require a step-up. Tokens are single-use.
if (empty($res['session_allowed'])) {
return new JsonResponse(['error' => $res['error'] ?? 'STEP_UP_REQUIRED'], 401);
}
return new JsonResponse(['sub' => $res['claims']['sub']]);
}
}
package com.example.demo.controller;
import com.login512.spring.Login512Client;
import com.login512.spring.Login512VerifyResult;
import jakarta.servlet.http.HttpSession;
import java.util.Map;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.*;
@RestController
@RequestMapping("/api/auth")
public class AuthController {
private final Login512Client login512; // auto-configured by login512-spring-boot-starter
public AuthController(Login512Client login512) { this.login512 = login512; }
@PostMapping("/verify")
public ResponseEntity<?> verify(@RequestBody Map<String, String> body, HttpSession session) {
// nonce your server issued for this login (optional); never taken from the client
Login512VerifyResult r = login512.verify(body.get("token"), (String) session.getAttribute("login512_nonce"));
if (!r.sessionAllowed()) {
return ResponseEntity.status(401).body(Map.of("error", r.error())); // TOKEN_ALREADY_USED, ...
}
session.setAttribute("userId", r.subject()); // claims.sub = your external_user_id
return ResponseEntity.ok(Map.of("success", true, "userId", r.subject()));
}
}
3. เชื่อมต่อ Spring Security SecurityFilterChain
JAVA
# Build and install the starter once (until it is on Maven Central)
unzip spring-boot.zip -d login512-starter
mvn -f login512-starter/pom.xml install
# pom.xml of your app
<dependency>
<groupId>com.login512</groupId>
<artifactId>login512-spring-boot-starter</artifactId>
<version>2.1.1</version>
</dependency>
⚡
Java Quarkus (GraalVM Native)
Official ZIP Package • Quarkus 3.x • GraalVM Native • SmallRye JWT
// Tokens are always signed with ML-DSA-65; the API verifies the signature.
// What your code must check is that this login may start a session:
if !result.Valid || !result.SessionAllowed {
log.Println("คำเตือน: โทเคนไม่ได้เข้ารหัสด้วยอัลกอริทึมมาตรฐาน Post-Quantum")
}
🦀
Rust (Async Tokio & Axum)
Official ZIP Package • Rust 2021 Edition • Tokio Async • Axum / Actix-web
using Login512;
using System.Security.Claims;
var builder = WebApplication.CreateBuilder(args);
// เพิ่ม Login512 Post-Quantum Authentication Scheme
builder.Services.AddAuthentication("Login512")
.AddScheme<Login512AuthenticationOptions, Login512AuthenticationHandler>("Login512", opt =>
{
opt.SecretKey = builder.Configuration["Login512:SecretKey"] ?? "l512_sk_live_your_key";
opt.Endpoint = "https://login512.com";
});
builder.Services.AddAuthorization();
var app = builder.Build();
app.UseAuthentication();
app.UseAuthorization();
2. สร้าง Endpoint ที่ต้องการสิทธิ์ (Minimal API)
CSHARP
app.MapGet("/api/profile", (ClaimsPrincipal user) =>
{
var userId = user.FindFirstValue(ClaimTypes.NameIdentifier);
var authMode = user.FindFirstValue("login512_mode");
var pqc = user.FindFirstValue("pqc_algorithm");
return Results.Ok(new {
Status = "Success",
UserId = userId,
AuthMode = authMode,
PqcAlgorithm = pqc
});
}).RequireAuthorization();
app.Run();
3. การตรวจสอบโทเคนแบบ Direct Client (Background Worker)
CSHARP
var client = new Login512Client("l512_sk_live_your_key");
var res = await client.VerifyTokenAsync(incomingToken);
if (res.Valid) {
Console.WriteLine($"ยืนยันสำเร็จสำหรับ User: {res.UserId}");
}
💎
Ruby on Rails (Gem & Initializer)
Official ZIP Package • Rails 7 / 8 • Ruby 3.1+ • Devise & Warden Ready
import 'package:flutter/material.dart';
import 'package:login512_flutter/login512_flutter.dart';
Future<void> signIn(BuildContext context, String nonceFromYourServer) async {
final r = await Login512LoginView.login(context,
publishableKey: 'l512_pk_live_...',
appOrigin: 'https://app.example.com', // http(s) origin registered in your tenant
nonce: nonceFromYourServer);
if (r.token != null) {
// POST r.token to YOUR server; it verifies the token with the secret key
} else {
debugPrint('Login512: ${r.error}'); // e.g. CANCELLED
}
}
3. กำหนด Permission ใน Android & iOS
XML
<!-- Android: android/app/src/main/AndroidManifest.xml -->
<uses-permission android:name="android.permission.CAMERA" />
<uses-permission android:name="android.permission.INTERNET" />
<!-- iOS: ios/Runner/Info.plist -->
<key>NSCameraUsageDescription</key>
<string>Used to scan your face to sign in</string>
// 1. Unzip ios.zip (folder Login512)
// 2. Xcode > File > Add Package Dependencies... > Add Local... > select the Login512 folder
// 3. Add the "Login512" library to your app target, then:
import Login512
2. เรียกใช้งานใน SwiftUI View (ContentView.swift)
SWIFT
import SwiftUI
import Login512
struct LoginView: View {
@State private var show = true
var body: some View {
if show {
Login512LoginView(options: {
var o = Login512LoginViewController.Options(publishableKey: "l512_pk_live_...")
o.appOrigin = "https://app.example.com" // http(s) origin registered in your tenant
return o
}()) { result in
show = false
if case .success(let token) = result { /* POST token to YOUR server */ }
}
}
}
}
3. เพิ่ม Camera Usage Description ใน Info.plist
XML
<key>NSCameraUsageDescription</key>
<string>Used to scan your face to sign in</string>
🤖
Android Native (Kotlin & Compose)
Official ZIP Package • Android API 26+ • Kotlin 1.9+ • Jetpack Compose
// unzip android.zip and copy login512-android-2.1.1.aar to app/libs/
dependencies {
implementation(files("libs/login512-android-2.1.1.aar"))
implementation("androidx.activity:activity-ktx:1.9.3")
}
2. เริ่ม login จาก Activity (Login512Contract)
KOTLIN
import com.login512.android.Login512Contract
class LoginActivity : ComponentActivity() {
private val login512 = registerForActivityResult(Login512Contract()) { r ->
if (r.token != null) sendToServer(r.token) // YOUR server verifies it with the secret key
else Log.w("Login512", r.error ?: "CANCELLED")
}
fun startLogin(nonceFromYourServer: String) = login512.launch(
Login512Contract.Input(
publishableKey = "l512_pk_live_...",
appOrigin = "https://app.example.com", // http(s) origin registered in your tenant
nonce = nonceFromYourServer,
)
)
}
3. สิทธิ์การใช้งานใน AndroidManifest.xml
XML
<!-- merged from the AAR; listed for clarity -->
<uses-permission android:name="android.permission.CAMERA" />
<uses-permission android:name="android.permission.INTERNET" />
🌐
WordPress & WooCommerce Plugin
Official WP Plugin ZIP • WordPress 6.0+ • WooCommerce 7.0+ • 1-Click Face Login
Official Package (.tgz) • Strapi 5 • REST API (Users-Permissions)
Official SDKPQC Verified
Official Strapi Plugin สำหรับระบบ Headless CMS เพิ่มการเข้าสู่ระบบด้วย Login512 ให้ผู้ใช้ของ Users-Permissions Plugin (End-user API ไม่รวม Admin Panel)
ติดตั้ง:npm install strapi-plugin-login512
1. ติดตั้งและเปิดใช้งานใน config/plugins.js
JAVASCRIPT
// config/plugins.js
module.exports = ({ env }) => ({
login512: {
enabled: true,
config: {
secretKey: env('LOGIN512_SECRET_KEY'),
endpoint: 'https://api.login512.com',
createUsers: true, // false: only users this plugin created or linked before can log in
// requireNonce: true (default) and linkExistingByUsername: false (default), see the package README
},
},
});
2. Endpoint ตรวจสอบโทเคนของ Strapi
BASH
# 1) Nonce (kept in an httpOnly cookie on the Strapi host: send credentials). Stops login CSRF.
GET /api/login512/nonce -> { "nonce": "..." }
# 2) Give the nonce to the Login512 button, then exchange the token (alias: /api/login512/authenticate):
# Login512.init({ publishableKey, endpoint: 'https://api.login512.com' }).mountButton('#login512', { nonce, onSuccess })
POST /api/login512/login (credentials: 'include')
Content-Type: application/json
{ "token": "<token from the Login512 button>" }
# 200: { "jwt": "eyJhbGciOiJIUzI1NiIsIn...", "user": { "id": 1, "username": "<claims.sub>", "email": "..." } }
# Same session as POST /api/auth/local: new Strapi 5 apps also get the refresh token (httpOnly cookie
# strapi_up_refresh, or "refreshToken" in the body); renew with POST /api/auth/refresh.
# 401: { "error": { "status": 401, "name": "UnauthorizedError", "message": "TOKEN_ALREADY_USED" } }
# also NONCE_REQUIRED, NONCE_MISMATCH, TOKEN_BAD_SIGNATURE, STEP_UP_REQUIRED, USER_BLOCKED
# Clients without cookies (mobile, SPA on another site): generate the nonce yourself and send { token, nonce }.
# A subject equal to an existing username or email gets its OWN account (l512_...), not that user's.
3. การปกป้อง Custom Strapi Controller
JAVASCRIPT
module.exports = {
async secureAction(ctx) {
try {
// a fresh Login512 token sent by the client, e.g. header X-Login512-Token
await strapi.plugin('login512').service('auth').verifyToken(ctx.request.header['x-login512-token']);
} catch (err) {
return ctx.unauthorized(err.message);
}
return { data: 'Super Secret Headless Data' };
},
};
curl -LO https://login512.com/packages/drupal.zip
unzip drupal.zip -d web/modules/custom
drush en login512
# then: Configuration > People > Login512 (/admin/config/people/login512)
2. ขั้นตอนการเข้าสู่ระบบ
TEXT
GET /login512/nonce -> one-time nonce in the visitor's Drupal session
POST /login512/verify {"token": "..."} (JSON only, foreign Origin refused)
-> token verified with your SECRET key + expected_nonce
-> account linked by user data (never matched by user name)
-> Drupal session (user_login_finalize)
1. System > Install > Extensions > Install from URL:
https://login512.com/packages/joomla.zip
2. System > Plugins > "System - Login512": enable it and set
API endpoint, Publishable key (l512_pk_...), Secret key (l512_sk_...)
2. ขั้นตอนการเข้าสู่ระบบ
TEXT
The Login512 button appears on the site and administrator login forms.
com_ajax: task=nonce -> nonce in the Joomla session
task=verify {"token"} -> verified with your SECRET key + expected_nonce
-> account linked in #__user_profiles (never by user name or e-mail)
-> signed in through Joomla's own onUserLogin (blocked users stay blocked)
🛡️
Nginx / Kong Gateway
Official Package (.zip) • nginx auth_request • Kong 3.x
capacitor.config.ts: server: { iosScheme: 'https' } (Login512 accepts http(s) origins only)
Tenant allowed origins: https://localhost
iOS: NSCameraUsageDescription in Info.plist
Android: <uses-permission android:name="android.permission.CAMERA" />
Passkeys do not work inside an app WebView: use face scan.