Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
Original file line number Diff line number Diff line change
Expand Up @@ -80,9 +80,18 @@ async def aquire_token_on_behalf_of(
)
elif isinstance(msal_auth_client, ConfidentialClientApplication):
# TODO: Handling token error / acquisition failed
return msal_auth_client.acquire_token_on_behalf_of(

token = msal_auth_client.acquire_token_on_behalf_of(
user_assertion=user_assertion, scopes=scopes
)["access_token"]
)

if "access_token" not in token:
logger.error(
f"Failed to acquire token on behalf of user: {user_assertion}"
)
raise ValueError(f"Failed to acquire token. {str(token)}")

return token["access_token"]

logger.error(
f"On-behalf-of flow is not supported with the current authentication type: {msal_auth_client.__class__.__name__}"
Expand Down
5 changes: 4 additions & 1 deletion test_samples/app_style/authorization_agent.py
Original file line number Diff line number Diff line change
Expand Up @@ -117,7 +117,10 @@ async def profile_request(context: TurnContext, state: TurnState) -> dict:
return None

try:
token_response = await AGENT_APP.auth.get_token(context, "GRAPH")
# token_to_exchange = await AGENT_APP.auth.get_token(context, "GRAPH")
token_response = await AGENT_APP.auth.exchange_token(
context, scopes=["User.Read", "email"], auth_handler_id="GRAPH"
)
if not token_response or not token_response.token:
await context.send_activity(
MessageFactory.text(
Expand Down
42 changes: 11 additions & 31 deletions test_samples/teams_agent/app.py
Original file line number Diff line number Diff line change
Expand Up @@ -2,51 +2,31 @@
# Licensed under the MIT License.

import pathlib
from os import environ, path
from dotenv import load_dotenv
from aiohttp.web import Application, Request, Response, run_app

from microsoft.agents.hosting.core import RestChannelServiceClientFactory
from microsoft.agents.hosting.core.state import UserState
from microsoft.agents.activity import load_configuration_from_env
from microsoft.agents.authentication.msal import MsalConnectionManager
from microsoft.agents.hosting.aiohttp import CloudAdapter, jwt_authorization_decorator
from microsoft.agents.hosting.core.authorization import (
Connections,
AccessTokenProviderBase,
ClaimsIdentity,
)
from microsoft.agents.authentication.msal import MsalAuth
from microsoft.agents.hosting.core.storage import MemoryStorage
from microsoft.agents.hosting.core import Authorization, MemoryStorage, UserState

from teams_handler import TeamsHandler
from teams_sso import TeamsSso
from teams_multi_feature import TeamsMultiFeature
from config import DefaultConfig

load_dotenv()
load_dotenv(path.join(path.dirname(__file__), ".env"))

CONFIG = DefaultConfig()
AUTH_PROVIDER = MsalAuth(DefaultConfig())

agents_sdk_config = load_configuration_from_env(environ)

class DefaultConnection(Connections):
def get_default_connection(self) -> AccessTokenProviderBase:
pass

def get_token_provider(
self, claims_identity: ClaimsIdentity, service_url: str
) -> AccessTokenProviderBase:
return AUTH_PROVIDER

def get_connection(self, connection_name: str) -> AccessTokenProviderBase:
return AUTH_PROVIDER


CHANNEL_CLIENT_FACTORY = RestChannelServiceClientFactory(CONFIG, DefaultConnection())

# Create adapter.
ADAPTER = CloudAdapter(CHANNEL_CLIENT_FACTORY)

# Create the storage and user state (for SSO agent)
STORAGE = MemoryStorage()
CONNECTION_MANAGER = MsalConnectionManager(**agents_sdk_config)
ADAPTER = CloudAdapter(connection_manager=CONNECTION_MANAGER)
AUTHORIZATION = Authorization(STORAGE, CONNECTION_MANAGER, **agents_sdk_config)

USER_STATE = UserState(STORAGE)


Expand All @@ -55,7 +35,7 @@ def create_agent(agent_type: str):
Create the appropriate agent based on configuration.
"""
if agent_type == "TeamsSso":
return TeamsSso(USER_STATE, CONFIG.CONNECTION_NAME, CONFIG.CLIENT_ID)
return TeamsSso(STORAGE, USER_STATE, CONFIG.CONNECTION_NAME, CONFIG.CLIENT_ID)
elif agent_type == "TeamsMultiFeature":
return TeamsMultiFeature()
else: # Default to TeamsHandler
Expand Down
20 changes: 14 additions & 6 deletions test_samples/teams_agent/config.py
Original file line number Diff line number Diff line change
@@ -1,16 +1,24 @@
from os import environ
from microsoft.agents.authentication.msal import AuthTypes, MsalAuthConfiguration
from microsoft.agents.hosting.core import AuthTypes, AgentAuthConfiguration


class DefaultConfig(MsalAuthConfiguration):
class DefaultConfig(AgentAuthConfiguration):
"""Teams Agent Configuration"""

def __init__(self) -> None:
self.AUTH_TYPE = AuthTypes.client_secret
self.TENANT_ID = "" or environ.get("TENANT_ID")
self.CLIENT_ID = "" or environ.get("CLIENT_ID")
self.CLIENT_SECRET = "" or environ.get("CLIENT_SECRET")
self.CONNECTION_NAME = "" or environ.get("CONNECTION_NAME")
self.TENANT_ID = "" or environ.get(
"CONNECTIONS__SERVICE_CONNECTION__SETTINGS__TENANTID"
)
self.CLIENT_ID = "" or environ.get(
"CONNECTIONS__SERVICE_CONNECTION__SETTINGS__CLIENTID"
)
self.CLIENT_SECRET = "" or environ.get(
"CONNECTIONS__SERVICE_CONNECTION__SETTINGS__CLIENTSECRET"
)
self.CONNECTION_NAME = "" or environ.get(
"AGENTAPPLICATION__USERAUTHORIZATION__HANDLERS__GRAPH__SETTINGS__AZUREBOTOAUTHCONNECTIONNAME"
)
self.AGENT_TYPE = environ.get(
"AGENT_TYPE", "TeamsHandler"
) # Default to TeamsHandler
Expand Down
12 changes: 6 additions & 6 deletions test_samples/teams_agent/env.TEMPLATE
Original file line number Diff line number Diff line change
@@ -1,7 +1,7 @@
# Rename to .env
TENANT_ID=
CLIENT_ID=
CLIENT_SECRET=
AGENT_TYPE=TeamsSso
BASE_URL=
CONNECTION_NAME=
CONNECTIONS__SERVICE_CONNECTION__SETTINGS__CLIENTID=client-id
CONNECTIONS__SERVICE_CONNECTION__SETTINGS__CLIENTSECRET=client-secret
CONNECTIONS__SERVICE_CONNECTION__SETTINGS__TENANTID=tenant-id
AGENTAPPLICATION__USERAUTHORIZATION__HANDLERS__GRAPH__SETTINGS__AZUREBOTOAUTHCONNECTIONNAME=connection-name
AGENT_TYPE=TeamsSso
14 changes: 9 additions & 5 deletions test_samples/teams_agent/teams_sso.py
Original file line number Diff line number Diff line change
@@ -1,19 +1,23 @@
from microsoft.agents.hosting.core import (
ActivityHandler,
OAuthFlow,
MessageFactory,
TurnContext,
UserState,
Storage,
)
from microsoft.agents.hosting.core.state import UserState
from microsoft.agents.activity import ChannelAccount
from microsoft.agents.hosting.teams import TeamsActivityHandler, TeamsInfo
from microsoft.agents.hosting.teams import TeamsActivityHandler

from graph_client import GraphClient


class TeamsSso(TeamsActivityHandler):
def __init__(
self, user_state: UserState, connection_name: str = None, app_id: str = None
self,
storage: Storage,
user_state: UserState,
connection_name: str = None,
app_id: str = None,
):
"""
Initializes a new instance of the TeamsSso class.
Expand All @@ -22,7 +26,7 @@ def __init__(
:param app_id: AgentApplication ID.
"""
self.user_state = user_state
self.oauth_flow = OAuthFlow(user_state, connection_name)
self.oauth_flow = OAuthFlow(storage, connection_name)

async def on_sign_in_invoke(self, turn_context):
# Log Event trigggered
Expand Down