'c# OpenIdConnect authentication

I'm trying to secure an API with keycloack. The API is called by a server. So there is no browser.

(Logging in via Browser works fine and i can access the api.)

When I try to call the API via curl or Postman, I get redirected to the login site of keycloak (just like in the browser). This happens regardless of me giving an Access Bearer Token.

Why can I not get access? The token is what should skip the login somehow...

These are the curl cmds I use:

export TOKEN=$(curl -k -H "Content-Type: application/x-www-form-urlencoded" \
  -d "client_id=test" \
  -d "[email protected]" \
  -d "password=123456" \
  -d "grant_type=password" \
  -d "client_secret=fefaefaefaseeas" \
  -X POST https://XXXXX/protocol/openid-connect/token | jq -r .access_token)

echo $TOKEN

curl -i -k -X GET -H "Authorization: Bearer $TOKEN" https://localhost:5001/api-test

This is the code where the API is:

.AddOpenIdConnect("oidc", options =>
 {
     options.Authority = "https://xxxxx/auth/realms/master";
     options.ClientId = "test";

     // For testing we disable https (should be true for production)
     options.RequireHttpsMetadata = false;
     options.SaveTokens = true;
                    
     // Client secret shared with Keycloak
     options.ClientSecret = "fefaefaefaseeas";
     options.GetClaimsFromUserInfoEndpoint = true;

     // OpenID flow to use
     options.ResponseType = OpenIdConnectResponseType.Code; 
});


Solution 1:[1]

An API's job is to validate access tokens, and there are no browser redirects. So your code should look like this:


services
.AddAuthentication(JwtBearerDefaults.AuthenticationScheme)
.AddJwtBearer(options =>
{
    options.Authority = oidcMetadataEndpoint;
    options.TokenValidationParameters = new 
    TokenValidationParameters
    {
        ValidateIssuer = true,
        ValidIssuer = "myissuer",
        ValidateAudience = true,
        ValudAudience = "api.mycompany.com",
    };
});

You are using the website tech stack which is causing the redirects. When using the above API tech stack, you will get a 401 error response if you send in an invalid token, rather than a redirect response.

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1