Skip to content

Commit c673abe

Browse files
authored
Merge pull request #8 from linkorb/fix
allow redirect to login page for jwt authentication
2 parents cf96b5f + eef12bd commit c673abe

File tree

1 file changed

+12
-3
lines changed

1 file changed

+12
-3
lines changed

src/Type/JWT/JWTTokenAuthenticator.php

Lines changed: 12 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -3,6 +3,7 @@
33
namespace FlexAuth\Type\JWT;
44

55
use FlexAuth\FlexAuthTypeProviderInterface;
6+
use Symfony\Component\HttpFoundation\RedirectResponse;
67
use Symfony\Component\HttpFoundation\Request;
78
use Symfony\Component\HttpFoundation\Response;
89
use Symfony\Component\Security\Core\Authentication\Token\TokenInterface;
@@ -20,23 +21,26 @@ class JWTTokenAuthenticator extends AbstractGuardAuthenticator
2021
const TOKEN_HEADER = 'Authorization';
2122
const TOKEN_PREFIX = 'Bearer ';
2223

23-
2424
/** @var JWTUserFactoryInterface */
2525
private $JWTUserFactory;
2626
/** @var JWTEncoderInterface */
2727
private $JWTEncoder;
2828
/** @var FlexAuthTypeProviderInterface */
2929
private $flexAuthTypeProvider;
30+
/** @var string|null */
31+
private $loginUrl;
3032

3133
public function __construct(
3234
JWTUserFactoryInterface $JWTUserFactory,
3335
JWTEncoderInterface $JWTEncoder,
34-
FlexAuthTypeProviderInterface $flexAuthTypeProvider
36+
FlexAuthTypeProviderInterface $flexAuthTypeProvider,
37+
?string $loginUrl = null
3538
)
3639
{
3740
$this->JWTUserFactory = $JWTUserFactory;
3841
$this->JWTEncoder = $JWTEncoder;
3942
$this->flexAuthTypeProvider = $flexAuthTypeProvider;
43+
$this->loginUrl = $loginUrl;
4044
}
4145

4246
public function supports(Request $request)
@@ -109,7 +113,12 @@ public function checkCredentials($credentials, UserInterface $user)
109113

110114
public function start(Request $request, AuthenticationException $authException = null)
111115
{
112-
return new Response(sprintf('"%s" header required', self::TOKEN_HEADER), 401);
116+
$isAcceptHtml = $request->headers->has('Accept') && strpos($request->headers->get('Accept'), 'text/html') !== false;
117+
if ($this->loginUrl && $isAcceptHtml) {
118+
return new RedirectResponse($this->loginUrl);
119+
} else {
120+
return new Response(sprintf('"%s" header required', self::TOKEN_HEADER), 401);
121+
}
113122
}
114123

115124
public function onAuthenticationFailure(Request $request, AuthenticationException $exception)

0 commit comments

Comments
 (0)