如何在 .NET(JWT 验证令牌)中抛出 401 未经授权的异常?

How to throw a 401 Unauthorized Exception in .NET (JWT Validate Token)?

我有一个 .NET 4.5 API 应用程序。它受 OWIN/Oauth 保护。我与 POSTMAN 通话并伪造 Bearer 令牌,因此我可以测试这种情况。 validateToken函数发现JWT token已经manipulated/is无效后如何打断代码执行?

ClaimsPrincipal principal = handler.ValidateToken(protectedText, _validationParameters, out validToken);

此行返回一个 SecurityTokenException。我抓住了这样的异常:

catch (SecurityTokenException ex)
{
     var msg = new HttpResponseMessage(HttpStatusCode.Unauthorized) { ReasonPhrase = "Access Token is manipulated" };
     throw new HttpResponseException(msg);
}

之后应用程序继续执行并进入我通过邮递员调用的 ApiController 的构造函数,它受 [Authorize] 保护,而不是给我一个带有 401 Unauthorized

的 HTTPResponse

P.S。这是 ApiController

中构造函数的代码
public class TicketController : ApiController
{
     private readonly TicketService _svcTicket;

     public TicketController()
     {
           try
           {
              _svcTicket = new TicketService(JwtFormat.AppContext);
           }
           catch (SecurityTokenException ex)
           {
                var msg = new HttpResponseMessage(HttpStatusCode.Unauthorized) { ReasonPhrase = "Access Token is manipulated" };
                    throw new HttpResponseException(msg);
           }
           catch (Exception ex)
           {
                throw ex;
           }
       }
    }

我发现了:

public class TicketController : ApiController
{
 private readonly TicketService _svcTicket;

 public TicketController()
 {
       try
       {
          if(tokenIsManipulated) {
                throw new HttpResponseException(new HttpResponseMessage(HttpStatusCode.Unauthorized)
                {
                    Content = new StringContent("Access Token is manipulated")
                });
          }
        }
        catch(HttpResponseException)
        {
            throw;
        }
   }
}

我的代码之前遗漏了 2 件重要的事情:

  1. 抛出时一个新的 HttpResponseMessage 对象
  2. HttpResponseException 的额外捕获块