オーセンティケーターは、要求データを認証操作に変換します。 識別子を利用して、既知のIdentityオブジェクトを検索します。
Authenticators handle convert request data into an authentication operations. They leverage Identifiers to find a known Identity Objects.
この認証システムは、セッションにユーザーデータまたは資格情報が含まれているかどうかを確認します。下記のフォームなどのステートフル認証システムを使用する場合は、セッション認証システムを最初にロードして、ログインするとユーザーデータが後続のリクエストでセッション自体からフェッチされるようにします。
This authenticator will check the session if it contains user data or credentials. When using any stateful authenticators likeFormlisted below, be sure to loadSessionauthenticator first so that once logged in user data is fetched from session itself on subsequent requests.
構成オプション:
Configuration options:
Authです。
trueの値を設定して、識別子に対するセッション資格情報のチェックを有効にします。
trueの場合、構成された識別子を使用して、各リクエストでセッションに保存されたデータを使用してユーザーを識別します。
デフォルト値はfalseです。
usernameフィールドをユーザーストレージの一意の識別子にマップできます。
デフォルトはusernameです。
このオプションは、identifyオプションがtrueに設定されている場合に使用されます。
- sessionKey: The session key for the user data, default is
Auth- identify: Set this key with a value of bool
trueto enable checking the session credentials against the identifiers. Whentrue, the configured Identifiers are used to identify the user using data stored in the session on each request. Default value isfalse.- fields: Allows you to map the
usernamefield to the unique identifier in your user storage. Defaults tousername. This option is used when theidentifyoption is set to true.
リクエストの本文でデータを検索します。通常、フォームの送信が POST / PUT を介して行われるときに行われます。
Looks up the data in the request body, usually when a form submit happens via POST / PUT.
構成オプション:
Configuration options:
nullで、すべてのページがチェックされます。
ユーザー名とパスワードを指定されたPOSTデータフィールドにマップする配列。
DefaultUrlCheckerです。
falseです。
falseです。このオプションは、クエリ文字列で認証されていないリダイレクトを保持する場合はうまく機能しません。
- loginUrl: The login URL, string or array of URLs. Default is
nulland all pages will be checked.- fields: Array that maps
usernameandpasswordto the specified POST data fields.- urlChecker: The URL checker class or object. Default is
DefaultUrlChecker.- useRegex: Whether or not to use regular expressions for URL matching. Default is
false.- checkFullUrl: Whether or not to check full URL including the query string. Useful when a login form is on a different subdomain. Default is
false. This option does not work well when preserving unauthenticated redirects in the query string.
Warning
URLに配列構文を使用する場合、URLはCakePHPルーターによって生成されます。結果は、ルート処理によっては、リクエストURIに実際にあるものとは異なる場合があります。したがって、これは大文字と小文字が区別されると考えてください!
If you use the array syntax for the URL, the URL will be generated by the CakePHP router. The result might differ from what you actually have in the request URI depending on your route handling. So consider this to be case sensitive!
トークン認証システムは、ヘッダーまたは要求パラメーターで要求に付随するトークンに基づいて要求を認証できます。
The token authenticator can authenticate a request based on a token that comes along with the request in the headers or in the request parameters.
構成オプション:
Configuration options:
- queryParam: Name of the query parameter. Configure it if you want to get the token from the query parameters.
- header: Name of the header. Configure it if you want to get the token from the header.
- tokenPrefix: The optional token prefix.
ヘッダーまたはクエリ文字列からトークンを取得する例は次のようになります:
An example of getting a token from a header, or query string would be:
$service->loadAuthenticator('Authentication.Token', [
'queryParam' => 'token',
'header' => 'Authorization',
'tokenPrefix' => 'Token'
]);
上記は、トークンの前にトークンとスペースが続く限り、トークンのGETパラメーターまたはAuthorizationヘッダーを読み取ります。
The above would read thetokenGET parameter or theAuthorizationheader as long as the token was preceded byTokenand a space.
トークンは常に、次のように構成済みの識別子に渡されます:
The token will always be passed to the configured identifier as follows:
[
'token' => '{token-value}',
]
JWTオーセンティケーターは、ヘッダーまたはクエリパラメーターからJWTトークンを取得し、ペイロードを直接返すか、ペイロードを識別子に渡して、たとえば別のデータソースと照合して検証します。
The JWT authenticator gets the JWT token from the header or query param and either returns the payload directly or passes it to the identifiers to verify them against another datasource for example.
Authorizationです。
tokenです。
bearerです。
['HS256']です。
trueです。
nullですが、Security::salt()を介して提供するCakePHPアプリケーションのコンテキストでない場合は、秘密鍵を渡す必要があります。
- header: The header line to check for the token. The default is
Authorization.- queryParam: The query param to check for the token. The default is
token.- tokenPrefix: The token prefix. Default is
bearer.- algorithms: An array of hashing algorithms for Firebase JWT. Default is an array
['HS256'].- returnPayload: To return or not return the token payload directly without going through the identifiers. Default is
true.- secretKey: Default is
nullbut you’re required to pass a secret key if you’re not in the context of a CakePHP application that provides it throughSecurity::salt().
デフォルトでは、JwtAuthenticatorはHS256対称鍵アルゴリズムを使用し、Cake\Utility\Security::salt()の値を暗号化鍵として使用します。セキュリティを強化するために、代わりにRS256非対称キーアルゴリズムを使用できます。そのために必要なキーを次のように生成できます:
By default theJwtAuthenticatorusesHS256symmetric key algorithm and uses the value ofCake\Utility\Security::salt()as encryption key. For enhanced security one can instead use theRS256asymmetric key algorithm. You can generate the required keys for that as follows:
# generate private key
openssl genrsa -out config/jwt.key 1024
# generate public key
openssl rsa -in config/jwt.key -outform PEM -pubout -out config/jwt.pem
jwt.keyファイルは秘密鍵であり、安全に保管する必要があります。jwt.pemファイルは公開鍵です。このファイルは、外部アプリケーションによって作成されたトークンを検証する必要がある場合に使用する必要があります。例:モバイルアプリ。
Thejwt.keyfile is the private key and should be kept safe. Thejwt.pemfile is the public key. This file should be used when you need to verify tokens created by external applications, eg: mobile apps.
次の例では、JwtSubject識別子を使用してトークンのsub (subject)に基づいてユーザーを識別し、公開鍵を使用してトークンを検証するようにAuthenticatorを構成できます:
The following example allows you to identify the user based on thesub(subject) of the token by usingJwtSubjectidentifier, and configures theAuthenticatorto use public key for token verification:
以下をApplicationクラスに追加します:
Add the following to your Application class:
public function getAuthenticationService(ServerRequestInterface $request): AuthenticationServiceInterface
{
$service = new AuthenticationService();
// ...
$service->loadIdentifier('Authentication.JwtSubject');
$service->loadAuthenticator('Authentication.Jwt', [
'secretKey' => file_get_contents(CONFIG . '/jwt.pem'),
'algorithms' => ['RS256'],
'returnPayload' => false
]);
}
UsersControllerで:
In your UsersController:
public function login()
{
$result = $this->Authentication->getResult();
if ($result->isValid()) {
$privateKey = file_get_contents(CONFIG . '/jwt.key');
$user = $result->getData();
$payload = [
'iss' => 'myapp',
'sub' => $user->id,
'exp' => time() + 60,
];
$json = [
'token' => JWT::encode($payload, $privateKey, 'RS256'),
];
} else {
$this->response = $this->response->withStatus(401);
$json = [];
}
$this->set(compact('json'));
$this->viewBuilder()->setOption('serialize', 'json');
}
公開鍵ファイルを外部アプリケーションと共有するだけでなく、次のようにアプリを構成することで、JWKSエンドポイントを介してファイルを配布できます:
Beside from sharing the public key file to external application, you can distribute it via a JWKS endpoint by configuring your app as follows:
// config/routes.php
$builder->setExtensions('json');
$builder->connect('/.well-known/:controller/*', [
'action' => 'index',
], [
'controller' => '(jwks)',
]); // connect /.well-known/jwks.json to JwksController
// controller/JwksController.php
public function index()
{
$pubKey = file_get_contents(CONFIG . './jwt.pem');
$res = openssl_pkey_get_public($pubKey);
$detail = openssl_pkey_get_details($res);
$key = [
'kty' => 'RSA',
'alg' => 'RS256',
'use' => 'sig',
'e' => JWT::urlsafeB64Encode($detail['rsa']['e']),
'n' => JWT::urlsafeB64Encode($detail['rsa']['n']),
];
$keys['keys'][] = $key;
$this->viewBuilder()->setClassName('Json');
$this->set(compact('keys'));
$this->viewBuilder()->setOption('serialize', 'keys');
}
JWKSの詳細については、https://tools.ietf.org/html/rfc7517またはhttps://auth0.com/docs/tokens/concepts/jwksを参照してください。
Refer to https://tools.ietf.org/html/rfc7517 or https://auth0.com/docs/tokens/concepts/jwks for more information about JWKS.
https://en.wikipedia.org/wiki/Basic_access_authenticationを参照してください
See https://en.wikipedia.org/wiki/Basic_access_authentication
構成オプション:
Configuration options:
$_SERVER['SERVER_NAME']で、必要に応じてオーバーライドします。
- realm: Default is
$_SERVER['SERVER_NAME']override it as needed.
https://en.wikipedia.org/wiki/Digest_access_authenticationを参照してください
See https://en.wikipedia.org/wiki/Digest_access_authentication
構成オプション:
Configuration options:
nullです
authです
uniqid(''),です
nullです
- realm: Default is
null- qop: Default is
auth- nonce: Default is
uniqid(''),- opaque: Default is
null
クッキー認証を使用すると、ログインフォームに「記憶」機能を実装できます。
The Cookie Authenticator allows you to implement the “remember me” feature for your login forms.
ログインフォームに、この認証システムで構成されているフィールド名と一致するフィールドがあることを確認してください。
Just make sure your login form has a field that matches the field name that is configured in this authenticator.
クッキーを暗号化および復号化するには、AuthenticationMiddlewareの前にアプリにEncryptedCookieMiddlewareを追加してください。
To encrypt and decrypt your cookie make sure you added the EncryptedCookieMiddleware to your app before the AuthenticationMiddleware.
構成オプション:
Configuration options:
remember_meです。
CookieAuthです。
nullです。
/です。
falseです。
falseです。
ユーザー名とパスワードを指定されたアイデンティティーフィールドにマップする配列。
DefaultUrlCheckerです。
nullで、すべてのページがチェックされます。
DefaultPasswordHasher::classです。
- rememberMeField: Default is
remember_me- cookie: Array of cookie options:
- name: Cookie name, default is
CookieAuth- expire: Expiration, default is
null- path: Path, default is
/- domain: Domain, default is an empty string ``
- secure: Bool, default is
false- httpOnly: Bool, default is
false- value: Value, default is an empty string ``
- fields: Array that maps
usernameandpasswordto the specified identity fields.- urlChecker: The URL checker class or object. Default is
DefaultUrlChecker.- loginUrl: The login URL, string or array of URLs. Default is
nulland all pages will be checked.- passwordHasher: Password hasher to use for token hashing. Default is
DefaultPasswordHasher::class.
現在、OAuth認証システムを実装する計画はありません。 この主な理由は、OAuth 2.0が認証プロトコルではないことです。
There are currently no plans to implement an OAuth authenticator. The main reason for this is that OAuth 2.0 is not an authentication protocol.
このトピックの詳細については、こちらをご覧ください。
Read more about this topic here.
将来的にはOpenID Connectオーセンティケーターを追加するかもしれません。
We will maybe add an OpenID Connect authenticator in the future.
認証によって発生するイベントは1つだけです:Authentication.afterIdentify。
There is only one event that is fired by authentication:
Authentication.afterIdentify.
イベントとその使用方法がわからない場合は、ドキュメントを確認してください。
If you don’t know what events are and how to use them check the documentation.
Authentication.afterIdentifyイベントは、IDが正常に識別された後にAuthenticationComponentによって発生します。
TheAuthentication.afterIdentifyevent is fired by theAuthenticationComponentafter an identity was successfully identified.
イベントには次のデータが含まれます:
The event contains the following data:
\Authentication\Authenticator\AuthenticatorInterface
\ArrayAccess
\Authentication\AuthenticationServiceInterface
- provider: An object that implements
\Authentication\Authenticator\AuthenticatorInterface- identity: An object that implements
\ArrayAccess- service: An object that implements
\Authentication\AuthenticationServiceInterface
イベントの件名は、AuthenticationComponentがアタッチされている現在のコントローラーインスタンスです。
The subject of the event will be the current controller instance the AuthenticationComponent is attached to.
ただし、このイベントは、IDの識別に使用されたオーセンティケーターが永続的でなく、ステートレスでない場合にのみ発生します。これは、たとえば、セッション認証またはトークンがすべてのリクエストに対して毎回トリガーされるため、イベントが毎回発生するためです。
But the event is only fired if the authenticator that was used to identify the identity is not persistent and not stateless. The reason for this is that the event would be fired every time because the session authenticator or token for example would trigger it every time for every request.
含まれているオーセンティケーターからFormAuthenticatorのみがイベントを発生させます。その後、セッション認証システムがIDを提供します。
From the included authenticators only the FormAuthenticator will cause the event to be fired. After that the session authenticator will provide the identity.
フォームやクッキーなどの一部の認証システムは、/loginページなどの特定のページでのみ実行する必要があります。これは、URLチェッカーを使用して実現できます。
Some authenticators likeFormorCookieshould be executed only on certain pages like/loginpage. This can be achieved using URL Checkers.
デフォルトでは、DefaultUrlCheckerが使用されます。これは、正規表現チェックのサポートとの比較に文字列URLを使用します。
By default a DefaultUrlChecker is used, which uses string URLs for
comparison with support for regex check.
構成オプション:
Configuration options:
falseです。
falseです。
- useRegex: Whether or not to use regular expressions for URL matching. Default is
false.- checkFullUrl: Whether or not to check full URL. Useful when a login form is on a different subdomain. Default is
false.
フレームワーク固有のURLのサポートが必要な場合などに、カスタムURLチェッカーを実装できます。この場合、Authentication\UrlChecker\UrlCheckerInterfaceを実装する必要があります。
A custom URL checker can be implemented for example if a support for
framework specific URLs is needed. In this case the
Authentication\UrlChecker\UrlCheckerInterface should
be implemented.
URLチェッカーの詳細については、こちらのドキュメントページをご覧ください。
For more details about URL Checkers see this documentation page.
ユーザーが認証された後、ユーザーの認証に成功したオーセンティケーターを検査または操作することができます:
After a user has been authenticated you may want to inspect or interact with the Authenticator that successfully authenticated the user:
// In a controller action
$service = $this->request->getAttribute('authentication');
// Will be null on authentication failure, or an authenticator.
$authenticator = $service->getAuthenticationProvider();
ユーザーを識別する識別子も取得できます:
You can also get the identifier that identified the user as well:
// In a controller action
$service = $this->request->getAttribute('authentication');
// Will be null on authentication failure, or an identifier.
$identifier = $service->getIdentificationProvider();
TokenまたはHttpBasic、HttpDigestを他のオーセンティケーターとともに使用する場合、これらのオーセンティケーターは、認証資格情報が欠落しているか無効な場合に要求を停止することを覚えておく必要があります。これらの認証システムは応答で特定のチャレンジヘッダーを送信する必要があるため、これは必要です:
When usingTokenorHttpBasic,HttpDigestwith other authenticators, you should remember that these authenticators will halt the request when authentication credentials are missing or invalid. This is necessary as these authenticators must send specific challenge headers in the response:
use Authentication\AuthenticationService;
// Instantiate the service
$service = new AuthenticationService();
// Load identifiers
$service->loadIdentifier('Authentication.Password', [
'fields' => [
'username' => 'email',
'password' => 'password'
]
]);
$service->loadIdentifier('Authentication.Token');
// Load the authenticators leaving Basic as the last one.
$service->loadAuthenticator('Authentication.Session');
$service->loadAuthenticator('Authentication.Form');
$service->loadAuthenticator('Authentication.Token');
HttpBasicまたはHttpDigestを他のオーセンティケーターと組み合わせる場合は、これらのオーセンティケーターが要求を中止し、ブラウザーダイアログを強制することに注意してください。
If you want to combineHttpBasicorHttpDigestwith other authenticators, be aware that these authenticators will abort the request and force a browser dialog.
AuthenticationComponent、ユーザーが認証されていない場合に例外を発生させます。AuthenticationServiceを構成するときにunauthenticatedRedirectを使用して、この例外をリダイレクトに変換できます。
TheAuthenticationComponentwill raise an exception when users are not authenticated. You can convert this exception into a redirect using theunauthenticatedRedirectwhen configuring theAuthenticationService.
queryParamオプションを使用して、現在のリクエストターゲットURIをクエリパラメータとして渡すこともできます:
You can also pass the current request target URI as a query parameter
using the queryParam option:
// In the getAuthenticationService() method of your src/Application.php
$service = new AuthenticationService();
// Configure unauthenticated redirect
$service->setConfig([
'unauthenticatedRedirect' => '/users/login',
'queryParam' => 'redirect',
]);
次に、コントローラーのログインメソッドでgetLoginRedirect()を使用して、クエリ文字列パラメーターからリダイレクトターゲットを安全に取得できます。
Then in your controller’s login method you can use getLoginRedirect() to get
the redirect target safely from the query string parameter:
public function login()
{
$result = $this->Authentication->getResult();
// Regardless of POST or GET, redirect if user is logged in
if ($result->isValid()) {
// Use the redirect parameter if present.
$target = $this->Authentication->getLoginRedirect();
if (!$target) {
$target = ['controller' => 'Pages', 'action' => 'display', 'home'];
}
return $this->redirect($target);
}
}