回答:
8.2から、DrupalはCookie認証のjsonエンドポイントをサポートします。もうフォームを投稿する必要はありません🎉
curl --header "Content-type: application/json" --request POST \
--data '{"name":"admin", "pass":"admin"}' \
http://drupal.d8/user/login?_format=json
出力は次のようになります
{"current_user":{"uid":"1","roles":["authenticated","administrator"],"name":"admin"},"csrf_token":"wBr9ldleaUhmP4CgVh7PiyyxgNn_ig8GgAan9-Ul3Lg","logout_token":"tEulBvihW1SUkrnbCERWmK2jr1JEN_mRAQIdNNhhIDc"}
レコードの変更:https : //www.drupal.org/node/2720655
その他の認証方法:https : //www.drupal.org/docs/8/core/modules/rest/using-other-authentication-protocols
Drupal 8 RESTのJavaScript経由でログインする方法は次のとおりです。
Drupal 8.2以降
http://example.com/user/login?_format=json
application/json
{ "name": "admin", "pass": "myPassword" }
200 OK
これにより、Cookie認証を介して適切にログインし、次のような結果が返されます。
{
"current_user": {
"uid":"1",
"roles":["authenticated"],
"name":"admin"
},
"csrf_token":"abc123",
"logout_token":"def456"
}
JavaScriptでのログインを非常に簡単にするjDrupalというcontribモジュールを作成しました。
// Login and show the user their id.
jDrupal.userLogin('admin', 'myPassword').then(function() {
alert(jDrupal.currentUser().id());
});
Drupal 8.2より前
http://example.com/user/login
application/x-www-form-urlencoded
name=admin&pass=myPassword&form_id=user_login_form
200 OK | 303 See Other
クエリ文字列としてURLでデータを送信します。結果はHTMLになるため、有用なものは何も返されませんが、Cookie認証を介して適切にログインします。
RESTful認証は、ステートレスであるため、各リクエストで認証を送信することを意味します。Drupal 8コアが提供する例はBasic Authモジュールです。これにより、GETを介してコンテンツにアクセスする権限を持つユーザーが指定された場合、Basic HTTP認証を介してHTTP要求の認証資格情報を送信できます。
カール: curl -vvv -k -H "Authorization: Basic test:password" http://8.d8.local/node/1?_format=json
GET /node/1?_format=json HTTP/1.1
Host: 8.d8.local
User-Agent: curl/7.43.0
Accept: */*
Authorization: Basic test:password
ただし、これでは通常十分ではありません。simple_oauthとOAuthの A HTTPリクエストは、OAuthの作業に基づいて、OAuth認証トークンを用いて作製することが可能なcontribモジュールそれぞれのOAuth 2と1のサポートを提供するが、これらのモジュールに記載流れます。
しかし、本当の質問は
そうするための安定したDrupal 8モジュールはありませんが、サービスモジュールは、「ログイン」などの非RESTfulアクションおよびターゲットアクションを作成するためのメソッドを提供します。
「api」というエンドポイントを設定すると、次のように動作します。
カール: curl -vvv -k -H "Content-Type: application/json" -H "Accept: application/json" -d '{"username": "test", "password": "password"}' http://8.d8.local/api/user/login
POST /api/user/login HTTP/1.1
Host: 8.d8.local
Accept: application/json
Content-Type: application/json
Content-Length: 44
{"username": "test", "password": "password"}
これにより、JSONセッションのIDと名前が返されます(応答のSet-Cookieヘッダーでも設定されます)。
また、次のスニペットでJquery ajax呼び出しでログインできます
$.ajax({
url : "http://gttc.dd:8083/user/login",
type : 'post',
data : 'form_id=user_login_form&name=' + encodeURIComponent("username") + '&pass=' + encodeURIComponent("password"),
dataType : 'json',
error : function(data) {
//error code
},
success : function(data) {
console.log(data);
//success code
}
});
Drupal Coreバージョン:8.x-4.x
最初にユーザーログインサービスを有効にする必要があります。これはさまざまな方法で実現できます。RESTUIモジュールを使用することをお勧めします。
ゴーへ/管理/設定/サービス/休息と有効ユーザー RESTリソースを。
有効にすると、ユーザーリソースの横にある[ 編集 ]をクリックして、/ admin / config / services / rest / resource / entity%3Auser / editに移動できます。GETメソッドを必ず有効にしてください。
すべての設定が完了したら、ターミナルでこのコマンドを実行するか、PostmanおよびRestletクライアントなどのcurlリクエスト用のアプリケーションを使用して、サービスの使用を開始できます。
注:CSRFトークンは、/ rest / session / tokenから取得できます。
curl -i -L -X POST \
-H "Content-Type:application/json" \
-H "Accept:application/json" \
-H "X-CSRF-aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa" \
-d \
'{
"name": "my_username",
"pass": "my_password"
}' \
'http://SITE-URL/user/login?_format=json'
返されるオブジェクトは次のとおりです。
成功:
{
"current_user": {
"uid": "1",
"roles": [
"authenticated"
],
"name": "Admin"
},
"csrf_token": "bbbbbbbbbbbbbbbbbbbbbbbbbb",
"logout_token": "ccccccccccccccccccccccccc"
}
失敗:
{
"message":"Sorry, unrecognized username or password."
}
drupal 8ではカスタムRESTFulログインを使用しますが、Cookieでは使用しません。モバイルアプリ用であり、情報が必要になるたびに、単純なAuthenticateを使用します。
Drupal 8.2x以降、モジュールには2つのファイルが必要です。
config / installフォルダー内のrest.ressource.user.rest_ressource.yml
langcode: en
status: true
dependencies:
module:
- basic_auth
id: user.rest_ressource
plugin_id: 'user_rest_ressource'
granularity: resource
configuration:
methods:
- GET
- PATCH
formats:
- json
authentication:
- basic_auth
DELETE / POSTなどのメソッドを追加できます
次に、ファイルが必要です
src / Plugin / rest / resourceのuserRestRessource.php
<?php
namespace Drupal\yourmodule\Plugin\rest\resource;
use Drupal\Core\Session\AccountProxyInterface;
use Drupal\rest\Plugin\ResourceBase;
use Drupal\rest\ResourceResponse;
use Symfony\Component\DependencyInjection\ContainerInterface;
use Psr\Log\LoggerInterface;
/**
* Provides a resource to get view modes by entity and bundle.
*
* @RestResource(
* id = "user_rest_ressource",
* label = @Translation("User Rest"),
* uri_paths = {
* "canonical" = "/api/user/getInfo"
* }
* )
*/
class UserRestRessource extends ResourceBase {
/**
* A current user instance.
*
* @var \Drupal\Core\Session\AccountProxyInterface
*/
protected $currentUser;
/**
* Constructs a Drupal\rest\Plugin\ResourceBase object.
*
* @param array $configuration
* A configuration array containing information about the plugin instance.
* @param string $plugin_id
* The plugin_id for the plugin instance.
* @param mixed $plugin_definition
* The plugin implementation definition.
* @param array $serializer_formats
* The available serialization formats.
* @param \Psr\Log\LoggerInterface $logger
* A logger instance.
* @param \Drupal\Core\Session\AccountProxyInterface $current_user
* A current user instance.
*/
public function __construct(
array $configuration,
$plugin_id,
$plugin_definition,
array $serializer_formats,
LoggerInterface $logger,
AccountProxyInterface $current_user) {
parent::__construct($configuration, $plugin_id, $plugin_definition, $serializer_formats, $logger);
$this->currentUser = $current_user;
}
/**
* {@inheritdoc}
*/
public static function create(ContainerInterface $container, array $configuration, $plugin_id, $plugin_definition) {
return new static(
$configuration,
$plugin_id,
$plugin_definition,
$container->getParameter('serializer.formats'),
$container->get('logger.factory')->get('yourmodulename'),
$container->get('current_user')
);
}
/**
* Responds to GET requests.
*
* Returns a list of bundles for specified entity.
*
* @throws \Symfony\Component\HttpKernel\Exception\HttpException
* Throws exception expected.
*/
public function get() {
$uid=$this->currentUser->getAccount()->id();
$role=$this->currentUser->getAccount()->getRoles(1);
//here you can add your custom code
$responseResource=new ResourceResponse(
array()
);
return $responseResource;
}
/**
* Responds to PATCH requests.
*
* Returns a list of bundles for specified entity.
*
* @throws \Symfony\Component\HttpKernel\Exception\HttpException
* Throws exception expected.
*/
public function patch(){
}
}
承認メソッドGET / POSTまたは設定に追加したもののユーザー権利に移動することを忘れないでください。
これにより、すべてのカスタムエンティティに対してすべてのカスタムRESTファイルを作成できます。
そして私のJSで:電話することを忘れないでください
yoursiteUrl / rest / session / token
トークン取得
$http({
method: 'GET',
url: 'siteUrl/api/user/getInfo?_format=json',
withCredentials:true,
headers: {
'Content-Type': "application/hal+json",
'X-CSRF-Token': token,
'Authorization': 'Basic ' + btoa(user+':'+password),
},
}).then(function successCallback(response) {
return response;
}, function errorCallback(response) {
return false;
});
@ tyler.frankensteinの回答に従って、Ajaxでログインフォームを実装する場合は、たとえばjQueryを使用できます。
user/login
Drupal 8 APIのエンドポイントにPOSTリクエストを行う必要があります。このエンドポイント(「安全でない方法」と見なされる)では、CSRFトークンを送信する必要があります。
最初のステップは、rest/session/token
エンドポイントにAJAXリクエストを送信してこのトークンを取得することです。
var getCsrfToken = function(callback) {
$.get(Drupal.url('rest/session/token'))
.done(function (data) {
var csrfToken = data;
callback(csrfToken);
});
}
注意:
callback
パラメータは、CSRFトークンがフェッチされるときに呼び出されるコールバック関数ですDrupal.url
関数を使用して、サイトのベースURLを取得しますこのトークンはX-CSRF-Token
ヘッダーとともに送信する必要があります。
次のHTMLを検討してください。
<form id="login" method="post" action="" accept-charset="UTF-8">
<div class="input-field">
<input id="edit-name" name="name" type="text" class="validate">
<label for="edit-name">Username or email address</label>
</div>
<div class="input-field">
<input id="edit-pass" name="pass" type="password" class="validate">
<label for="edit-pass">Password</label>
</div>
<p><a href="{{ url('user.pass') }}">Forgot your password?</a></p>
<button type="submit" class="btn btn-default btn-submit">Sign in</button>
</form>
...および対応するjQueryコード:
$('form#login').on('submit', function(e) {
e.preventDefault();
var inputUsername = $('#edit-name').val();
var inputPassword = $('#edit-pass').val();
if (inputUsername != '' && inputPassword != '') {
getCsrfToken(function(csrfToken) {
$.ajax({
url: Drupal.url('user/login?_format=json'),
type: 'POST',
dataType: 'json',
data: JSON.stringify({name: inputUsername, pass: inputPassword}),
headers: {
'X-CSRF-Token': csrfToken
},
}).done(function(response) {
if (response.current_user) {
console.log('The user is logged!');
}
}).fail(function(jqXHR, textStatus) {
...
});
});
}
});
このコードはDrupal 8.3で正常にテストされています。
これがお役に立てば幸いです!