0

我正在我的 Web API 项目中实现基于令牌的身份验证。以下是我用来验证令牌的代码。尽管我的令牌是有效的,但我收到的响应是“此请求的授权已被拒绝”,我不知道它来自哪里!

 public override void OnAuthorization(HttpActionContext actionContext)
        {
            base.OnAuthorization(actionContext);
            try
            {
                //Try to read the token from header.
                if (actionContext.Request.Headers.Contains("Authorization"))
                {
                    authenticationToken = actionContext.Request.Headers.GetValues("Authorization").FirstOrDefault();
                    if (!String.IsNullOrEmpty(authenticationToken))
                    {
                        //Remove "Bearer" from token. Doing case insensitive replacement.
                        Regex regex = new Regex("Bearer", RegexOptions.IgnoreCase);
                        authenticationToken = regex.Replace(authenticationToken, "");

                        //Remove colon from token
                        authenticationToken = authenticationToken.Replace(":", "");

                        //Now that we have a clean token, let's validate it.
                        if (!Managers.TokenManager.ValidateToken(authenticationToken.Trim()))
                        {
                            actionContext.Response = new HttpResponseMessage(HttpStatusCode.Unauthorized);
                            return;
                        }
                        return;
                    }
                }
                else
                {
                    actionContext.Response.Headers.Add("WWW-Authenticate", string.Format("Bearer realm={0}", Realm));
                    actionContext.Response = new HttpResponseMessage(HttpStatusCode.Forbidden);
                    return;
                }
            }
            catch (Exception)
            {
                actionContext.Response = new HttpResponseMessage(HttpStatusCode.Forbidden);
                return;
            }
        }

我在这里想念什么?

4

0 回答 0