Difference between revisions of "I2Rest Advanced Setup"

From i2Rest
Jump to: navigation, search
m
m
Line 6: Line 6:
 
* Использование file: ендпойнт
 
* Использование file: ендпойнт
 
* How to require OAuth2 authentication (тут только *LOCAL сессии и минимальную настройку юзера, клиента и скоупа для run_program, pcml для echo)
 
* How to require OAuth2 authentication (тут только *LOCAL сессии и минимальную настройку юзера, клиента и скоупа для run_program, pcml для echo)
* How to allow command API (тут только *LOCAL сессии и минимальную настройку юзера, клиента и скоупа для run_command)
+
* How to allow command call API (тут только *LOCAL сессии и минимальную настройку юзера, клиента и скоупа для run_command)
 
* How to allow calls to management API
 
* How to allow calls to management API
 
* How to call API located on remote IBM i server
 
* How to call API located on remote IBM i server

Revision as of 08:54, 27 June 2020

Паша, я думал что не так с этим документом. Мне кажется он слишком сумбурный и тяжелый. Переспал с этой мыслью :) Предлагаю такой порядок изложения:
"На данной странице приведены различные варианты настройки сервера, позволяющие достить тех или иных результатов. Вы можете комбинировать данные примеры для того чтобы получить конфигурацию, которая удовлетворят вашим требованиям."
Дальше делаем список ссылок на страницы, в которых приводим примеры различных кейсов, у тебя я так понял уже большая коллекция :)

  • Защита соединений при помощи https
  • Использование file: ендпойнт
  • How to require OAuth2 authentication (тут только *LOCAL сессии и минимальную настройку юзера, клиента и скоупа для run_program, pcml для echo)
  • How to allow command call API (тут только *LOCAL сессии и минимальную настройку юзера, клиента и скоупа для run_command)
  • How to allow calls to management API
  • How to call API located on remote IBM i server
  • Custom scopes. Пока тут можно рассказать про то что можно добавить собственный скоуп, использовать его в настройке полномочий и передавать его в сессию
  • Примеры настройки различных API - ссылка на страницу на которой будет список ссылок на страницы с различными примерами PCML (библиотека примеров настроек PCML)

Каждый раздел описывается на отдельной странице, аналогично тому как описан basic сценарий. То есть - в начале пишем что в этом сценарии отражено, описываем предварительные действия и приводим целиком все связанные со сценарием настройки (json и pcml), красным выделяем места которые нужно поменять под себя. Json должен быть таким, чтобы в нем были очевидны те минимальные отличия от basic, которые нужны для того чтобы решить требуемую задачу. Возможно эти отличия получится выделить цветом. В конце можно привести ссылки на основные точки в reference, которые важны для этого кейса

Мне кажется так документ приобретет чистую структуру, не будет перегружен, и в то же время его можно будет легко расширять


This section describes configuration options of i2Rest Server. Basic configuration allows only demo server functionaliy, and must be extended to supply full functional server instancence.

Some words about basic configuration

Should start with important explanations about the basic configuration (shown bellow in snippets for your convenience).

i2Rest Gates

...
   "gates":
   {
      "main"       : {"url":"http://<host_name>[:port] (for example api.i2rest.com:1234)"},
      "management" : {"url":"http://<host_name>[:port] (for example api.i2rest.com:4321)"}
   },
...

i2Rest Gate is the endpoint where the server listens for incoming requests. The server uses up to three endpoints to process requests from clients, administrators/managers and sessions. Configuration file can contain up to three gate objects to setup these endpoints. If the configuration does not contain a setting for some gate, then the default setting is used - file: protocol at temporary location.
Detailed description of all available configuration options for gates is here

http

This is a common protocol, without encryption. You can use this protocol in a fully secure network environment. Example:

"gates":
   {
      ...
      "main": {"url":"http://192.168.1.123:5678", ...},
      ...
   },

https

To protect the connections, use the https protocol. i2Rest Server uses standard IBM i GSK API to protect connections. All required parameters are configured using DCM, see detailed guide. Example:

"gates":
   {
      ...
      "main": {"url":"https://192.168.1.123:5678", "dcm_server_id":"MYSERVER", ...},
      ...
   },

file

When your i2Rest Server instance and its clients both located on the same IBM i server, it is reasonable to use file: protocol. For example, you can use this protocol for management gate, to perform management functions using local i2Rest Client. i2Rest Server is able to listen incoming requests at some unix socket defined as a file at IFS. In this case, the server will not be accessible externally. i2Rest Server uses temporary file: endpoints when it can't find configuration for some gate. Temporary file: endpoints are created at /tmp folder, for example /tmp/AS5WRD7DCJ. Example:

"gates":
   {
      ...
      "session": {"url":"file:///tmp/session_gate", ...},
      ...
   },

i2Rest session system

...
   "session_systems":
   [
      {  "name"   : "*ANONYMOUS", 
         "submit" : "SBMJOB JOB(I2RESTA)                \
                            USER(${user})               \
                            CMD(CALL I2REST             \
                               PARM('-session'          \
                                    '-url' '${surl}'    \
                                    '-uid' '${uid}'     \
                                    '-user' '${user}')) \
                            INLLIBL(I2REST)"
      }
   ],
...

Session system is about submitting IBM i jobs that should process incoming requests. In our case I2Rest_anonymous_sessions

i2Rest PCML

  "pcmls":
  [
     {
        "pcml_mount"         : "echo",
        "pcml_file"          : "<complete name of i2restecho.pcml on IFS (for example /tmp/PCML/i2restecho.pcml)>", 
        "valid_in_anonymous" : true
     }
  ]

pcmls object is about I2Rest_API_Implementation I2Rest_PCML_syntax#openapi30_tag

SSL

The first thing we recommend to add to the basic server configuration is a https protocol connections protection. Please follow ssl guide.

Request authorization

Most of requests to i2Rest Sever require authorization. Such requests as IBM i command call, API call (except anonymous API call) and management api call will not be served without OAuth2 token with appropriate scope. There is a OAuth2 object, representing built-in authorization model. i2Rest built-in authorization model configuration options on example.

    "OAuth2":
  {
     "scopes": {"management_functions" : {"description":"i2Rest management APIs call"},
                "run_program"          : {"description":"Run *PGM and *SRVPGM"}, 
                "run_command"          : {"description":"Run CL command"}
  },
     "users":
     {
        "USRX":{"description":"John Johnes","valid_clients":{"TSTCLNT":{"scopes":["management_functions"]}}}
     },
     "clients":
     {
        "TSTCLNT":{"redirect_uri":"<main gate URL>/oauth2/redirect", 
                   "description":"Test client", 
                   "valid_scopes":["management_functions"],
                   "valid_grant_types":["authorization_code"]}
     },
     "tokens": {"type":"token"},"codes":{"type":"code"}
  } 

The snippet above shows us In general worlds i2Rest authorization model is something like WHAT is allowed and to WHOM, and HOW it realized. WHAT parameters - are the "scopes", HOW parameters - "tokens", WHOM parameters - "users" and "clients" (built-in authorization model implies that both "users" and "clients" has to be registered as an IBM i users). So we can see that user USRX using client TSTCLNT is allowed to do some actions within "managment_functions" scope. And these are exactly the settings of Oauth2 object that we need to perform a Мanagement api call.

Мanagement API call

So, what you have to do before we can test Мanagement API call to i2Rest Server:

a) Register two users on IBM i - one for a "сlient" parameter and one for a "user" parameter.
b) Fill the OAuth2 object template above with IBM i users values. Then add the snippet to your basic server configuration(with or without ssl protection) and put your new *.json anywhere on IBM i IFS.
c) Restart server to apply your new configuration *.json.

Now let's test the configuration obtaining Oauth2 token with SoapUI, and than proceed to Management api authorized call.

run_program API call

Unlike anonimous API call we performed in our basic guide, authorized API call requires Oauth2 token with "run_program" scope and *local Session System defined. So that's how we will change your basic server configuration (with or without ssl protection) to perform authorized run_program API call:

a) Add the snippet bellow to the session systems object:
{
      "name": "*LOCAL",
      "submit": SBMJOB JOB(I2RESTS) USER(${user})
                   CMD(CALL I2REST PARM(
                      '-session'
                      '-url' '${surl}'
                      '-uid' '${uid}'
                      '-user' '${user}'
                      '-init' 'ADDLIBLE I2REST'))
                      '-dcm_client_id' 'MYCLIENT'))"
},
b) Register two users on IBM i - one for a "сlient" parameter and one for a "user" parameter.
c) Fill the OAuth2 object template above with IBM i users values and add to your *.json.
d) Add the "run_program" scope to scopes object.
e) Change the pscms object as follows:
   "pcmls":
   [
      {
         "pcml_mount"         : "echo",
         "pcml_file"          : "<complete name of i2restecho.pcml on IFS (for example /tmp/PCML/i2restecho.pcml)>", 
         "valid_in_anonymous" : false
      }
   ]
f) Restart server to apply your new configuration *.json.

Now you can update your SoapUI ECHO test project with Authorization profile and perform your authorized API call.