使用KeycloakOwinAuthentication授权asp.net web api 2服务

时间:2018-04-25 15:38:10

标签: c# asp.net-web-api2 jwt keycloak

我想使用这个未维护的project来授权我的网络API的服务,因为我们必须使用Keycloak。

很容易遵循这个tutorial并使其在我的web api中工作,但我找不到使用令牌而不是交互式登录的任何示例。 web api将使用http请求接收我们已登录客户端的授权标头,目标是使服务安全并根据某些角色对其进行授权。

我在Startup.cs中执行了一些更改 - 配置方法:

ConfigureAuth(app);
app.UseKeycloakAuthentication(new KeycloakAuthenticationOptions
        {
            // App-Specific Settings
            ClientId = "demo-app", // *Required*
            ClientSecret = "ssshhhh", // If using public authentication, delete this line
            VirtualDirectory = "", // Set this if you use a virtual directory when deploying to IIS

            // Instance-Specific Settings
            Realm = "PruebaRealm", // Don't change this unless told to do so
            KeycloakUrl = "http://example.com/auth", // Enter your Keycloak URL here

            // Template-Specific Settings
            EnableWebApiMode = true,
            AuthenticationType = "KeycloakOwinAuthenticationSample_keycloak_auth", // Unique identifier for the auth middleware
        }); 

我已将授权属性添加到htttp方法:

[Authorize]
public IHttpActionResult Get()
{    
    PrivilegeProvider pPrivileges = new PrivilegeProvider();
    var searchResults = pPrivileges.GetPrivilege();
    if (searchResults == null)
        return NotFound();
    return Ok(searchResults);
    }

当我执行包含授权标题的请求时

Accept: application/json, text/plain, */*
Accept-Encoding: gzip, deflate, br
Accept-Language: es-ES,es;q=0.9
Authorization: bearer thisisanexamplethisisanexamplethisisanexample....
Cache-Control: no-cache
Connection: keep-alive
Host: localhost:49729
Origin: http://localhost:4200
Pragma: no-cache
Referer: http://localhost:4200/privilegios
User-Agent: Mozilla/5.0 (Windows NT 6.1; Win64; x64) AppleWebKit/537.36 
(KHTML, like Gecko) Chrome/66.0.3359.117 Safari/537.36

我总是收到:

Access Unauthorized: Requires valid bearer token authorization header

有人可以给我一个建议来实现这个目标吗? 我正在考虑使用owin创建自己的适配器。

提前致谢。

0 个答案:

没有答案