当前位置: 首页 > 知识库问答 >
问题:

Spring security密钥斗篷适配器承载配置

邴俊达
2023-03-14

我有java REST应用程序,我希望通过keycloak保护。我做了一些测试,应用程序与keycloak servlet过滤器配合良好,但我在Spring Security适配器方面遇到了问题。

钥匙斗篷。json(删除值)

{
  "realm": "",
  "realm-public-key": "",
  "bearer-only": true,
  "auth-server-url": "",
  "ssl-required": "external",
  "resource": ""
}

可见,我只需要承载授权,若请求包含有效令牌,那个么若不是http 401,那个么我希望是http 200。我使用了以下xml配置:

<security:global-method-security  jsr250-annotations="enabled"/>

    <security:authentication-manager alias="authenticationManager">
        <security:authentication-provider ref="keycloakAuthenticationProvider"/>
    </security:authentication-manager>


    <bean id="keycloakAuthenticationEntryPoint"
                class="org.keycloak.adapters.springsecurity.authentication.KeycloakAuthenticationEntryPoint">
            </bean>
    <bean id="keycloakAuthenticationProvider"
                class="org.keycloak.adapters.springsecurity.authentication.KeycloakAuthenticationProvider">
        <property name="grantedAuthoritiesMapper">
            <bean class="org.springframework.security.core.authority.mapping.SimpleAuthorityMapper">
                <property name="convertToUpperCase" value="true"/>
                <property name="prefix" value="ROLE_"/>
            </bean>

        </property>
    </bean>

    <bean id="keycloakPreAuthActionsFilter"
                class="org.keycloak.adapters.springsecurity.filter.KeycloakPreAuthActionsFilter"/>
    <bean id="keycloakAuthenticationProcessingFilter"
                class="org.keycloak.adapters.springsecurity.filter.KeycloakAuthenticationProcessingFilter">
        <constructor-arg name="authenticationManager" ref="authenticationManager"/>
    </bean>

    <bean id="adapterDeploymentContext" class="org.keycloak.adapters.springsecurity.AdapterDeploymentContextFactoryBean">
        <constructor-arg value="/WEB-INF/keycloak.json" />
    </bean>


    <security:http auto-config="false" entry-point-ref="keycloakAuthenticationEntryPoint" create-session="stateless">
        <security:custom-filter ref="keycloakPreAuthActionsFilter" before="LOGOUT_FILTER" />
        <security:custom-filter ref="keycloakAuthenticationProcessingFilter" before="FORM_LOGIN_FILTER"/>


        <security:intercept-url pattern="*" access="permitAll()" />
        <security:intercept-url pattern="/services/protected/*" access="isFullyAuthenticated()" />
        <security:csrf disabled="true"/>
    </security:http>

到底发生了什么?请求经过身份验证,但成功后我被重定向到“/”。然后我一次又一次地经过身份验证。日志:

11:18:36,492 DEBUG [org.springframework.security.web.FilterChainProxy] (http-0.0.0.0:8080-4) /services/protected/getAttributes at position 1 of 9 in additional filter chain; firing Filter: 'SecurityContextPersistenceFilter'
11:18:36,508 DEBUG [org.springframework.security.web.FilterChainProxy] (http-0.0.0.0:8080-4) /services/protected/getAttributes at position 2 of 9 in additional filter chain; firing Filter: 'WebAsyncManagerIntegrationFilter'
11:18:36,508 DEBUG [org.springframework.security.web.FilterChainProxy] (http-0.0.0.0:8080-4) /services/protected/getAttributes at position 3 of 9 in additional filter chain; firing Filter: 'HeaderWriterFilter'
11:18:36,508 DEBUG [org.springframework.security.web.FilterChainProxy] (http-0.0.0.0:8080-4) /services/protected/getAttributes at position 4 of 9 in additional filter chain; firing Filter: 'KeycloakPreAuthActionsFilter'
11:18:36,508 DEBUG [org.keycloak.adapters.PreAuthActionsHandler] (http-0.0.0.0:8080-4) adminRequest http://test.srv:8080/core2/services/protected/getAttributes
11:18:36,508 DEBUG [org.springframework.security.web.FilterChainProxy] (http-0.0.0.0:8080-4) /services/protected/getAttributes at position 5 of 9 in additional filter chain; firing Filter: 'KeycloakAuthenticationProcessingFilter'
11:18:36,508 DEBUG [org.springframework.security.web.util.matcher.OrRequestMatcher] (http-0.0.0.0:8080-4) Trying to match using Ant [pattern='/sso/login']
11:18:36,508 DEBUG [org.springframework.security.web.util.matcher.AntPathRequestMatcher] (http-0.0.0.0:8080-4) Checking match of request : '/services/protected/getAttributes'; against '/sso/login'
11:18:36,508 DEBUG [org.springframework.security.web.util.matcher.OrRequestMatcher] (http-0.0.0.0:8080-4) Trying to match using RequestHeaderRequestMatcher [expectedHeaderName=Authorization, expectedHeaderValue=null]
11:18:36,508 DEBUG [org.springframework.security.web.util.matcher.OrRequestMatcher] (http-0.0.0`enter code here`.0:8080-4) matched
11:18:36,508 DEBUG [org.keycloak.adapters.springsecurity.filter.KeycloakAuthenticationProcessingFilter] (http-0.0.0.0:8080-4) Request is to process authentication
11:18:36,508 DEBUG [org.keycloak.adapters.springsecurity.filter.KeycloakAuthenticationProcessingFilter] (http-0.0.0.0:8080-4) Attempting Keycloak authentication
11:18:36,555 DEBUG [org.keycloak.adapters.springsecurity.authentication.SpringSecurityRequestAuthenticator] (http-0.0.0.0:8080-4) Completing bearer authentication. Bearer roles: [uma_authorization] 
11:18:36,555 DEBUG [org.keycloak.adapters.RequestAuthenticator] (http-0.0.0.0:8080-4) User 'e9ae6919-c0f3-4dcb-96f6-82e3373932e9' invoking 'http://test.srv:8080/core2/services/protected/getAttributes' on client 'mak_test'
11:18:36,555 DEBUG [org.keycloak.adapters.RequestAuthenticator] (http-0.0.0.0:8080-4) Bearer AUTHENTICATED
11:18:36,555 DEBUG [org.keycloak.adapters.springsecurity.filter.KeycloakAuthenticationProcessingFilter] (http-0.0.0.0:8080-4) Auth outcome: AUTHENTICATED
11:18:36,555 DEBUG [org.springframework.security.authentication.ProviderManager] (http-0.0.0.0:8080-4) Authentication attempt using org.keycloak.adapters.springsecurity.authentication.KeycloakAuthenticationProvider
11:18:36,555 DEBUG [org.keycloak.adapters.springsecurity.filter.KeycloakAuthenticationProcessingFilter] (http-0.0.0.0:8080-4) Authentication success. Updating SecurityContextHolder to contain: org.keycloak.adapters.springsecurity.token.KeycloakAuthenticationToken@65776c48: Principal: e9ae6919-c0f3-4dcb-96f6-82e3373932e9; Credentials: [PROTECTED]; Authenticated: true; Details: org.keycloak.adapters.springsecurity.account.SimpleKeycloakAccount@44667d3a; Granted Authorities: ROLE_UMA_AUTHORIZATION
11:18:36,555 DEBUG [org.springframework.security.web.authentication.SavedRequestAwareAuthenticationSuccessHandler] (http-0.0.0.0:8080-4) Using default Url: /
11:18:36,555 DEBUG [org.springframework.security.web.DefaultRedirectStrategy] (http-0.0.0.0:8080-4) Redirecting to '/core2/'
11:18:36,555 DEBUG [org.springframework.security.web.header.writers.HstsHeaderWriter] (http-0.0.0.0:8080-4) Not injecting HSTS header since it did not match the requestMatcher org.springframework.security.web.header.writers.HstsHeaderWriter$SecureRequestMatcher@159e9b90
11:18:36,555 DEBUG [org.springframework.security.web.context.SecurityContextPersistenceFilter] (http-0.0.0.0:8080-4) SecurityContextHolder now cleared, as request processing completed
11:18:36,570 DEBUG [org.springframework.security.web.FilterChainProxy] (http-0.0.0.0:8080-4) / at position 1 of 9 in additional filter chain; firing Filter: 'SecurityContextPersistenceFilter'

我正在测试Junit的endpoit

@Test
    public void protectedTest() throws IOException {
        String token = getToken();
        long time1 = System.currentTimeMillis();
        String url =  server + "/services/protected/getAttributes";
        URL obj = new URL(url);
        HttpURLConnection con = (HttpURLConnection) obj.openConnection();
        con.setRequestMethod("GET");
        con.setRequestProperty("Authorization", token);
        Assert.assertEquals(200, con.getResponseCode());
        System.out.print(String.format("Authorized time: %s ms ", (System.currentTimeMillis() - time1)));
    }

endpoint代码:

@RestController
public class ProtectedService {

    @RequestMapping(value = "/services/protected/getAttributes",
            method = RequestMethod.GET,
            produces = {MediaType.APPLICATION_XML_VALUE, MediaType.APPLICATION_JSON_VALUE})
    @ResponseBody
    @RolesAllowed("ROLE_UMA_AUTHORIZATION")
    public GetCustAttrsRes getAttributes() {
        return new GetCustAttrsRes();
    }
}

密钥斗篷服务器版本:2.1.0。最终的

钥匙斗篷相关pom部分:

<dependency>
            <groupId>org.keycloak</groupId>
            <artifactId>keycloak-spring-security-adapter</artifactId>
            <version>2.2.1.Final</version>
        </dependency>
  <dependency>
            <groupId>org.springframework.security</groupId>
            <artifactId>spring-security-web</artifactId>
            <version>4.1.3.RELEASE</version>
        </dependency>
        <dependency>
            <groupId>org.springframework.security</groupId>
            <artifactId>spring-security-config</artifactId>
            <version>4.1.3.RELEASE</version>
        </dependency>

        <dependency>
            <groupId>org.springframework.security</groupId>
            <artifactId>spring-security-core</artifactId>
            <version>4.1.3.RELEASE</version>
        </dependency>

欢迎任何建议。

共有1个答案

杜俭
2023-03-14

问题解决了。我的测试代码出错了。方法getToken()返回“bearer”。这在KeyClope过滤器适配器中是可以接受的,但在Spring Security适配器中是不可以接受的。正确的方法是“承载器”,它在两个适配器中都有效。

 类似资料:
  • 我正试图在我的spring boot应用程序中使用KeyClope。 我想根据REST方法和用户角色限制对特定URL的访问。 在下面的示例中,具有或角色的用户可以执行GET,而具有或角色的用户可以执行POST、PUT或DELETE。 不幸的是,此配置允许任何经过身份验证的用户访问/api/日历URL。我做错了什么?

  • 不知何故,我迷失了Spring Security和Keycloak。 在一个应用程序中,我成功地从KeyClope实例接收了一个访问令牌。然后,我使用这个令牌请求我的Spring Security服务器(它使用相同的KeyClope实例)。 但我得到的只是403个错误。 以下是代码摘录(用kotlin编写): 安全配置: 在我的控制器中: 在我对服务器的调用中,我可以验证授权头的设置如下:auth

  • 我正在尝试在API网关(Apache APISIX)后面使用KeyClope。 我使用minikube来运行KeyClope和API网关。 网关正常工作,KeyClope也正常工作: 使用KeyClope,我可以使用不同的endpoint(使用发现endpoint(http://127.0.0.1:7070/auth/realms/myrealm/.well-已知/uma2配置),询问访问令牌并进

  • 我有一个spring boot应用程序(带有Keyclope适配器),运行在端口8000上,Keyclope运行在8080上 我编辑了我的 /etc/hosts文件,将测试域(foo.bar.com)上的请求路由到127.0.0.1 到目前为止,我对SSL不感兴趣。 我的示例nginx配置: 问题: 此示例nginx conf是否足够?我有一些无限的重定向发生。我的spring应用程序中来自Key

  • 我试图使用Keycloak的openId-connectendpoint来获取关于用户角色的信息。我使用/auth/realms/moje/protocol/OpenID-connect/userinfoendpoint来获取关于已验证用户的信息。我可以获得姓名、用户名、电子邮件等信息。但是我不能强迫Keyclak给我关于用户角色的信息。 我已经阅读了openID文档,我没有找到任何关于必须获取角

  • 有角度的v.v4。0.2 Spring靴1.5版。2.发布 钥匙斗篷v.2。4.0.最终版本(稍后将升级) 我读了关于同样问题的邮件对话:http://keycloak-user.88327.x6.nabble.com/keycloak-user-NOT-ATTEMPTED-bearer-only-error-while-trying-to-access-server-from-client-td