本帖最后由 狮心哥哥 于 2018-8-29 16:40 编辑
Gist连接
暂时解决没有长期生效令牌的方案。适用0.77,至少需要创建一个用户。
执行以下脚本,注意修改配置文件目录。把输出的Bearer Token记录下来。
然后就可以使用这个Token进行API访问了。
import os
from datetime import timedelta
from homeassistant import auth, core, config as conf_util
CLIENT_ID = 'long_lived_client'
LIFE_TIME = timedelta(days=3650)
async def create_refresh_token(auth_mgr: auth.AuthManager,
owner: auth.models.User):
"""Create a refresh token for owner."""
refresh_token = auth.models.RefreshToken(
user=owner,
access_token_expiration=LIFE_TIME,
client_id=CLIENT_ID,
)
owner.refresh_tokens[refresh_token.id] = refresh_token
# hack code to save refresh_token
await auth_mgr._store._store.async_save(
auth_mgr._store._data_to_save())
print('Created a new refresh token for {}: {}'.format(
CLIENT_ID, refresh_token.id))
return refresh_token
async def get_long_live_access_token(auth_mgr: auth.AuthManager):
"""Create a bearer token for owner."""
owner = [u for u in await auth_mgr.async_get_users() if u.is_owner][0]
print('Owner name is {}\n'.format(owner.name))
refresh_token = None
for token in owner.refresh_tokens.values():
if token.client_id == CLIENT_ID:
refresh_token = token
break
if not refresh_token:
refresh_token = await create_refresh_token(auth_mgr, owner)
# get access_token, it won't saved
access_token = auth_mgr.async_create_access_token(refresh_token)
print('Add following HTTP header to your REST API'
' and Websocket API request:')
print('Authorization: Bearer {}'.format(access_token))
# change to your config path
config_dir = conf_util.get_default_config_dir()
config_path = conf_util.ensure_config_exists(config_dir)
print('Loading config from {}'.format(config_path))
config_dict = conf_util.load_yaml_config_file(config_path)
core_config = config_dict.get('homeassistant', {})
hass = core.HomeAssistant()
hass.config.config_dir = os.path.abspath(os.path.dirname(config_path))
hass.loop.run_until_complete(
conf_util.async_process_ha_core_config(
hass, core_config, False, False))
hass.loop.run_until_complete(
get_long_live_access_token(hass.auth))
复制代码