PHP Laravel
-
There are constants in config file.
-
mariadb is used as the database.
-
Imports are:
use App\Http\Controllers\Controller;
use Illuminate\Http\Request;
use Illuminate\Http\Response;
use Illuminate\Support\Facades\Http;
use Illuminate\Support\Facades\DB;
use Lcobucci\JWT\Builder; // v3.3
use Lcobucci\JWT\Parser;
- Config file:
return [
'OIDC_AUTH_END_POINT' => "https://tenantname.aws1.test1.com/auth/realms/{tenantname}/protocol/openid-connect/auth",
'OIDC_CLIENT' => "oidctest",
'OIDC_CLIENT_SECRET' => "029c6a91-4624-40cf-af4c-23b647318a2e",
'OIDC_TOKEN_URI' => "https://tenantname.aws1.test1.com/auth/realms/{tenantname}/protocol/openid-connect/token"
];
/auth/oidc
(GET)
public function oidc(Request $request){
$redirect_uri = $request->query('redirect_uri');
$length = 8;
$keyspace = '0123456789abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ';
if ($length < 1) {
throw new RangeException("Length must be a positive integer");
}
$pieces = [];
$max = mb_strlen($keyspace, '8bit') - 1;
for ($i = 0; $i < $length; ++$i) {
$pieces []= $keyspace[random_int(0, $max)];
}
$nonce = implode('', $pieces);
$url = sprintf("%s?client_id=%s&redirect_uri=%s&scope=openid&response_type=code&response_mode=query&nonce=%s",config("openid.OIDC_AUTH_END_POINT"), config("openid.OIDC_CLIENT"),$redirect_uri ,$nonce);
return response()->json([
'client_id' => config("openid.OIDC_CLIENT"),
'auth_url' => config("openid.OIDC_AUTH_END_POINT"),
'composed_url' => $url
],200);
}
/auth/code
(POST)
public function code(Request $request){
$code = $request->input('code');
$redirect_uri = $request->input('redirect_uri');
$response = Http::asForm()->post(config("openid.OIDC_TOKEN_URI"), [
'code' => $code,
'client_id' => config('openid.OIDC_CLIENT'),
'grant_type' => "authorization_code",
'client_secret' => config('openid.OIDC_CLIENT_SECRET'),
'redirect_uri' => $redirect_uri
]);
if (!$response->ok()) {
return response()->json([
'error' => $response->json(),
]);
}
$data = $response->json();
$id_token = $data['id_token'];
$decoded = (new Parser())->parse($id_token);
$email = $decoded->getClaim("email");
$users = DB::select('select * from users where email = ?', [$email]);
if (empty($users)){
DB::insert('insert into users (email) values (?, ?)', [$email]);
}
$user = [
'email' => $email
];
$time = time();
$builder = new Builder();
// Lcobucci v3.3
$token = $builder->issuedBy('http://example.com')
->identifiedBy('4f1g23a12aa', true)
->issuedAt($time)
->canOnlyBeUsedAfter($time + 60)
->expiresAt($time + 3600)
->with('email', $email)
->getToken();
return response()->json([
'token' => ((string)$token),
'user' => $user
],200);
}
info
- This repo contains a Laravel and Plain PHP based app that expresses the Implicit flow of OpenID Connect - Laravel PHP - Authorization Flow and Plain PHP - Authorization Flow.