title: Enable role authentication with spring boot (security) and keycloak?
body: <p>I am trying to do a simple thing.</p>
  
  <p>Want to make a request to a single endpoint and send a bearer token (from a client), I want this token to be validated and depending on the role assigned on keycloak accept/deny request on my endpoint.</p>
  
  <p>I followed many tutorials and even books but most of all them I simply dont understand.</p>
  
  <p>Followed this to setup my keycloak info (realm, role, user)
  <a href="https://medium.com/@bcarunmail/securing-rest-api-using-keycloak-and-spring-oauth2-6ddf3a1efcc2" rel="noreferrer">https://medium.com/@bcarunmail/securing-rest-api-using-keycloak-and-spring-oauth2-6ddf3a1efcc2</a></p>
  
  <p>So,</p>
  
  <p>I basically set up my keycloak with a client, a user with a specific role "user" and configured it like this:</p>
  
  <pre><code>@Configuration
  @KeycloakConfiguration
  //@ComponentScan(basePackageClasses = KeycloakSecurityComponents.class)
  public class SecurityConf extends KeycloakWebSecurityConfigurerAdapter
  {
      /**
       * Registers the KeycloakAuthenticationProvider with the authentication manager.
       */
      @Autowired
      public void configureGlobal(AuthenticationManagerBuilder auth) throws Exception {
          auth.authenticationProvider(keycloakAuthenticationProvider());
      }
  
      /**
       * Defines the session authentication strategy.
       */
      @Bean
      @Override
      protected SessionAuthenticationStrategy sessionAuthenticationStrategy() {
          return new RegisterSessionAuthenticationStrategy(new SessionRegistryImpl());
      }
  
      @Bean
      public KeycloakSpringBootConfigResolver KeycloakConfigResolver() {
          return new KeycloakSpringBootConfigResolver();
      }
  
      @Bean
      public FilterRegistrationBean keycloakAuthenticationProcessingFilterRegistrationBean(
              KeycloakAuthenticationProcessingFilter filter) {
          FilterRegistrationBean registrationBean = new FilterRegistrationBean(filter);
          registrationBean.setEnabled(false);
          return registrationBean;
      }
  
      @Bean
      public FilterRegistrationBean keycloakPreAuthActionsFilterRegistrationBean(
              KeycloakPreAuthActionsFilter filter) {
          FilterRegistrationBean registrationBean = new FilterRegistrationBean(filter);
          registrationBean.setEnabled(false);
          return registrationBean;
      }
  
  
      @Override
      protected void configure(HttpSecurity http) throws Exception
      {
          super.configure(http);
          http
                  .authorizeRequests()
                  .antMatchers("/user/*").hasRole("admin")
                  .antMatchers("/admin*").hasRole("user")
  
      }
  }
  </code></pre>
  
  <p>I dont understand why at many tutorials I see this(as the last rule):</p>
  
  <pre><code>.anyRequest().permitAll();
  </code></pre>
  
  <p>Basically when I set that I have no security, I can call the endpoints without a bearer token.</p>
  
  <p>But when I add this as last rule</p>
  
  <pre><code> .anyRequest().denyAll();
  </code></pre>
  
  <p>I always get a 403.</p>
  
  <p>Debbugging I found this:</p>
  
  <p>Request is to process authentication</p>
  
  <pre><code>f.KeycloakAuthenticationProcessingFilter : Attempting Keycloak authentication
  o.k.a.BearerTokenRequestAuthenticator    : Found [1] values in authorization header, selecting the first value for Bearer.
  o.k.a.BearerTokenRequestAuthenticator    : Verifying access_token
  o.k.a.BearerTokenRequestAuthenticator    : successful authorized
  a.s.a.SpringSecurityRequestAuthenticator : Completing bearer authentication. Bearer roles: [] 
  o.k.adapters.RequestAuthenticator        : User 'testuser' invoking 'http://localhost:9090/api/user/123' on client 'users'
  o.k.adapters.RequestAuthenticator        : Bearer AUTHENTICATED
  f.KeycloakAuthenticationProcessingFilter : Auth outcome: AUTHENTICATED
  o.s.s.authentication.ProviderManager     : Authentication attempt using org.keycloak.adapters.springsecurity.authentication.KeycloakAuthenticationProvider
  o.s.s.core.session.SessionRegistryImpl   : Registering session 5B871A0E2AF55B70DC8E3B7436D79333, for principal testuser
  f.KeycloakAuthenticationProcessingFilter : Authentication success using bearer token/basic authentication. Updating SecurityContextHolder to contain: org.keycloak.adapters.springsecurity.token.KeycloakAuthenticationToken@355f68d6: Principal: testuser; Credentials: [PROTECTED]; Authenticated: true; Details: org.keycloak.adapters.springsecurity.account.SimpleKeycloakAccount@5d7a32a9; Not granted any authorities
  [nio-9090-exec-3] o.s.security.web.FilterChainProxy        : /api/user/123 at position 8 of 15 in additional filter chain; firing Filter: 'RequestCacheAwareFilter'
  nio-9090-exec-3] o.s.s.w.s.DefaultSavedRequest            : pathInfo: both null (property equals)
  [nio-9090-exec-3] o.s.s.w.s.DefaultSavedRequest            : queryString: both null (property equals)
  </code></pre>
  
  <p>Seems like I get no bearer roles ...</p>
  
  <p>My dependencies:</p>
  
  <pre><code>        &lt;dependency&gt;
              &lt;groupId&gt;org.keycloak&lt;/groupId&gt;
              &lt;artifactId&gt;keycloak-spring-boot-starter&lt;/artifactId&gt;
              &lt;version&gt;6.0.1&lt;/version&gt;
          &lt;/dependency&gt;
          &lt;dependency&gt;
              &lt;groupId&gt;org.keycloak&lt;/groupId&gt;
              &lt;artifactId&gt;keycloak-spring-security-adapter&lt;/artifactId&gt;
              &lt;version&gt;6.0.1&lt;/version&gt;
          &lt;/dependency&gt;
  
          &lt;dependency&gt;
              &lt;groupId&gt;org.springframework.boot&lt;/groupId&gt;
              &lt;artifactId&gt;spring-boot-starter-security&lt;/artifactId&gt;
          &lt;/dependency&gt;
  </code></pre>
  
  <p>My problem?</p>
  
  <p>I request an access token sending:</p>
  
  <pre><code>client_id -&gt; my client from keycloak
  username -&gt; my user from keycloak
  password -&gt; my password from keycloak
  grant_type -&gt; password
  client_secret -&gt; from keycloak
  </code></pre>
  
  <p>I get a token and then I use to request to my app endoint. <strong>My requests are always valid no matter what endpoint I use (the one with role user or with role admin).</strong></p>
  
  <p>At my properties I have something like this:</p>
  
  <pre><code>keycloak:
    auth-server-url: http://localhost:8080/auth/
    resource: users-api
    credentials:
      secret : my-secret
    use-resource-role-mappings : true
    realm: my-realm
    realmKey:  my-key
    public-client: true
    principal-attribute: preferred_username
    bearer-only: true
  </code></pre>
  
  <p>Any idea how to actually enabling the roles in this case?</p>
  
  <p>Do I have to configure a client to use JWT? any ideas?</p>
  
  <p>I also added the annotations on my endpoint</p>
  
  <pre><code>@Secured("admin")
  @PreAuthorize("hasAnyAuthority('admin')")
  </code></pre>
  
  <p>but seems they dont do anything...</p>
  
  <p>-- EDIT --</p>
  
  <p>After fixed the url to match the resource I still get 403.</p>
  
  <pre><code>"realm_access": {
      "roles": [
        "offline_access",
        "admin",
        "uma_authorization"
      ]
    },
    "resource_access": {
      "account": {
        "roles": [
          "manage-account",
          "manage-account-links",
          "view-profile"
        ]
      }
    },
  </code></pre>
  
  <p>Is it somehow related the resource_access with my problem?</p>