Skip to content

Commit e9cc3a6

Browse files
authored
Merge pull request #87 from andrex47/master
new keycloak can one middleware
2 parents eb30758 + f58f657 commit e9cc3a6

File tree

2 files changed

+39
-0
lines changed

2 files changed

+39
-0
lines changed

src/KeycloakWebGuardServiceProvider.php

Lines changed: 4 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -13,6 +13,7 @@
1313
use Vizir\KeycloakWebGuard\Auth\KeycloakWebUserProvider;
1414
use Vizir\KeycloakWebGuard\Middleware\KeycloakAuthenticated;
1515
use Vizir\KeycloakWebGuard\Middleware\KeycloakCan;
16+
use Vizir\KeycloakWebGuard\Middleware\KeycloakCanOne;
1617
use Vizir\KeycloakWebGuard\Models\KeycloakUser;
1718
use Vizir\KeycloakWebGuard\Services\KeycloakService;
1819

@@ -72,6 +73,9 @@ public function register()
7273
// Add Middleware "keycloak-web-can"
7374
$this->app['router']->aliasMiddleware('keycloak-web-can', KeycloakCan::class);
7475

76+
// Add Middleware "keycloak-web-can-one
77+
$this->app['router']->aliasMiddleware('keycloak-web-can-one', KeycloakCanOne::class);
78+
7579
// Bind for client data
7680
$this->app->when(KeycloakService::class)->needs(ClientInterface::class)->give(function() {
7781
return new Client(Config::get('keycloak-web.guzzle_options', []));

src/Middleware/KeycloakCanOne.php

Lines changed: 35 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,35 @@
1+
<?php
2+
3+
namespace Vizir\KeycloakWebGuard\Middleware;
4+
5+
use Closure;
6+
use Illuminate\Auth\Access\AuthorizationException;
7+
use Illuminate\Support\Facades\Auth;
8+
use Vizir\KeycloakWebGuard\Exceptions\KeycloakCanException;
9+
10+
class KeycloakCanOne extends KeycloakAuthenticated
11+
{
12+
/**
13+
* Handle an incoming request.
14+
*
15+
* @param \Illuminate\Http\Request $request
16+
* @param \Closure $next
17+
* @param string|null $guard
18+
* @return mixed
19+
*/
20+
public function handle($request, Closure $next, ...$guards)
21+
{
22+
if (empty($guards) && Auth::check()) {
23+
return $next($request);
24+
}
25+
26+
$guards = explode('|', ($guards[0] ?? ''));
27+
foreach ($guards as $guard) {
28+
if (Auth::hasRole($guard)) {
29+
return $next($request);
30+
}
31+
}
32+
33+
throw new AuthorizationException('Forbidden', 403);
34+
}
35+
}

0 commit comments

Comments
 (0)