33namespace FlexAuth \Type \JWT ;
44
55use FlexAuth \FlexAuthTypeProviderInterface ;
6+ use Symfony \Component \HttpFoundation \RedirectResponse ;
67use Symfony \Component \HttpFoundation \Request ;
78use Symfony \Component \HttpFoundation \Response ;
89use 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