首页 > 解决方案 > 带有 Keycloak 的 Spring 应用程序返回 401 错误

问题描述

我正在尝试通过 Keycloak 访问 Spring App,但我总是收到 401 Unauthorized 错误。基本上我有一个单独工作的聊天模块,但是一旦我添加了 Keycloak,由于 401 错误,我无法访问该应用程序。我已经关注了大约 3 个教程,这些教程显示了与我所做的类似的事情,但我仍然不知道我做错了什么。

这是我的应用程序的配置:

keycloak: 
    enabled: true
    realm: myReal
    resource: myReal-api
    public-client: true
    bearer-only: true
    auth-server-url: http://localhost:8080/auth
    credentials:
      secret: 82eXXXXX-3XXX-4XXX-XXX7-287aXXXXXXXX
    principal-attribute: preferred_username
    cors: true

localhost:port/我有第一个界面(没有 Keycloak 安全性),它链接到我的服务,即localhost:port/index/{topicName}. 现在,当我单击该链接时,我应该得到 Keycloak 身份验证屏幕,但我得到了 401 错误。

我检查了请求的标头,将 HttpServletRequest 作为参数添加到我的displayMessage方法中,实际上我可以在我的 IDE 控制台中显示 access_token 和 X-Auth-Token。但似乎当我点击该链接时,它发送的请求没有令牌。

这是我的控制器方法(我的 Controller 类带有注释@Controller

@GetMapping(path = "/")
    public String index() {
        return "external";
    }

    @GetMapping(path = "/index/{topicName}",
            produces = MediaType.APPLICATION_JSON_VALUE)
    public String displayMessages(Model model, 
            @PathVariable String topicName) {       

            //HttpHeaders headers = new HttpHeaders();

            //headers.set("Authorization", request.getHeader("Authorization"));
            //header = request.getHeader("Authorization");
            //System.out.println(" T O K E N "+request.getHeader("X-Auth-Token"));

            projectServiceImpl.findByName(topicName);
            List<Message> messages = messageServiceImpl.findAllMessagesByProjectName(topicName);
            model.addAttribute("topic", topicName);
            model.addAttribute("message",messages);

            return "index";
    }

我的 Keycloak 配置文件的灵感来自于我读过的 tuto,所以那里可能有一个我不知道的错误(不确定方法accesshasRoleis 之间的区别):

@Configuration
@ComponentScan(
        basePackageClasses = KeycloakSecurityComponents.class,
        excludeFilters = @ComponentScan.Filter(
                type = FilterType.REGEX, 
                pattern = "org.keycloak.adapters.springsecurity.management.HttpSessionManager"))
@EnableWebSecurity
public class SecurityConfig extends KeycloakWebSecurityConfigurerAdapter {


    private static final Logger logger = LoggerFactory.getLogger(SecurityConfig.class);

    @Bean
    public HttpSessionIdResolver httpSessionIdResolver() { //replace HttpSessionStrategy
        return HeaderHttpSessionIdResolver.xAuthToken();
    }

    //Registers the KeycloakAuthenticationProvider with the authentication manager.
    @Autowired
    public void configureGlobal(AuthenticationManagerBuilder auth) throws Exception {

        try {
            SimpleAuthorityMapper grantedAuthorityMapper = new SimpleAuthorityMapper();
            grantedAuthorityMapper.setPrefix("ROLE_");
            grantedAuthorityMapper.setConvertToUpperCase(true);

            KeycloakAuthenticationProvider keycloakAuthenticationProvider = keycloakAuthenticationProvider();
            keycloakAuthenticationProvider.setGrantedAuthoritiesMapper(grantedAuthorityMapper);

            auth.authenticationProvider(keycloakAuthenticationProvider());

        } catch(Exception ex)  {
            logger.error("SecurityConfig.configureGlobal: " + ex);

        }

         /*try {
                KeycloakAuthenticationProvider keycloakAuthenticationProvider = keycloakAuthenticationProvider();
                keycloakAuthenticationProvider.setGrantedAuthoritiesMapper(new SimpleAuthorityMapper());
                auth.authenticationProvider(keycloakAuthenticationProvider);
            }catch(Exception ex){
                logger.error("SecurityConfig.configureGlobal: " +ex);
            }*/
    }

    //Load Keycloak properties from service config-file
    @Bean
    public KeycloakSpringBootConfigResolver KeycloakConfigResolver() {
        return new KeycloakSpringBootConfigResolver();
    }

    //Defines the session authentication strategy.
    @Bean
    @Override
    protected SessionAuthenticationStrategy sessionAuthenticationStrategy() {
        //Public or Confidential application keycloak/OpenID Connect client
        return new RegisterSessionAuthenticationStrategy(new SessionRegistryImpl());
        //Bearer mode only keycloak/OpenID Connect client without keycloak session -> stateless behavior
        //return new NullAuthenticatedSessionStrategy();
    }


    @Override
    protected void configure(HttpSecurity http) throws Exception
    {
        super.configure(http);
        http.authorizeRequests()
        //BEGIN
            //USER -done to be tested

            .antMatchers(HttpMethod.GET,"/index**").access("hasAuthority('ADMIN')")
            .antMatchers(HttpMethod.GET,"/").access("hasAuthority('ADMIN')")
            .antMatchers(HttpMethod.GET,"/").access("hasAnyAuthority('ADMIN','MANAGER','EXPERT','STANDARD')")



            .anyRequest().authenticated() 

            .and()
            .cors()
            .and()
            .csrf().disable()
            //BEGIN Login/Logout
            .formLogin()
                .permitAll()//.successHandler(authenticationSuccessHandler) //
            .and()
            .logout()//.clearAuthentication(true) //Add .clearAuthentication(true) to logout()
                //.logoutUrl("/custom-logout")
                .addLogoutHandler(keycloakLogoutHandler())
                //.addLogoutHandler(new LogoutHandlerImpl())
                .clearAuthentication(true)
                .invalidateHttpSession(true)
                .permitAll();
            //END Login/Logout

        //BEGIN Session
        http
        .sessionManagement()
            //.sessionCreationPolicy(SessionCreationPolicy.ALWAYS) //BY default IF_REQUIRED
            .maximumSessions(1)
                .maxSessionsPreventsLogin(false) // if true generate an error when user login after reaching maximumSession (SessionAuthenticationStrategy rejected the authentication object / SessionAuthenticationException: Maximum sessions of 1 for this principal exceeded)
                //.expiredUrl("/auth/login")
                .sessionRegistry(sessionRegistry());   



    }

     @Bean
     @Scope(scopeName = WebApplicationContext.SCOPE_REQUEST, proxyMode = ScopedProxyMode.TARGET_CLASS)
     public AccessToken accessToken() {
         HttpServletRequest request = ((ServletRequestAttributes) RequestContextHolder.currentRequestAttributes()).getRequest();
         return ((KeycloakSecurityContext) ((KeycloakAuthenticationToken) request.getUserPrincipal()).getCredentials()).getToken();
     }

    ///BEGIN session     
     @Bean
     public SessionRegistry sessionRegistry() {
        SessionRegistry sessionRegistry = new SessionRegistryImpl();
        return sessionRegistry;
     }


    @Bean
    public RegisterSessionAuthenticationStrategy registerSessionAuthStr( ) {
        return new RegisterSessionAuthenticationStrategy( sessionRegistry( ) );
    }

    // Register HttpSessionEventPublisher
    @Bean
    public static ServletListenerRegistrationBean<HttpSessionEventPublisher> httpSessionEventPublisher() {
        return new ServletListenerRegistrationBean<HttpSessionEventPublisher>(new HttpSessionEventPublisher());
    }

我真的不知道我应该改变什么才能让它工作,但我相信那里一定有什么问题。但是我认为如果我在尝试访问我的服务时可以拥有 Keycloak 身份验证屏幕,那就没问题了。

标签: javaspringspring-securitykeycloak

解决方案


我收到了同样的错误,要仔细检查的一件事是auth-server-url服务器和客户端获取令牌是一样的。

即如果一个是dns名称,一个是IP地址,它不会授权。(在我的情况下,我有 localhost 和 127.0.0.1 所以授权失败)

服务器,src/main/resources/application.yml

在此处输入图像描述

邮递员/客户:

在此处输入图像描述


推荐阅读