【问题标题】:Spring Security authorization remotelySpring Security 远程授权
【发布时间】:2016-08-08 23:53:20
【问题描述】:

我目前正在开发 Spring Security 4,使用默认配置一切正常。但是,由于我在一台机器 (192.168.0.1) 上拥有 Spring Web 应用程序,而在另一台机器 (192.168.0.2) 上拥有 HTML Server,我如何将 Spring Security 配置为使用 192.168.0.2 上的登录表单进行授权。

Spring 安全配置:

<http use-expressions="true" auto-config="true" >
  default-target-url="http://192.168.0.2/home.html"
</http>

目前,在 192.168.0.2 的登录表单中,我使用

<form method="post" action="http://192.168.0.1:8080/xxx/login">
    <input type="text" required name="username"/>
    <input type="password" required name="password"/>
    <button type="submit">Sign in</button>
</form>

在192.168.0.2上,用户可以通过授权。但是,我在 192.168.0.2 的 cookie 中找不到任何 JSESSIONID 或任何相关的东西。

我的问题是,为了让 Spring Security 知道我是谁,我应该在后续 ajax 请求中包含哪些信息?

顺便说一句,如果我的授权失败,浏览器将被重定向到192.168.0.1/xxx/login,我怎样才能留在我的自定义登录页面?

谢谢。

【问题讨论】:

    标签: java spring spring-mvc spring-security


    【解决方案1】:

    为了简单起见,假设您有两台机器命名。

    AppIp    : 192.168.0.1
    StaticIp : 192.168.0.2
    

    现在,当您在浏览器中加载表单时,它会点击 StaticIp。然后提交给AppIp

    这就是正在发生的事情。当您将表单提交给AppIp 时,它会返回JSESSIONID 或要为AppIp 设置的任何其他Cookie。所以浏览器也会这样做,它将 cookie 设置为 AppIp 而不是 StaticIp

    一个域(如 google.com)只能读/写它自己的 cookie。浏览器不会为 facebook 设置 google 发送的 cookie。

    这就是为什么您在StaticIp 资源中看不到cookie,如果您加载AppIp,您将能够在其资源中看到cookie。

    解决方案是在两台服务器前面都有一个代理服务器。例如 Apache HTTPd 或 NGINX。

    现在假设代理服务器是ProxyIp,配置如下。

    ProxyIp/static maps to http://192.168.0.2/ (or http://AppIp/)
    ProxyIp/app maps to http://192.168.0.1/ (or http://StaticIp/)
    

    所以现在表单 URL 变成了http://ProxyIp/static/home.html

    /login URL 将变为http://ProxyIp/app/xxx/login

    现在浏览器只有一个域ProxyIp,它可以为两个映射的服务器设置cookie。

    注意:您不能发送正常的 Ajax 跨域请求。浏览器将阻止所有此类尝试。 Ajax 请求只能发送到加载了执行 Ajax 脚本的 HTML 的域。可以通过 CORS 的一些配置来完成,但这太痛苦和汗水了。

    【讨论】:

      猜你喜欢
      • 2017-04-20
      • 2014-05-10
      • 2013-03-15
      • 2020-04-25
      • 2022-01-06
      • 2020-03-20
      • 2013-12-01
      • 2015-10-21
      • 1970-01-01
      相关资源
      最近更新 更多