c# OpenIdConnect authentication



我正在尝试使用keyclock保护API。API由服务器调用。所以没有浏览器

(通过浏览器登录可以正常访问api)

当我尝试通过curl或Postman调用API时,我被重定向到keycloak的登录站点(就像在浏览器中一样)。无论我是否给予访问承载令牌,都会发生这种情况。

为什么我不能访问?令牌应该以某种方式跳过登录…

这些是我使用的curl命令:

export TOKEN=$(curl -k -H "Content-Type: application/x-www-form-urlencoded" 
-d "client_id=test" 
-d "username=test@test.de" 
-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

是API所在的代码:

.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; 
});

API的工作是验证访问令牌,并且没有浏览器重定向。所以你的代码应该是这样的:


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

您正在使用导致重定向的网站技术堆栈。当使用上述API技术栈时,如果您发送无效令牌,您将获得401错误响应,而不是重定向响应。

最新更新