Why is my ClaimsIdentity IsAuthenticated always false (for web api Authorize filter)?

后端 未结 2 1656
时光说笑
时光说笑 2020-12-01 01:41

In a Web API project I am overriding the normal authentication process to check tokens instead. The code looks something like this:



        
2条回答
  •  南方客
    南方客 (楼主)
    2020-12-01 02:24

    The problem is because of a breaking change in .Net 4.5. As explained by this article, simply constructing a claims identity no longer makes it IsAuthenticated return true. Instead, you need to pass some string (doesn't matter what) into the constructor.

    So this line in the above code:

    var claimsIdentity = new ClaimsIdentity( claims );
    

    Becomes this:

    // exact string doesn't matter
    var claimsIdentity = new ClaimsIdentity( claims, "CustomApiKeyAuth" );
    

    And the problem is solved. Update: see other answer from Leo. The exact AuthenticationType value may or may not be important depending on what else you have in your auth pipeline.

    Update 2: as suggested by Robin van der Knaap in the comments, one of the System.Security.Claims.AuthenticationTypes values might be appropriate.

    var claimsIdentity = new ClaimsIdentity( claims, AuthenticationTypes.Password );
    
    // and elsewhere in your application...
    if (User.Identity.AuthenticationType == AuthenticationTypes.Password) {
        // ...
    }
    

提交回复
热议问题