认证模型(Authentication Providers)
认证模型的作用是确认用户的身份。用户通过经历登录流程来证明其身份。认证模型负责定义登录流程,并可以向用户询问所需的任意信息。这通常是用户名和密码,但也可能包含2FA(双因素)令牌或其他要求。
Authentication providers confirm the identity of users. The user proofs their identity by going through the login flow for an auth provider. The auth provider defines the login flow and can ask the user all information this needs. This will commonly be username and password but could also include a 2FA token or other challenges.
一旦认证模型确认了用户的身份,它将以凭证对象(Credentials)的形式将其传递给HA。
Once an authentication provider has confirmed the identity of a user, it will pass that on to Home Assistant in the form of a Credentials object.
定义1个认证模型(Defining an auth provider)
我们目前仅支持内置的认证模型。将来可能会支持自定义的认证模型。
We currently only support built-in auth providers. Support for custom auth providers might arrive in the future.
认证模型定义于homeassistant/auth_providers/<name of provider>.py
中。该模块需要提供一个AuthProvider
(认证模型)类和LoginFlow
(登录流程)类的实现,从而基于data_entry_flow
(数据输入流程),询问用户信息,并以此验证用户。
Auth providers are defined in homeassistant/auth/providers/<name of provider>.py
. The auth provider module will need to provide an implementation of the AuthProvider
class and LoginFlow
class, it is what asks user for information and validates it base on data_entry_flow
.
完整的认证模型的示例,请参阅insecure_example.py。
For an example of a fully implemented auth provider, please see insecure_example.py.
认证模型应当扩展以下AuthProvider
(认证模型)类的方法。
Auth providers shall extend the following methods of AuthProvider
class.
方法(method) |
必选(Required) |
描述(Description) |
async def async_login_flow(self) |
是 |
返回登录流程的实例,提供给用户来标识自己。 |
async def async_get_or_create_credentials(self, flow_result) |
是 |
给定登录流程的结果,返回凭证对象。可以是已有的也可以是全新的。 |
async def async_user_meta_for_credentials(credentials) |
否 |
名为Home Assistant的回调将以凭证对象创建用户,或为用户填充额外字段。 |
认证模型应当扩展以下的LoginFlow
(登录流程)类的方法。
Auth providers shall extend the following methods of LoginFlow
class.
方法(method) |
必选(Required) |
描述(Description) |
async def async_step_init(self, user_input=None) |
是 |
处理登录表单,详情见下. |
LoginFlow类的async_step_init方法
在不远的将来,我们将更换这个接口
We may change this inteface in near future.
LoginFlow
(登录流程)继承于data_entry_flow.FlowHandler
(数据输入流程的流程处理)。而数据输入流程的第一步是进行初始化硬编码init
,因此每个输入流程都必须有async_step_init
的这个实现方法。async_step_init
的格局(形式)类似于下列的pseudo-code伪代码:
LoginFlow
extends data_entry_flow.FlowHandler
. The first step of data entry flow is hard coded as init
, so each flow has to implement async_step_init
method. The pattern of async_step_init
likes following pseudo-code:
async def async_step_init(self, user_input=None):
return self.async_show_form(step_id='init', data_schema='some schema to construct ui form') if user_input is None
return self.async_show_form(step_id='init', errors) if user_input is invalid
return await self.async_finish(username) if user_input is valid