有 Java 编程相关的问题?

你可以在下面搜索框中键入要查询的问题!

java Spring安全:如何将两个应用程序与单独的Spring安全配置集成?

我有两个应用程序,作为独立的springboot应用程序运行。 附录1&;附件2

用户在App1的UI上输入凭据,这些凭据通过angular js路由

$http.post('/login', $.param(self.credentials), {
      headers : {
        "content-type" : "application/x-www-form-urlencoded"
      }
}   

Spring security成功拦截了此请求。截获此请求后,我向App2发出post请求(在端口8018上运行)

// implementation of authentication provider:
public Authentication authenticate(final Authentication authentication) throws AuthenticationException {    
    Authentication auth = null;   
    MultiValueMap<String, Object> params = new LinkedMultiValueMap<>();
    params.set("username", "user"); // for testing purpose
    params.set("password", "user"); // for testing purpose
    RestTemplate restTemplate = new RestTemplate();
    HttpHeaders reqHead = new HttpHeaders();
    reqHead.setContentType(MediaType.APPLICATION_FORM_URLENCODED);
    restTemplate.getMessageConverters().add(new FormHttpMessageConverter());
    ResponseEntity response = restTemplate.postForEntity("http://localhost:8018/login/process",
            new HttpEntity<>(params, reqHead), MyClass.class);  

然而,App2中的Spring security无法正确拦截该请求。我只得到302(空)

DEBUG 12144 --- [nio-8010-exec-1] o.s.web.client.RestTemplate              : Setting request Accept header to [application/json, application/*+json]
DEBUG 12144 --- [nio-8010-exec-1] o.s.web.client.RestTemplate              : Writing [{username=[user], password=[user]}] as "application/x-www-form-urlencoded" using [org.springframework.http.converter.support.AllEncompassingFormHttpMessageConverter@2fc281c1]
DEBUG 12144 --- [nio-8010-exec-1] o.s.web.client.RestTemplate              : POST request for "http://localhost:8018/login/process" resulted in 302 (null)

(MyClass只是一个包含httpstatus和对象数据的类。)

我的app2安全配置:

@Override
    protected void configure(final HttpSecurity http) throws Exception {
        http.authorizeRequests().antMatchers("/welcome").permitAll().anyRequest().authenticated();
        http.csrf().disable();
        // http.httpBasic();
        http.formLogin()
    }

如果我改变

antMatchers("/welcome").permitAll()

antMatchers("/welcome","/login/**").permitAll()

然后请求成功绕过安全并到达我的控制器。 所以我假设spring security能够拦截,但我做了一些配置错误


共 (1) 个答案

  1. # 1 楼答案

    App2中的配置显示:“每个人都可以访问/欢迎端点;但只有经过身份验证的人(具有表单身份验证)才能访问所有其他页面”

    因此,当您向/login/process发出请求时,App2中的Spring Security会将该请求重定向到登录页面

    如果您希望像处理“受信任”的请求一样处理该请求,则必须在App2中相应地指示Spring Security。例如,您可以向“特权”URL添加基本身份验证。这可以通过下面描述的技术来实现:Combining basic authentication and form login for the same REST Api

    然后,您必须向请求中添加基本身份验证,例如:http://www.baeldung.com/how-to-use-resttemplate-with-basic-authentication-in-spring

    另一种需要更少代码但强制您手动构建授权头的方法如下所述:http://springinpractice.com/2013/10/02/quick-tip-basic-authentication-with-spring-resttemplate