You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

C# MVC API控制器:如何实现URL中的令牌认证?

Great question! Let's walk through how to implement URL-embedded token authentication just like the Telegram Bot API—including controller setup, token validation, and custom error responses for invalid or missing tokens.

URL-Embedded Token Authentication Implementation

1. Route Design & Token Extraction

First, you'll need to define a route pattern that captures the token directly from the URL (like api.mysite.com/{token}/action). The exact setup depends on your backend framework, but the core idea is consistent: define a placeholder in your route to grab the token, then extract it for validation.

Here are examples for common frameworks:

Example 1: Spring Boot (Java)

Configure your controller to accept the token as a path variable:

@RestController
@RequestMapping("/{token}")
public class ApiController {

    @GetMapping("/action")
    public ResponseEntity<?> handleAction(@PathVariable String token) {
        // Validate the token first
        if (!isValidToken(token)) {
            return ResponseEntity.status(HttpStatus.UNAUTHORIZED)
                .body("Custom unauthorized response: Invalid or missing token");
        }
        // Proceed with your business logic if token is valid
        return ResponseEntity.ok("Action processed successfully");
    }

    private boolean isValidToken(String token) {
        // Implement your validation logic here:
        // - Check against stored valid tokens in a database
        // - Verify JWT signature (if using JWT tokens)
        // - Check token expiration
        return "VALID_BOT_TOKEN".equals(token);
    }
}

Example 2: Express.js (Node.js)

Use Express route parameters to capture the token:

const express = require('express');
const app = express();

app.get('/:token/action', (req, res) => {
    const token = req.params.token;
    
    if (!isValidToken(token)) {
        return res.status(401).send("Custom unauthorized response: Invalid or missing token");
    }
    
    // Run your action logic here
    res.send("Action processed successfully");
});

function isValidToken(token) {
    // Add your token validation logic (e.g., check against a database)
    return token === 'VALID_BOT_TOKEN';
}

app.listen(3000);

2. Token Validation Logic

No matter which framework you use, these validation steps are critical:

  • Check for token presence: If a request hits api.mysite.com/action (without the token segment), immediately return an unauthorized response.
  • Validate token authenticity: Match the token against your stored valid tokens, verify signatures (for JWT), or check expiration dates.
  • Security note: Tokens in URLs get logged in server logs, browser history, and proxy logs. This approach works best for non-user-specific tokens (like Telegram Bot tokens) — avoid using it for sensitive user credentials. If you must use it, opt for short-lived tokens.

To avoid repeating validation code in every controller method, use a global interceptor/middleware to handle token checks across all relevant routes:

Example: Spring Boot Global Interceptor

@Component
public class TokenAuthInterceptor implements HandlerInterceptor {

    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        // Extract token from the first segment of the URL path
        String[] pathSegments = request.getRequestURI().split("/");
        String token = pathSegments.length > 1 ? pathSegments[1] : null;
        
        if (token == null || !isValidToken(token)) {
            response.setStatus(HttpStatus.UNAUTHORIZED.value());
            response.getWriter().write("Custom unauthorized response: Invalid or missing token");
            return false; // Block the request from reaching the controller
        }
        return true; // Allow valid requests to proceed
    }

    private boolean isValidToken(String token) {
        // Reuse your validation logic here
        return "VALID_BOT_TOKEN".equals(token);
    }
}

Register this interceptor to apply it to all routes matching /{token}/** — this way, every request with a token in the URL gets validated upfront.

4. Key Considerations

  • Avoid route conflicts: Ensure your token-inclusive routes don't clash with other API endpoints that don't require tokens.
  • URL-safe tokens: Make sure your tokens don't contain characters like / that would break URL parsing. Use URL-safe encoding if needed.
  • Alternatives for sensitive data: For user-specific authentication, prefer Authorization request headers (e.g., Bearer {token}) over URL-embedded tokens — they're more secure.

内容的提问来源于stack exchange,提问作者jeffffc

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.05.15 08:52:00