如何在.NET中抛出401 Unauthorized Exception(JWT Validate Token)?

时间:2017-09-25 15:25:11

标签: c# .net exception-handling jwt

我有一个.NET 4.5 API应用程序。它受到OWIN / Oauth的保护。我用POSTMAN打电话并伪造Bearer令牌,所以我可以测试这个案例。 如何在validateToken函数发现JWT令牌被操作/无效后中断代码执行?

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的构造函数,我通过postman调用,后者受[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;
           }
       }
    }

1 个答案:

答案 0 :(得分:0)

我发现了:

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;
        }
   }
}

我的代码之前缺少两件重要的事情:

  1. 抛出时新的HttpResponseMessage对象
  2. HttpResponseException的额外catch块