Skip to content

Commit 2885da5

Browse files
authored
Users/axsuarez/teams sample revision (#81)
* Teams sample updates * Teams sample updates * Teams sample updates
1 parent 97ffc42 commit 2885da5

6 files changed

Lines changed: 55 additions & 51 deletions

File tree

libraries/microsoft-agents-authentication-msal/microsoft/agents/authentication/msal/msal_auth.py

Lines changed: 11 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -80,9 +80,18 @@ async def aquire_token_on_behalf_of(
8080
)
8181
elif isinstance(msal_auth_client, ConfidentialClientApplication):
8282
# TODO: Handling token error / acquisition failed
83-
return msal_auth_client.acquire_token_on_behalf_of(
83+
84+
token = msal_auth_client.acquire_token_on_behalf_of(
8485
user_assertion=user_assertion, scopes=scopes
85-
)["access_token"]
86+
)
87+
88+
if "access_token" not in token:
89+
logger.error(
90+
f"Failed to acquire token on behalf of user: {user_assertion}"
91+
)
92+
raise ValueError(f"Failed to acquire token. {str(token)}")
93+
94+
return token["access_token"]
8695

8796
logger.error(
8897
f"On-behalf-of flow is not supported with the current authentication type: {msal_auth_client.__class__.__name__}"

test_samples/app_style/authorization_agent.py

Lines changed: 4 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -117,7 +117,10 @@ async def profile_request(context: TurnContext, state: TurnState) -> dict:
117117
return None
118118

119119
try:
120-
token_response = await AGENT_APP.auth.get_token(context, "GRAPH")
120+
# token_to_exchange = await AGENT_APP.auth.get_token(context, "GRAPH")
121+
token_response = await AGENT_APP.auth.exchange_token(
122+
context, scopes=["User.Read", "email"], auth_handler_id="GRAPH"
123+
)
121124
if not token_response or not token_response.token:
122125
await context.send_activity(
123126
MessageFactory.text(

test_samples/teams_agent/app.py

Lines changed: 11 additions & 31 deletions
Original file line numberDiff line numberDiff line change
@@ -2,51 +2,31 @@
22
# Licensed under the MIT License.
33

44
import pathlib
5+
from os import environ, path
56
from dotenv import load_dotenv
67
from aiohttp.web import Application, Request, Response, run_app
78

8-
from microsoft.agents.hosting.core import RestChannelServiceClientFactory
9-
from microsoft.agents.hosting.core.state import UserState
9+
from microsoft.agents.activity import load_configuration_from_env
10+
from microsoft.agents.authentication.msal import MsalConnectionManager
1011
from microsoft.agents.hosting.aiohttp import CloudAdapter, jwt_authorization_decorator
11-
from microsoft.agents.hosting.core.authorization import (
12-
Connections,
13-
AccessTokenProviderBase,
14-
ClaimsIdentity,
15-
)
16-
from microsoft.agents.authentication.msal import MsalAuth
17-
from microsoft.agents.hosting.core.storage import MemoryStorage
12+
from microsoft.agents.hosting.core import Authorization, MemoryStorage, UserState
1813

1914
from teams_handler import TeamsHandler
2015
from teams_sso import TeamsSso
2116
from teams_multi_feature import TeamsMultiFeature
2217
from config import DefaultConfig
2318

24-
load_dotenv()
19+
load_dotenv(path.join(path.dirname(__file__), ".env"))
2520

2621
CONFIG = DefaultConfig()
27-
AUTH_PROVIDER = MsalAuth(DefaultConfig())
2822

23+
agents_sdk_config = load_configuration_from_env(environ)
2924

30-
class DefaultConnection(Connections):
31-
def get_default_connection(self) -> AccessTokenProviderBase:
32-
pass
33-
34-
def get_token_provider(
35-
self, claims_identity: ClaimsIdentity, service_url: str
36-
) -> AccessTokenProviderBase:
37-
return AUTH_PROVIDER
38-
39-
def get_connection(self, connection_name: str) -> AccessTokenProviderBase:
40-
return AUTH_PROVIDER
41-
42-
43-
CHANNEL_CLIENT_FACTORY = RestChannelServiceClientFactory(CONFIG, DefaultConnection())
44-
45-
# Create adapter.
46-
ADAPTER = CloudAdapter(CHANNEL_CLIENT_FACTORY)
47-
48-
# Create the storage and user state (for SSO agent)
4925
STORAGE = MemoryStorage()
26+
CONNECTION_MANAGER = MsalConnectionManager(**agents_sdk_config)
27+
ADAPTER = CloudAdapter(connection_manager=CONNECTION_MANAGER)
28+
AUTHORIZATION = Authorization(STORAGE, CONNECTION_MANAGER, **agents_sdk_config)
29+
5030
USER_STATE = UserState(STORAGE)
5131

5232

@@ -55,7 +35,7 @@ def create_agent(agent_type: str):
5535
Create the appropriate agent based on configuration.
5636
"""
5737
if agent_type == "TeamsSso":
58-
return TeamsSso(USER_STATE, CONFIG.CONNECTION_NAME, CONFIG.CLIENT_ID)
38+
return TeamsSso(STORAGE, USER_STATE, CONFIG.CONNECTION_NAME, CONFIG.CLIENT_ID)
5939
elif agent_type == "TeamsMultiFeature":
6040
return TeamsMultiFeature()
6141
else: # Default to TeamsHandler

test_samples/teams_agent/config.py

Lines changed: 14 additions & 6 deletions
Original file line numberDiff line numberDiff line change
@@ -1,16 +1,24 @@
11
from os import environ
2-
from microsoft.agents.authentication.msal import AuthTypes, MsalAuthConfiguration
2+
from microsoft.agents.hosting.core import AuthTypes, AgentAuthConfiguration
33

44

5-
class DefaultConfig(MsalAuthConfiguration):
5+
class DefaultConfig(AgentAuthConfiguration):
66
"""Teams Agent Configuration"""
77

88
def __init__(self) -> None:
99
self.AUTH_TYPE = AuthTypes.client_secret
10-
self.TENANT_ID = "" or environ.get("TENANT_ID")
11-
self.CLIENT_ID = "" or environ.get("CLIENT_ID")
12-
self.CLIENT_SECRET = "" or environ.get("CLIENT_SECRET")
13-
self.CONNECTION_NAME = "" or environ.get("CONNECTION_NAME")
10+
self.TENANT_ID = "" or environ.get(
11+
"CONNECTIONS__SERVICE_CONNECTION__SETTINGS__TENANTID"
12+
)
13+
self.CLIENT_ID = "" or environ.get(
14+
"CONNECTIONS__SERVICE_CONNECTION__SETTINGS__CLIENTID"
15+
)
16+
self.CLIENT_SECRET = "" or environ.get(
17+
"CONNECTIONS__SERVICE_CONNECTION__SETTINGS__CLIENTSECRET"
18+
)
19+
self.CONNECTION_NAME = "" or environ.get(
20+
"AGENTAPPLICATION__USERAUTHORIZATION__HANDLERS__GRAPH__SETTINGS__AZUREBOTOAUTHCONNECTIONNAME"
21+
)
1422
self.AGENT_TYPE = environ.get(
1523
"AGENT_TYPE", "TeamsHandler"
1624
) # Default to TeamsHandler
Lines changed: 6 additions & 6 deletions
Original file line numberDiff line numberDiff line change
@@ -1,7 +1,7 @@
11
# Rename to .env
2-
TENANT_ID=
3-
CLIENT_ID=
4-
CLIENT_SECRET=
5-
AGENT_TYPE=TeamsSso
6-
BASE_URL=
7-
CONNECTION_NAME=
2+
CONNECTIONS__SERVICE_CONNECTION__SETTINGS__CLIENTID=client-id
3+
CONNECTIONS__SERVICE_CONNECTION__SETTINGS__CLIENTSECRET=client-secret
4+
CONNECTIONS__SERVICE_CONNECTION__SETTINGS__TENANTID=tenant-id
5+
6+
AGENTAPPLICATION__USERAUTHORIZATION__HANDLERS__GRAPH__SETTINGS__AZUREBOTOAUTHCONNECTIONNAME=connection-name
7+
AGENT_TYPE=TeamsSso

test_samples/teams_agent/teams_sso.py

Lines changed: 9 additions & 5 deletions
Original file line numberDiff line numberDiff line change
@@ -1,19 +1,23 @@
11
from microsoft.agents.hosting.core import (
2-
ActivityHandler,
32
OAuthFlow,
43
MessageFactory,
54
TurnContext,
5+
UserState,
6+
Storage,
67
)
7-
from microsoft.agents.hosting.core.state import UserState
88
from microsoft.agents.activity import ChannelAccount
9-
from microsoft.agents.hosting.teams import TeamsActivityHandler, TeamsInfo
9+
from microsoft.agents.hosting.teams import TeamsActivityHandler
1010

1111
from graph_client import GraphClient
1212

1313

1414
class TeamsSso(TeamsActivityHandler):
1515
def __init__(
16-
self, user_state: UserState, connection_name: str = None, app_id: str = None
16+
self,
17+
storage: Storage,
18+
user_state: UserState,
19+
connection_name: str = None,
20+
app_id: str = None,
1721
):
1822
"""
1923
Initializes a new instance of the TeamsSso class.
@@ -22,7 +26,7 @@ def __init__(
2226
:param app_id: AgentApplication ID.
2327
"""
2428
self.user_state = user_state
25-
self.oauth_flow = OAuthFlow(user_state, connection_name)
29+
self.oauth_flow = OAuthFlow(storage, connection_name)
2630

2731
async def on_sign_in_invoke(self, turn_context):
2832
# Log Event trigggered

0 commit comments

Comments
 (0)