I am trying to do basic authentication using attribute mapping (AuthorizationFilterAttribute) using technique shown 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);
}
I am using this attribute on my 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
Even though I am setting the CurrentPrincipal to genericPrincipal object and getting IsAuthenticated property as true:
var genericPrincipal = new GenericPrincipal(identity, null);
Thread.CurrentPrincipal = genericPrincipal;
and using it in my Controller to check IsAuthenticated property which is coming as false
if (System.Threading.Thread.CurrentPrincipal != null && System.Threading.Thread.CurrentPrincipal.Identity.IsAuthenticated)
Why I am getting IsAuthenticated property false in my controller, when I am getting it true in attribute class.
Please guide, what I am doing wrong.
Thank you.
I got the same issue before and i solved this by using HttpContext.Current.User instead of System.Threading.Thread.CurrentPrincipal.
Below is the sample code:
var genericPrincipal = new GenericPrincipal(identity, null);
HttpContext.Current.User = genericPrincipal;
In your controller:
if (HttpContext.Current.User != null && HttpContext.Current.User.Identity.IsAuthenticated)
Hopefully this answer helps you.
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.