在Skype For Business Online上自动刷新UCWA令牌

时间:2017-02-28 09:37:12

标签: skype-for-business ucwa

我使用UCWA和密码令牌开发了一个应用程序。我正在阅读使用事件通过应用程序验证的用户的所有消息,但令牌不会持续很长时间并且续订正在使用浏览器,这对于自动化非常糟糕。

有没有办法获得一个不需要通过浏览器续订的令牌,这样我可以让我的应用程序完全自动化?我已经阅读了Github和ucwa网站上的所有文档。

这是我获取令牌的请求。

获取登录网址

def get_signin_url(redirect_uri,client_id,tenant,resource):     xframe,user_discovery_uri,resource = do_autodiscover(config [' domain'])

# Build the query parameters for the signin url
params = {
  'client_id': client_id,
  'redirect_uri': redirect_uri,
  'response_type': 'token',
  'response_mode': 'form_post',
  'resource': resource
}

# The authorize URL that initiates the OAuth2 client credential flow for admin consent
authorize_url = '{0}{1}'.format(authority, '/%s/oauth2/authorize?{0}' % tenant)

# Format the sign-in url for redirection
signin_url = authorize_url.format(urlencode(params))

return signin_url

完成几个步骤后,获取令牌:

def get_token_from_code(client_id, tenant, auth_code, redirect_uri, resource, client_secret):

  # Build the post form for the token request
  post_data = {
    'grant_type': 'authorization_code',
    'code': auth_code,
    'redirect_uri': redirect_uri,
    'resource': resource,
    'client_id': client_id,
    'client_secret': client_secret
  }

  # The token issuing endpoint
  token_url = '{0}{1}'.format(authority, '/{0}/oauth2/token'.format(tenant))

  # Perform the post to get access token
  response = requests.post(token_url, data=post_data)

  try:
    # try to parse the returned JSON for an access token
    access_token = response.json()['id_token']
    return access_token
  except:
    raise Exception('Error retrieving token: {0} - {1}'.format(
      response.status_code, response.text))

谢谢!

1 个答案:

答案 0 :(得分:1)

虽然文档说由于某种原因需要隐式流,但实际上Skype for Business Online与普通的authorization_token + refresh_token方法完美配合。

我认为他们还没有记录下来。由于此方法适用于所有其他Office365 API,因此它不太可能被删除。

因此,在您授权用户一次之后,您需要这样做 - 完全按照您的代码进行:

POST https://login.microsoftonline.com/common/oauth2/token
{
  grant_type: "authorization_code",
  code: authorization_code,
  redirect_uri: redirect_uri,
  client_id: client_id,
  client_secret: client_secret
}

然后从响应中获得access_token AND refresh_token 。 refresh_token应保存在某处(例如在数据库中)供以后使用。

现在,您使用access_token,但在某些时候您会收到403,现在您可以使用之前保存的refresh_token刷新它:

POST https://login.microsoftonline.com/common/oauth2/token
{
    refresh_token: refresh_token,
    grant_type: "refresh_token",
    redirect_uri: redirect_uri,
    client_id: client_id,
    client_secret: client_secret
}

经验表明,即使自access_token过期以来已经过了很长时间,也可以执行刷新令牌请求。

我在几个使用Office 365 API的应用程序中使用此方法,包括与Skype for Business交互的应用程序,并且到目前为止没有任何问题。

就官方文档而言,许多子系统都记录了refresh_token(在撰写本文时不适用于Skype for Business),并且它的工作方式几乎相同。例如,这里是Azure AD的此类文档:

相关问题