简体   繁体   English

keycloak(春季启动)未验证REST端点

[英]keycloak (spring boot) Not authenticating REST endpoint

I am trying to play around with open source user management service like keycloak. 我正在尝试使用像keycloak这样的开源用户管理服务。 Building a angularJs app that will be send HTTP request to REST endpoint secured by keycloak. 构建一个angularJs应用程序,该应用程序会将HTTP请求发送到由keycloak保护的REST端点。 I am using spring boot on the backend. 我在后端使用Spring Boot。 I am able to call the endpoint and get result which should not be possible since it should block request coming from unauthorized source. 我能够调用端点并获得不可能的结果,因为它会阻止来自未授权来源的请求。

These are the two links that I followed 这是我关注的两个链接

  1. keycloak with angular and spring boot 角斗篷和弹簧靴

2. Github link to keycloak example 2. Github链接到keycloak示例

Controller which consists of REST endpoint that the user will call. 由用户将调用的REST端点组成的控制器。

@RequestMapping(value = "/api/getSample")
public test welcome() {
    return new test("sample");
}

@RequestMapping(value = "/check/test")
public test welcome2() {
    return new test("test");
}

Spring boot application with CORS 具有CORS的Spring Boot应用程序

@SpringBootApplication
public class Application 
{
    public static void main( String[] args )
    {
        SpringApplication.run(Application.class, args);
    }

    @Bean
    public FilterRegistrationBean corsFilter() {
        UrlBasedCorsConfigurationSource source = new UrlBasedCorsConfigurationSource();
        CorsConfiguration config = new CorsConfiguration();
        config.setAllowCredentials(true);
        config.addAllowedOrigin("*");
        config.addAllowedHeader("*");
        config.addAllowedMethod("*");
        source.registerCorsConfiguration("/api/*", config);

        FilterRegistrationBean bean = new FilterRegistrationBean(new CorsFilter(source));
        bean.setOrder(0);
        return bean;
    }
}

Application properties files for 的应用程序属性文件

server.port = 8090

keycloak.realm = demo
keycloak.auth-server-url = http://localhost:8080/auth
keycloak.ssl-required = external
keycloak.resource = tutorial-backend
keycloak.bearer-only = true
keycloak.credentials.secret = 111-1111-111-111
keycloak.use-resource-role-mappings = true
keycloak.cors= true

keycloak.securityConstraints[0].securityCollections[0].name = spring secured api
keycloak.securityConstraints[0].securityCollections[0].authRoles[0] = user
keycloak.securityConstraints[0].securityCollections[0].patterns[0] = /api

keycloak.securityConstraints[0].securityCollections[1].name = insecure stuff
keycloak.securityConstraints[0].securityCollections[1].authRoles[0] = user
keycloak.securityConstraints[0].securityCollections[1].patterns[0] = /check

There are two test case 有两个测试用例

  1. Making REST call without logging in. In this case I am able to get the result back. 无需登录即可进行REST调用。在这种情况下,我可以取回结果。 This should not be the case, I get should blocked(get 401 error). 事实并非如此,我应该被阻止(出现401错误)。

  2. Making REST call when logged in. I am able to call the api/getSample and this is the correct behavior. 登录时进行REST调用。我能够调用api / getSample,这是正确的行为。 However when I call check/test I get XMLHttpRequest cannot load http://localhost:8090/check/test. Response to preflight request doesn't pass access control check: No 'Access-Control-Allow-Origin' header is present on the requested resource. Origin 'http://localhost:9000' is therefore not allowed access. The response had HTTP status code 403. 但是,当我调用check / test时,我得到XMLHttpRequest cannot load http://localhost:8090/check/test. Response to preflight request doesn't pass access control check: No 'Access-Control-Allow-Origin' header is present on the requested resource. Origin 'http://localhost:9000' is therefore not allowed access. The response had HTTP status code 403. XMLHttpRequest cannot load http://localhost:8090/check/test. Response to preflight request doesn't pass access control check: No 'Access-Control-Allow-Origin' header is present on the requested resource. Origin 'http://localhost:9000' is therefore not allowed access. The response had HTTP status code 403.

1) 1)

I don't know how exactly your test looks like, but maybe the system thinks that you are still logged in? 我不知道您的测试看起来如何,但是也许系统认为您仍在登录? You could try to delete your cookies to make sure that there's no access token saved. 您可以尝试删除Cookie,以确保没有保存访问令牌。

Another Option could be that Spring Boot doesn't recognize the Keycloak Adapter and therefore doesn't secure the access. 另一个选择可能是Spring Boot无法识别Keycloak适配器,因此无法保护访问。 You mainly configure the Adapter by adding the keycloak-spring-boot-adapter and keycloak-tomcat8-adapter dependencies ( more details here ). 您主要是通过添加keycloak-spring-boot-adapterkeycloak-tomcat8-adapter依赖keycloak-tomcat8-adapter此处有更多详细信息 )。

2) 2)

It looks like the CORS is not configured properly. 好像CORS配置不正确。 You could consider this implementation for the configuration ( more details here ): 您可以考虑将这种实现用于配置( 此处有更多详细信息 ):

@Bean
FilterRegistrationBean corsFilter(
        @Value("${tagit.origin:http://localhost:9000}") String origin) {
    return new FilterRegistrationBean(new Filter() {
        public void doFilter(ServletRequest req, ServletResponse res,
                             FilterChain chain) throws IOException, ServletException {
            HttpServletRequest request = (HttpServletRequest) req;
            HttpServletResponse response = (HttpServletResponse) res;
            String method = request.getMethod();
            // this origin value could just as easily have come from a database
            response.setHeader("Access-Control-Allow-Origin", origin);
            response.setHeader("Access-Control-Allow-Methods",
                    "POST,GET,PUT,DELETE");
            response.setHeader("Access-Control-Max-Age", Long.toString(60 * 60));
            response.setHeader("Access-Control-Allow-Credentials", "true");
            response.setHeader(
                    "Access-Control-Allow-Headers",
                    "Origin,Accept,X-Requested-With,Content-Type,Access-Control-Request-Method,Access-Control-Request-Headers,Authorization");
            if ("OPTIONS".equals(method)) {
                response.setStatus(HttpStatus.OK.value());
            }
            else {
                chain.doFilter(req, res);
            }
        }

        public void init(FilterConfig filterConfig) {
        }

        public void destroy() {
        }
    });
}

You haven't added the Spring Boot Keycloak Adapter dependency in your pom.xml. 您尚未在pom.xml中添加Spring Boot Keycloak适配器依赖项。

For 2. You haven't configured CORS for /check (only for /api) 对于2。您尚未为/ check配置CORS(仅针对/ api)

 <dependency>
      <groupId>org.keycloak</groupId>
      <artifactId>keycloak-spring-boot-adapter</artifactId>
      <version>${keycloak.version}</version>
  </dependency>

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM