2016-10-10 13 views
1

У меня есть приложение REST для Java, которое я хочу защитить от keycloak. Я сделал несколько тестов, приложение хорошо работает с фильтром сервлетов keycloak, но у меня проблемы с адаптером весны.Весна безопасности keycloak адаптер на предъявителя

keycloak.json (значения удалены)

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

Как видно мне нужно только разрешение на предъявителя, если запрос содержит действительный маркер, то я ожидаю HTTP 200, если не HTTP 401. Я использовал эту конфигурацию 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.key[email protected]65776c48: Principal: e9ae6919-c0f3-4dcb-96f6-82e3373932e9; Credentials: [PROTECTED]; Authenticated: true; Details: org[email protected]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.se[email protected]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' 

Я проверяю этот endpoit на JUnit

@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(); 
    } 
} 

Keycloak версия сервера: 2.1.0.Final

Keycloak родственный pom part:

<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> 

Любые предложения приветствуются.

ответ

0

Проблема решена. В моем тестовом коде была ошибка. Метод getToken() возвращает «предъявитель». Это приемлемо для адаптера фильтра keycloak, но не для весеннего адаптера безопасности. Правильный путь - «несущий», и он работает в обоих адаптерах.

 Смежные вопросы

  • Нет связанных вопросов^_^