Replies: 3 comments 3 replies
-
I tried the default Authentication boilerplate: Program.cs
Tool.cs [McpServerTool, Description("It prints Hello World!")]
[Authorize]
public static string HelloWorld() => "Hello World!"; but it doesnt work, I think the authentication framework is not yet supported |
Beta Was this translation helpful? Give feedback.
3 replies
-
I think
|
Beta Was this translation helpful? Give feedback.
0 replies
-
I figure it out using Microsoft.AspNetCore.Http;
namespace Company.Product.Mcp.Server.Authentication;
public class AuthorizationMiddleware
{
private readonly RequestDelegate _next;
public AuthorizationMiddleware(RequestDelegate next)
{
_next = next;
}
public async Task InvokeAsync(HttpContext context)
{
string token = GetToken(context);
if (!ValidateToken(token))
{
context.Response.StatusCode = StatusCodes.Status401Unauthorized;
await context.Response.WriteAsync("Invalid or missing token.");
return;
}
await _next(context); // Token is present, continue
}
private string GetToken(HttpContext context)
{
if (!context.Request.Headers.TryGetValue("Authorization", out var tokenValue))
{
return null;
}
var token = tokenValue.ToString();
// TODO: Remove this.. MCP Inspector v0.14.3 does not have options to send tokens without "Bearer " prefix:
// https://github.com/modelcontextprotocol/inspector/issues/249
// I use it as a workaround to be able to test the MCP server with the Inspector.
token = token.Replace("Bearer ", string.Empty, StringComparison.OrdinalIgnoreCase);
return token;
}
private bool ValidateToken(string token)
{
// TODO Logic to validate the token
return false;
}
} app.UseMiddleware<AuthorizationMiddleware>(); |
Beta Was this translation helpful? Give feedback.
0 replies
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Uh oh!
There was an error while loading. Please reload this page.
-
Pre-submission Checklist
Question Category
Your Question
How can we add Authentication And Authorization in MCP, just like we add in our API, this make our api authorize and give us the identity of user, how can we do same thing with MCP in dotnet
Beta Was this translation helpful? Give feedback.
All reactions