Search code examples
c#.net-coreasp.net-identityaccess-tokenopenid-connect

Access User.Identity and Claims from Outside


I am trying to build an SSO(.net core) service with OpenID Connect which will be a layer between a Webforms application and the Service Provider. I created some endpoints to check if user is authenticated and get user claims from the service. I am able to get correct results when I call these endpoints from my browser. However when I call them from the website(with HttpWebRequest). User.Identity is always empty. My endpoint to check if user authenticated, looks like this:

[HttpGet]
[Route("IsAuthenticated")]
public IActionResult IsAuthenticated()
{
    return Json(User.Identity.IsAuthenticated);
}

Or to get access token:

[HttpGet]
[Route("access_token")]
public async Task<IActionResult> AccessToken()
{
    var tokenResult = await HttpContext.GetTokenAsync("access_token");
    return Json(tokenResult);
}

My Startup ConfigureServices looks like this:

var OIDCConfiguration = new OIDCSettings()
{
    Authority = Configuration["OIDCSettings:Authority"],
    ClientId = Configuration["OIDCSettings:ClientId"],
    ClientSecret = Configuration["OIDCSettings:ClientSecret"],
    CallbackPath = Configuration["OIDCSettings:CallbackPath"],
    UserInfoEndpoint = Configuration["OIDCSettings:UserInfoEndpoint"]
};

services.AddAuthentication(options => {
    options.DefaultAuthenticateScheme = CookieAuthenticationDefaults.AuthenticationScheme;
    options.DefaultSignInScheme = CookieAuthenticationDefaults.AuthenticationScheme;
    options.DefaultChallengeScheme = "oidc";
})
.AddCookie(CookieAuthenticationDefaults.AuthenticationScheme)
.AddOpenIdConnect("oidc", options => {
    options.Authority = OIDCConfiguration.Authority;
    options.ClientId = OIDCConfiguration.ClientId;
    options.ClientSecret = OIDCConfiguration.ClientSecret;
    options.CallbackPath = new PathString(OIDCConfiguration.CallbackPath);
    options.ResponseType = OpenIdConnectResponseType.Code;
    options.GetClaimsFromUserInfoEndpoint = true;
    options.Scope.Add("openid emailAddress");
    options.AuthenticationMethod = OpenIdConnectRedirectBehavior.RedirectGet;
    options.SaveTokens = true;
});

And to start middleware I am using ChallengeResult object.

I am a beginner for OpenID Connect and Middleware architecture so I am not sure what I am missing or even if my architecture is correct.


Solution

  • So usually when you log in through your browser, ASP.NET Core administers a cookie with all the relevant information about your ClaimsPrincipal so that the server can identify you on subsequent requests to the website. What might be happening is that your server is not sending requests with the cookie that was administered post-authentication, hence why your requests could not be authenticated.