System.Threading.Thread.CurrentPrincipal未在AuthorizationFilterAttribute中设置

时间:2017-03-10 12:47:08

标签: c#

我正在尝试使用属性映射(AuthorizationFilterAttribute)使用显示的here

技术进行基本身份验证
public override void OnAuthorization(System.Web.Http.Controllers.HttpActionContext actionContext)
    {
        if (!_active)
            return;
        var identity = FetchHeader(actionContext);
        if (identity == null)
        {
            ChallengeAuthRequestFilter(actionContext);
            return;
        }
        var genericPrincipal = new GenericPrincipal(identity, null);
        Thread.CurrentPrincipal = genericPrincipal;
        var val = Thread.CurrentPrincipal.Identity.IsAuthenticated;

        if (!OnAuthorizeUser(identity.Name, identity.Password, actionContext))
        {
            ChallengeAuthRequestFilter(actionContext);
            return;
        }
        base.OnAuthorization(actionContext);
    }

我在Controller [AuthenticationController]

上使用此属性
[ApiAuthenticationFilter(true)] //This is the attribute class
    [RoutePrefix("api/Authentication")]
    public class AuthenticateController : ApiController
    {
        private ITokenService _tokenService;

        public AuthenticateController() { }
        public AuthenticateController(ITokenService tokenService)
        {
            _tokenService = tokenService;
        }

        // GET api/<controller>
        [Route("Login")]
        [HttpGet]
        public HttpResponseMessage Authenticate(User user)
        {
            if (System.Threading.Thread.CurrentPrincipal != null && System.Threading.Thread.CurrentPrincipal.Identity.IsAuthenticated)
            {
                BasicAuthenticationIdentity identity = Thread.CurrentPrincipal.Identity as BasicAuthenticationIdentity;
                if (identity != null)
                    return GenerateToken(identity.UserId);
            }
            return null;
        }

MyQuestion

即使我将CurrentPrincipal设置为genericPrincipal对象并将IsAuthenticated属性设置为true:

var genericPrincipal = new GenericPrincipal(identity, null);
Thread.CurrentPrincipal = genericPrincipal;

并在我的Controller中使用它来检查IsAuthenticated属性是否为false

if (System.Threading.Thread.CurrentPrincipal != null && System.Threading.Thread.CurrentPrincipal.Identity.IsAuthenticated)

为什么我在控制器中将IsAuthenticated属性设置为false,当我在属性类中将其设置为true时。

请指导,我做错了什么。

谢谢。

1 个答案:

答案 0 :(得分:0)

之前我遇到了同样的问题,我通过使用HttpContext.Current.User而不是System.Threading.Thread.CurrentPrincipal解决了这个问题。

以下是示例代码:

var genericPrincipal = new GenericPrincipal(identity, null);
HttpContext.Current.User = genericPrincipal;

在您的控制器中:

if (HttpContext.Current.User != null && HttpContext.Current.User.Identity.IsAuthenticated)

希望这个答案可以帮到你。