Securing Your Application
local graph
Chapter 11 — Securing Your Application
Section titled “Chapter 11 — Securing Your Application”In many cases, a prerequisite for a web application is to secure it before you put it in production. There are definitely cases where you don’t need to do that, but in most cases, you want to make sure that your application is secure and that only authorized users can access certain parts of it.
Let’s look at some scenarios and what security measures you should consider for each of them:
| Scenario | Sensitivity level | Security measures | Rationale |
|---|---|---|---|
| Public data that anyone can access | Minimal risk of exposure | Basic security or none | If you want to prevent bots or similar from using your API excessively, opt for having users sign up for an API key |
| Some public data and some protected data | Moderate risk of exposure | Basic security with HTTPS and API keys | Protect sensitive data while allowing public access to non-sensitive data |
| Sensitive personal data (e.g., health records and financial information) | High risk of exposure | Advanced security with HTTPS, OAuth 2.0/2.1, encryption, and RBAC | Comply with regulations such as General Data Protection Regulation (GDPR) and Health Insurance Portability and Accountability Act (HIPAA), and ensure data privacy and integrity |
Table 11.1 – Security measures scenarios
With that in mind, let’s look at some common security measures you can implement in your web application.
In this chapter, you will learn how to do the following:
- Add basic authentication to your application
- Secure your application with a JSON Web Token (JWT)
- Use OAuth2 to secure your application for an even better security posture
The chapter covers the following topics:
- Basic authentication
- Hardening security with JWT
- How does JWT work?
- Creating a JWT
- Integrating JWT in our middleware (and MCP server)
- OAuth2
Basic authentication
Section titled “Basic authentication”Basic authentication is the simplest way to secure your application. It involves sending a username and password with each request to the server. This is definitely not the most secure way to do it. If it’s not that secure, why would you use it? Well, there are scenarios where it’s better to have at least some security than no security at all. For example, if you have an API and it’s generally open to the public but you want to restrict access to certain endpoints, basic authentication can be a good option.
How does it work under the hood? The client sends an Authorization header with each request. The value of this header is the word Basic followed by a space and a Base64-encoded string of the format username:password. The server then decodes this string and checks whether the username and password are valid. Here’s the flow of how it works:

Figure 11.1 – Basic authentication flow
Figure 11.1 – Basic authentication flow
Sometimes the basic authentication consists of an API key instead of a username and password. The API key is sent in the same way as the username and password, but it’s just a single string that identifies the client. The server then checks whether the API key is valid.
From a code viewpoint, here’s what it can look like when the client sends a request with basic authentication:
# send api keyimport requestsimport base64api_key = 'your_api_key'encoded_api_key = base64.b64encode(api_key.encode()).decode()headers = {'Authorization': f'Basic {encoded_api_key}'}response = requests.get('https://api.example.com/endpoint', headers=headers)print(response.json())// send api keyconst apiKey = 'your_api_key';const encodedApiKey = btoa(apiKey);const headers = new Headers();headers.append('Authorization', \`Basic ${encodedApiKey}\`);fetch('https://api.example.com/endpoint', { headers }) .then(response => response.json()) .then(data => console.log(data));(1) to quickly copy code into your coding environment, or click the Explain button
(2) to get the AI assistant to explain a block of code to you.

A white background with a black text AI-generated content may be incorrect.
Using basic authentication for our MCP server
Section titled “Using basic authentication for our MCP server”Let’s leverage this technique to secure our MCP server. After all, we don’t want just anyone to be able to access our server and potentially misuse it. To get this to work, we need two things:
- A server middleware that checks for the
Authorizationheader and validates the credentials - The client that sends the
Authorizationheader with each request
Implementing the MCP server and bootstrapping it as a web app
Section titled “Implementing the MCP server and bootstrapping it as a web app”First things first, we need to implement the MCP server and bootstrap it as a web app. In doing so, we will have a web server that can handle MCP requests and responses. Once we’re done with this, we can add the middleware to the server that will add the security layer.
This uses Starlette; however, that server isn’t easy to get a hold of for your MCP server. So instead, you need to take control of the bootstrapping of the server and add the middleware yourself.
First, let’s create our MCP server instance:
app = FastMCP( name="MCP Resource Server", instructions="Resource Server that validates tokens via Authorization Server introspection", host=settings["host"], port=settings["port"], debug=True,)Second, let’s see how we can create the Starlette MCP app, which should use the Streamable HTTP transport:
starlette_app = app.streamable_http_app()Next, we need the bootstrap code that will run the server. This is done using Uvicorn:
async def run(starlette_app): import uvicorn config = uvicorn.Config( starlette_app, host=app.settings.host, port=app.settings.port, log_level=app.settings.log_level.lower(), ) server = uvicorn.Server(config) await server.serve()run(starlette_app)Creating the middleware
Section titled “Creating the middleware”To create our middleware, we need to remember how it should work. The middleware should check for the Authorization header, validate the credentials, and either allow the request to proceed or return an error response.
With that in mind, here’s what the middleware can look like. We need the middleware itself and a function to validate the token. Middleware in Starlette is created by subclassing BaseHTTPMiddleware. It has the request and a call_next function that you call to proceed with the request, should the validation be successful. If not, you should return a response with an error code:
def valid_token(token: str) -> bool: # remove the "Bearer " prefix if token.startswith("Bearer "): token = token[7:] return token == "secret-token" return Falseclass CustomHeaderMiddleware(BaseHTTPMiddleware): async def dispatch(self, request, call_next): has_header = request.headers.get("Authorization") if not has_header: print("-> Missing Authorization header!") return Response(status_code=401, content="Unauthorized") if not valid_token(has_header): print("-> Invalid token!") return Response(status_code=403, content="Forbidden") print("Valid token, proceeding...") print(f"-> Received {request.method} {request.url}") response = await call_next(request) response.headers['Custom'] = 'Example' return responseThe logic of the middleware is as follows:
- Check whether the
Authorizationheader is present. If not, return a401 Unauthorizedresponse. - Validate the token; if the token is invalid, return a
403 Forbiddenresponse. - If the token is valid, proceed with the request and add a custom header to the response. We proceed with the request by calling
call_next(request), which will pass the request to the next middleware or the actual endpoint handler.
The final part is to add the middleware to the Starlette app:
middleware = [ Middleware(CustomHeaderMiddleware, header_value='Customized')]async def main(): print("Running MCP Resource Server...") starlette_app = await setup(app) print("Adding custom middleware...") starlette_app.add_middleware(CustomHeaderMiddleware)In this code, we create a list of middleware and add CustomHeaderMiddleware to it. Then, in the main function, we add the middleware to the Starlette app using starlette_app.add_middleware(CustomHeaderMiddleware).
Testing the middleware
Section titled “Testing the middleware”To test the middleware, we can use the same client code as before, but this time, we need to include the Authorization header with a valid token.
Here’s how the client code can look:
import requestsimport base64def get_auth_token(): api_key = "my_api_key" token = base64.b64encode(api_key.encode()).decode() return f"Bearer {token}"headers = {'Authorization': get_auth_token()}response = requests.get('http://127.0.0.1:8000/protected', headers=headers)print(response.status_code)print(response.text)To test it with an MCP client, it’s the same idea, but we need to know how to pass custom headers with the MCP client. Here’s how you can do it.
Here, we use streamablehttp_client from the MCP SDK to create a client. We pass the Authorization header via the headers parameter:
token = "secret-token"async with streamablehttp_client( url = f"http://localhost:{port}/mcp", headers = {"Authorization": f"Bearer {token}"} ) as ( read_stream, write_stream, session_callback, ): async with ClientSession( read_stream, write_stream ) as session: await session.initialize()
# TODO, what you want done in the client, e.g list tools, call tools etc.Let’s look at JWT next.
Hardening security with JWT
Section titled “Hardening security with JWT”What’s the benefit of JWT rather than basic authentication? Well, with JWT, you can have more granular control over what the client can do. You can include claims in the token that specify what the client is allowed to do. For example, you can include a claim that specifies that the client is only allowed to read data, but not write data. This would look like something like this:
{ "sub": "1234567890", "name": "User Userson", "admin": true, "iat": 1516239022, "exp": 1516242622, "scopes": ["User.Read"]}This token payload specifies that the client is allowed to read user data. The server can then check the token and see whether the client has the required scope to perform the requested action. There are a lot of other benefits as well, such as the following:
- Stateless: The server doesn’t need to store any session information. The token contains all the information needed to authenticate the client.
- Scalability: Since the server doesn’t need to store any session information, it can easily scale horizontally.
- Security: The token can be signed and/or encrypted to ensure its integrity and confidentiality.
- Flexibility: The token can include any number of custom claims, allowing for a wide range of use cases.
- Interoperability: JWT is a widely adopted standard, making it easy to integrate with other systems and services.
Okay, all of that sounds great, but let’s take you through what you need to do to upgrade your basic authentication to JWT. First off, let’s talk about how JWT works.
How does JWT work?
Section titled “How does JWT work?”JWT is a compact, URL-safe means of representing claims to be transferred between two parties. The claims in a JWT are encoded as a JSON object. This JSON object has three parts separated by dots (.):
- Header: This typically consists of two parts: the type of the token (
JWT) and the signing algorithm being used, such as HMAC SHA256 or RSA. A header typically looks like this:{"alg": "HS256","typ": "JWT"}
Here we see that the algorithm used is HMAC SHA256, and the type is JWT. This information is important for the server to know how to verify the token.
- Payload: This contains the claims. Claims are statements about an entity (typically, the user) and additional data. There are three types of claims: registered, public, and private claims. A payload typically looks like this:
{"sub": "1234567890","name": "User Userson","admin": false,"iat": 1516239022,"exp": 1516242622,"scopes": ["User.Write", "User.Write"]}
This payload represents a user with an ID of 1234567890, the name User Userson, who is not an admin, and the User.Write and User.Read scopes. The iat claim represents the time the token was issued, and the exp claim represents the time the token expires.
- Signature: This is used to verify that the sender of the JWT is who it says it is and to ensure that the message wasn’t changed along the way.
Creating a JWT
Section titled “Creating a JWT”Okay, so we know what parts we have, but how do we create a JWT? Well, it’s actually quite simple. You can use a library to create the JWT for you. Here’s how you can do it:
# pip install PyJWTimport jwtimport datetimedef create_jwt(): header = { "alg": "HS256", "typ": "JWT" } payload = { "sub": "1234567890", # Subject (user ID) "name": "User Userson", # Custom claim "admin": True, # Custom claim "iat": datetime.datetime.utcnow(),# Issued at "exp": datetime.datetime.utcnow() + datetime.timedelta(hours=1), # Expiry "scopes": ["Admin.Write", "User.Read"] # Custom claim for scopes/permissions } secret = "your-256-bit-secret" token = jwt.encode(payload, secret, algorithm="HS256", headers=header) return tokenWith this code, you can create a JWT with a header, payload, and signature. The jwt.encode function takes care of encoding the header and payload, and signing the token with the secret. The signature is created as part of the jwt.encode function. Now, the token variable is in Base64-encoded format and can be used as a bearer token in the Authorization header. If you remove the Base64 encoding, you would see that the token consists of three parts separated by dots (.), namely, the header, payload, and signature, as mentioned previously. To decode the token, however, you would see the header and payload in JSON format.
Validating the JWT
Section titled “Validating the JWT”We also need to know how to validate the JWT. What we do when we validate is ensure that the token is valid, not expired, and that the signature is correct. That’s by no means all we can do, but it’s a good start. Here’s how you can validate a JWT:
import jwtdef validate_jwt(token: str) -> bool: secret = "your-256-bit-secret" try: decoded = jwt.decode(token, secret, algorithms=["HS256"]) print("Decoded claims:") for key, value in decoded.items(): print(f" {key}: {value}") return True except jwt.ExpiredSignatureError: print("Token has expired") return False except jwt.InvalidTokenError: print("Invalid token") return FalseThis code checks that the token is valid, not expired, and that the signature is correct. If the token is valid, it prints the decoded claims. If the token has expired or is invalid, it prints an error message.
We mentioned earlier that these structural checks are a good start. What other checks should we do? Here are some ideas of things you can check:
- The
iss(issuer) claim to ensure the token was issued by a trusted authority, for example, your auth server. - The
aud(audience) claim to ensure the token is intended for your application. Valid values could be your MCP server URL. - The
nbf(not before) claim to ensure the token is not used before a certain time. - Scopes or roles, to ensure the client has the required permissions to perform the requested action. Examples of scopes could be
User.Read,User.Write,Admin.Read, andAdmin.Write, and the roles could beUser,Admin, and so on. These look similar, but scopes are typically more granular than roles.
Integrating the JWT in our middleware (and MCP server)
Section titled “Integrating the JWT in our middleware (and MCP server)”So far, you’ve seen how we perform basic authentication and check whether a credential is valid as part of our middleware. Now, let’s see how we can integrate JWT validation. Our plan is as follows:
- Create a JWT for testing. We will do so with a utility script. In a real-world application, you would get the token from an identity provider (IDP) such as Auth0, Keycloak, or Entra ID.
- Update the middleware to validate the JWT.
- Update the client to send the JWT in the
Authorizationheader.
Creating a JWT for testing
Section titled “Creating a JWT for testing”Here’s the utility code we will use to create a JWT token for testing, including functions for generating a JWT and validating it:
import jwtimport datetimedef create_jwt(): header = { "alg": "HS256", "typ": "JWT" } payload = { "sub": "1234567890", # Subject (user ID) "name": "User Userson", # Custom claim "admin": True, # Custom claim "iat": datetime.datetime.utcnow(),# Issued at "exp": datetime.datetime.utcnow() + datetime.timedelta(hours=1), # Expiry "scopes": ["Admin.Write", "User.Read"] # Custom claim for scopes/permissions } token = jwt.encode(payload, "your-256-bit-secret", algorithm="HS256", headers=header) with open(".env", "w") as f: f.write(f"JWT_TOKEN={token}\n")def validate_jwt(token: str) -> str | None: secret = "your-256-bit-secret" try: decoded = jwt.decode(token, secret, algorithms=["HS256"])
return decoded except jwt.ExpiredSignatureError: print("Token has expired") return None except jwt.InvalidTokenError: print("Invalid token") return Noneif __name__ == "__main__": create_jwt()In this code, we create a JWT with a header, payload, and signature. The create_jwt function generates the token and writes it to a .env file. Note how the validate_jwt function validates the token and returns the decoded claims if the token is valid.
Updating the client to send the JWT
Section titled “Updating the client to send the JWT”Let’s move on to the client. It will need to load the token from the .env file and send it in the Authorization header. Here’s how you can do it:
import osfrom dotenv import load_dotenvload_dotenv()def get_auth_token(): token = os.getenv("JWT_TOKEN") return f"Bearer {token}"headers = {'Authorization': get_auth_token()}# omitted, creating and connecting the MCP clientUpdating the server middleware to validate the JWT
Section titled “Updating the server middleware to validate the JWT”Finally, we need to update the server middleware to validate the JWT. Here’s how we can do it:
from your_jwt_utility import validate_jwt # import the validate_jwt function\`\`\`pythonfrom starlette.middleware.base import BaseHTTPMiddlewarefrom starlette.responses import Responseclass JWTMiddleware(BaseHTTPMiddleware): async def dispatch(self, request, call_next): token = request.headers.get("Authorization") if not token or not token.startswith("Bearer "): return Response("Unauthorized", status_code=401) jwt_token = token.split(" ")[1] decoded = validate_jwt(jwt_token) if not decoded: return Response("Unauthorized", status_code=401) # TODO, check things like existing user, scopes etc. # Optionally attach user info to request.state request.state.user = decoded response = await call_next(request) return responseNow, the middleware checks for the Authorization header, validates the JWT, and either allows the request to proceed or returns a 401 Unauthorized response. We’re also leaving a TODO task for you to check things such as existing users, scopes, and so on.
OAuth2
Section titled “OAuth2”We’ve definitely improved our security posture by moving from basic authentication to JWT. However, there’s still room for improvement. OAuth2 is a widely adopted authorization framework that provides a more robust and flexible way to secure your application.
It allows you to delegate access to your resources without sharing credentials. What that means concretely is that there are three parties involved when accessing a resource:
- Resource server: This is the server that hosts the protected resources, in our case, the MCP server
- Client: This is the application that wants to access the protected resources, in our case, the MCP client
- Authorization server: This is the server that issues access tokens to the client after successfully authenticating the resource owner and obtaining authorization
What about the delegation part? Well, the resource owner (typically the user) can delegate access to the client by granting it an access token. The client can then use this access token to access the protected resources on behalf of the resource owner. This way, the client doesn’t need to know the resource owner’s credentials, and the resource owner can revoke access at any time by invalidating the access token. This is clearly a better approach than basic authentication. JWT, however, is often used to represent the access token in OAuth2. So the real improvement with OAuth2 is that it represents a complete framework for managing access tokens, including how they are issued, validated, and revoked.
OAuth2.1 code flow
Section titled “OAuth2.1 code flow”OAuth2.1 is what’s supported by the MCP SDK. Or rather, the way it’s supported is by providing a middleware that lets you point out the following:
- The authorization server: This is used to issue and validate tokens
- The resource server: This is where your data lives and is typically your MCP server
- The scopes you want to request: This is where you define what access you want to the resource server
Here’s what the flow looks like:

Figure 11.2 – OAuth2.1 flow
Figure 11.2 – OAuth2.1 flow
The preceding flow tells us that the client will first check whether it has a valid token. If it does, it will use it to access the resource server. If not, it will ask the user to authenticate and authorize the client to access the resource server on its behalf. Once the client has a valid token, it can use it to access the resource server.
So, what does the MCP SDK do for us then? It provides middleware that lets us easily integrate OAuth2.1 into our MCP server. All we need to do is provide the following configuration options:
auth=AuthSettings( issuer_url=AnyHttpUrl("https://auth.example.com"), # Authorization Server URL resource_server_url=AnyHttpUrl("http://localhost:3001"), # This server's URL required_scopes=["user"], )These are the fields of the middleware configuration:
issuer_url: This is the URL of the authorization server that issues the tokens. In a real-world application, this would be the URL of your IdP, such as Auth0, Keycloak, Entra ID, and so on.resource_server_url: This is the URL of the resource server, in our case, the MCP server. This is used to validate that the token is intended for this resource server.required_scopes: This is a list of scopes that the client must have to access the resource server.
This middleware takes care of validating the token, checking the scopes, and ensuring that the token is intended for the resource server. It also handles the OAuth2 flow, including redirecting the user to the authorization server to obtain an access token if needed.
OAuth 2.1 under the hood
Section titled “OAuth 2.1 under the hood”To understand how the OAuth2.1 middleware works under the hood, let’s explain the OAuth2.1 code flow in more detail. Here’s how the flow works:
- Validate token or obtain authorization code: The client checks whether it has a valid access token. If it does, it uses it to access the resource server. If not, it calls the
/authorizeendpoint on the authorization server to obtain an authorization code. This code is obtained when the client presents valid credentials and performs a login. The user is then redirected back to the client with the authorization code. - Call
/tokento exchange authorization code for access token: The client then calls the/tokenendpoint on the authorization server to exchange the authorization code for an access token. At this point, it’s ready to access the resource server. - Access resource server: Accessing the resource server is done by calling the desired endpoint and providing the access token in the
Authorizationheader as a bearer token. The resource server then validates the token, checks the scopes, and ensures that the token is intended for this resource server. If everything checks out, it allows the request to proceed.
Just to get a sense of roughly what code is involved, here’s a simplified version of the OAuth2.1 middleware flow:
# Step 1: Simulate browser redirect to /authorizeauthorize_url = f"{AUTH_SERVER}/authorize?client_id={CLIENT_ID} &redirect_uri={REDIRECT_URI}&state={STATE} &code_challenge={CODE_CHALLENGE}&code_challenge_method=plain"print(f"Requesting authorization: {authorize_url}")response = requests.get(authorize_url, allow_redirects=False)# Step 2: Extract authorization code from redirectredirect_location = response.headers.get("Location")if not redirect_location: print("Authorization server did not redirect. Is it running?") exit(1)parsed_url = urlparse(redirect_location)query_params = parse_qs(parsed_url.query)auth_code = query_params.get("code", [None])[0]print(f"Received authorization code: {auth_code}")# Step 3: Exchange code for access tokentoken_response = requests.post(f"{AUTH_SERVER}/token", data={ "grant_type": "authorization_code", "code": auth_code, "redirect_uri": REDIRECT_URI, "client_id": CLIENT_ID, "code_verifier": CODE_VERIFIER})token_data = token_response.json()access_token = token_data.get("access_token")print(f"Access token: {access_token}")# Step 4: Call resource serverresource_response = requests.get(f"{RESOURCE_SERVER}/userinfo", headers={ "Authorization": f"Bearer {access_token}"})print("User info response:")print(resource_response.json())Here’s the code explained:
- Step 1: The client constructs the authorization URL and makes a
GETrequest to the/authorizeendpoint on the authorization server. The user is redirected to this URL to authenticate and authorize the client. The response contains a redirect URL with an authorization code. - Step 2: The client extracts the authorization code from the redirect URL.
- Step 3: The client makes a
POSTrequest to the/tokenendpoint on the authorization server to exchange the authorization code for an access token. - Step 4: The client makes a
GETrequest to the resource server, providing the access token in theAuthorizationheader as a bearer token. The resource server validates the token and returns the requested resource if the token is valid.
The MCP SDK provides a sample implementation of OAuth2.1 (https://github.com/modelcontextprotocol/python-sdk/blob/main/examples/servers/simple-auth/mcp_simple_auth/auth_server.py) that you’re encouraged to check out.
Concluding thoughts on security with OAuth2.1
Section titled “Concluding thoughts on security with OAuth2.1”In a production scenario, the only code you would write yourself would be the client and the resource server. The authorization server would be a separate component/service, for example, handled via Entra ID if you’re using Azure, or Amazon Cognito if you’re on AWS. Auth0 is another good choice.
You need to decide what you are putting the authorization component in front of:
- The web server: If so, you can use standard web server middleware approaches with your chosen IdP, such as Entra ID, Amazon Cognito, Auth0, or similar.
- The MCP server: If choosing this, by all means, leverage auth components in the MCP SDK. You can still use standard middleware approaches here as well, but you will use the MCP SDK’s built-in authentication features.
- A gateway (a reverse proxy): A gateway is a service such as Azure API Management or Gateway from AWS. Both of these services are capable of handling authentication and can simplify the architecture. Additionally, these services have features you might want to use around AI usage, such as content safety and semantic caching, and also features that help with resiliency and scaling.
Also, when it comes to authorization per tool, you might need to add extra code checks for the call to a tool to ensure that the user has the right scopes/permissions to use that tool. Different tools might require different scopes/permissions. This is not something that’s supported out of the box in the MCP SDK, but it’s something you can easily add yourself. Something such as the following, where has_permission is a function you implement to check whether the user has the required permission to call the tool:
PermissionToolMapping = { "User.Read": ["GetUser", "ListUsers"], "User.Write": ["CreateUser", "UpdateUser", "DeleteUser"], "Admin.Read": ["GetAdmin", "ListAdmins"]}def has_permission(token: str, tool: str) -> bool: decoded = validate_jwt(token) if not decoded or "scopes" not in decoded: return False user_scopes = decoded["scopes"] required_scopes = [scope for scope, tools in PermissionToolMapping.items() if tool in tools] return any(scope in user_scopes for scope in required_scopes)@server.call_tool)def call_tool((name: str, arguments: dict[str, Any], request: types.CallToolRequest) -> types.CallToolResponse: if(has_permission(token=request.headers["token"], tool=name): # proceed with calling tool else: raise Exception)Summary
Section titled “Summary”In this chapter, you’ve learned about the importance of securing your MCP server and client. You’ve seen how to implement basic authentication, JWT, and OAuth2.1 to enhance the security of your applications. Remember that security is an ongoing process, and it’s essential to stay updated with the latest best practices and technologies to protect your applications and data. In our next and final chapter, we’ll explore how to bring your MCP server to production and ensure that it’s robust and scalable.
Assignment 1: Secure your MCP server with basic authentication
Section titled “Assignment 1: Secure your MCP server with basic authentication”In this assignment, you’re asked to implement basic authentication in your MCP server, which involves the creation of a middleware that checks for the Authorization header in incoming requests. The client should send the credentials in the Authorization header. This is a good first step to secure your MCP server, but remember that basic authentication has its limitations and should ideally be replaced with more secure methods.
Review the code snippets provided earlier in the section on basic authentication for guidance.
Solution 1
Section titled “Solution 1”You can access the solution at https://github.com/PacktPublishing/Learn-Model-Context-Protocol-with-Python/blob/main/Chapter11/code/basic/README.md.
Assignment 2: Secure your MCP server with JWT
Section titled “Assignment 2: Secure your MCP server with JWT”In this assignment, you’re asked to improve upon your previous assignment by implementing JWT authentication in your MCP server. Review the parts on JWT in this chapter for guidance.
Solution 2
Section titled “Solution 2”You can access the solution at https://github.com/PacktPublishing/Learn-Model-Context-Protocol-with-Python/blob/main/Chapter11/solutions/README.md.
What is the most secure approach out of the following?
- A: Basic authentication over HTTP
- B: JWT over HTTP
- C: OAuth 2.1
Which of the following best describes a scope in the context of authentication and authorization?
- A: The specific permissions or access rights that a client application is requesting from a resource server.
- B: A unique identifier for a user session
- C: A type of encryption algorithm used to secure tokens
You can access the solution at https://github.com/PacktPublishing/Learn-Model-Context-Protocol-with-Python/blob/main/Chapter11/solutions/solution-quiz.md.
Resources
Section titled “Resources”- The whole chapter in this free curriculum tells you about problems, attacks, and how to mitigate them: https://github.com/microsoft/mcp-for-beginners/tree/main/02-Security
- This lesson covers Entra ID security with MCP: https://github.com/microsoft/mcp-for-beginners/tree/main/05-AdvancedTopics/mcp-security-entra
- This repository shows solutions for working with Azure API Management and OAuth with GitHub: https://github.com/Azure-Samples/mcp-auth-servers/blob/main/README.md
- This chapter covers security best practices: https://github.com/microsoft/mcp-for-beginners/blob/main/05-AdvancedTopics/mcp-security/README.md