【问题标题】:Official Spring security oauth2 example doesn't work because of cookies clashing(authorization code mechanism)由于 cookie 冲突(授权码机制),官方 Spring 安全 oauth2 示例不起作用
【发布时间】:2018-10-01 05:31:12
【问题描述】:

根据教程Spring Boot and OAuth2

我有以下项目结构:

以及以下源代码:

SocialApplication.class:

@SpringBootApplication
@RestController
@EnableOAuth2Client
@EnableAuthorizationServer
@Order(200)
public class SocialApplication extends WebSecurityConfigurerAdapter {

    @Autowired
    OAuth2ClientContext oauth2ClientContext;

    @RequestMapping({ "/user", "/me" })
    public Map<String, String> user(Principal principal) {
        Map<String, String> map = new LinkedHashMap<>();
        map.put("name", principal.getName());
        return map;
    }

    @Override
    protected void configure(HttpSecurity http) throws Exception {
        // @formatter:off
        http.antMatcher("/**").authorizeRequests().antMatchers("/", "/login**", "/webjars/**").permitAll().anyRequest()
                .authenticated().and().exceptionHandling()
                .authenticationEntryPoint(new LoginUrlAuthenticationEntryPoint("/")).and().logout()
                .logoutSuccessUrl("/").permitAll().and().csrf()
                .csrfTokenRepository(CookieCsrfTokenRepository.withHttpOnlyFalse()).and()
                .addFilterBefore(ssoFilter(), BasicAuthenticationFilter.class);
        // @formatter:on
    }

    @Configuration
    @EnableResourceServer
    protected static class ResourceServerConfiguration extends ResourceServerConfigurerAdapter {
        @Override
        public void configure(HttpSecurity http) throws Exception {
            // @formatter:off
            http.antMatcher("/me").authorizeRequests().anyRequest().authenticated();
            // @formatter:on
        }
    }

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

    @Bean
    public FilterRegistrationBean<OAuth2ClientContextFilter> oauth2ClientFilterRegistration(OAuth2ClientContextFilter filter) {
        FilterRegistrationBean<OAuth2ClientContextFilter> registration = new FilterRegistrationBean<OAuth2ClientContextFilter>();
        registration.setFilter(filter);
        registration.setOrder(-100);
        return registration;
    }

    @Bean
    @ConfigurationProperties("github")
    public ClientResources github() {
        return new ClientResources();
    }

    @Bean
    @ConfigurationProperties("facebook")
    public ClientResources facebook() {
        return new ClientResources();
    }

    private Filter ssoFilter() {
        CompositeFilter filter = new CompositeFilter();
        List<Filter> filters = new ArrayList<>();
        filters.add(ssoFilter(facebook(), "/login/facebook"));
        filters.add(ssoFilter(github(), "/login/github"));
        filter.setFilters(filters);
        return filter;
    }

    private Filter ssoFilter(ClientResources client, String path) {
        OAuth2ClientAuthenticationProcessingFilter filter = new OAuth2ClientAuthenticationProcessingFilter(
                path);
        OAuth2RestTemplate template = new OAuth2RestTemplate(client.getClient(), oauth2ClientContext);
        filter.setRestTemplate(template);
        UserInfoTokenServices tokenServices = new UserInfoTokenServices(
                client.getResource().getUserInfoUri(),
                client.getClient().getClientId());
        tokenServices.setRestTemplate(template);
        filter.setTokenServices(new UserInfoTokenServices(
                client.getResource().getUserInfoUri(),
                client.getClient().getClientId()));
        return filter;
    }

}

class ClientResources {

    @NestedConfigurationProperty
    private AuthorizationCodeResourceDetails client = new AuthorizationCodeResourceDetails();

    @NestedConfigurationProperty
    private ResourceServerProperties resource = new ResourceServerProperties();

    public AuthorizationCodeResourceDetails getClient() {
        return client;
    }

    public ResourceServerProperties getResource() {
        return resource;
    }
}

index.html:

<!doctype html>
<html lang="en">
<head>
    <meta charset="utf-8"/>
    <meta http-equiv="X-UA-Compatible" content="IE=edge"/>
    <title>Demo</title>
    <meta name="description" content=""/>
    <meta name="viewport" content="width=device-width"/>
    <base href="/"/>
    <link rel="stylesheet" type="text/css"
          href="/webjars/bootstrap/css/bootstrap.min.css"/>
    <script type="text/javascript" src="/webjars/jquery/jquery.min.js"></script>
    <script type="text/javascript"
            src="/webjars/bootstrap/js/bootstrap.min.js"></script>
</head>
<body>
<h1>Login</h1>
<div class="container unauthenticated">
    With Facebook: <a href="/login/facebook">click here</a>
</div>
<div class="container authenticated" style="display: none">
    Logged in as: <span id="user"></span>
    <div>
        <button onClick="logout()" class="btn btn-primary">Logout</button>
    </div>
</div>
<script type="text/javascript"
        src="/webjars/js-cookie/js.cookie.js"></script>
<script type="text/javascript">
    $.ajaxSetup({
        beforeSend: function (xhr, settings) {
            if (settings.type == 'POST' || settings.type == 'PUT'
                || settings.type == 'DELETE') {
                if (!(/^http:.*/.test(settings.url) || /^https:.*/
                        .test(settings.url))) {
                    // Only send the token to relative URLs i.e. locally.
                    xhr.setRequestHeader("X-XSRF-TOKEN",
                        Cookies.get('XSRF-TOKEN'));
                }
            }
        }
    });
    $.get("/user", function (data) {
        $("#user").html(data.userAuthentication.details.name);
        $(".unauthenticated").hide();
        $(".authenticated").show();
    });
    var logout = function () {
        $.post("/logout", function () {
            $("#user").html('');
            $(".unauthenticated").show();
            $(".authenticated").hide();
        });
        return true;
    }
</script>
</body>
</html>

application.yml:

server:
  port: 8080
security:
  oauth2:
    client:
      client-id: acme
      client-secret: acmesecret
      scope: read,write
      auto-approve-scopes: '.*'

facebook:
  client:
    clientId: 233668646673605
    clientSecret: 33b17e044ee6a4fa383f46ec6e28ea1d
    accessTokenUri: https://graph.facebook.com/oauth/access_token
    userAuthorizationUri: https://www.facebook.com/dialog/oauth
    tokenName: oauth_token
    authenticationScheme: query
    clientAuthenticationScheme: form
  resource:
    userInfoUri: https://graph.facebook.com/me
github:
  client:
    clientId: bd1c0a783ccdd1c9b9e4
    clientSecret: 1a9030fbca47a5b2c28e92f19050bb77824b5ad1
    accessTokenUri: https://github.com/login/oauth/access_token
    userAuthorizationUri: https://github.com/login/oauth/authorize
    clientAuthenticationScheme: form
  resource:
    userInfoUri: https://api.github.com/user

logging:
  level:
    org.springframework.security: DEBUG

但是当我打开浏览器并尝试点击http://localhost:8080

在浏览器控制台中我看到:

(index):44 Uncaught TypeError: Cannot read property 'details' of undefined
    at Object.success ((index):44)
    at j (jquery.js:3073)
    at Object.fireWith [as resolveWith] (jquery.js:3185)
    at x (jquery.js:8251)
    at XMLHttpRequest.<anonymous> (jquery.js:8598)

在代码中:

$.get("/user", function (data) {
        $("#user").html(data.userAuthentication.details.name);
        $(".unauthenticated").hide();
        $(".authenticated").show();
    });

这是因为 /user 响应带有 302 状态码和 js 回调尝试解析 localhost:8080 的结果:

我不明白为什么会发生这种重定向。您能解释一下这种行为并帮助解决它吗?

更新

我从https://github.com/spring-guides/tut-spring-boot-oauth2获取此代码

重要:

只有在我启动客户端应用程序后才会重现。

附言

如何重现:

要测试新功能,您只需运行这两个应用程序并访问 localhost:9999/client 在您的浏览器中。客户端应用程序将重定向到 本地授权服务器,然后为用户提供通常的 选择使用 Facebook 或 Github 进行身份验证。一旦那是 完全控制权返回给测试客户端,本地访问令牌是 授予并且身份验证完成(您应该看到“Hello” 浏览器中的消息)。如果你已经通过 Github 认证 或 Facebook,您甚至可能没有注意到远程身份验证

答案:

https://stackoverflow.com/a/50349078/2674303

【问题讨论】:

标签: java spring-security oauth-2.0 spring-oauth2


【解决方案1】:

更新:2018 年 5 月 15 日

正如您已经找到了解决方案,问题的发生是因为 JSESSIONID 被覆盖

更新:2018 年 5 月 10 日

嗯,您对第三次赏金的坚持终于得到了回报。我开始深入研究你在 repo 中的两个示例之间的不同之处

如果您查看 manual 存储库和 /user 映射

@RequestMapping("/user")
public Principal user(Principal principal) {
    return principal;
}

如您所见,您在此处返回principal,您可以从同一个对象中获得更多详细信息。现在在您从 auth-server 文件夹运行的代码中

@RequestMapping({ "/user", "/me" })
public Map<String, String> user(Principal principal) {
    Map<String, String> map = new LinkedHashMap<>();
    map.put("name", principal.getName());
    return map;
}

如您所见,您仅在 /user 映射中返回了 name,并且您的 UI 逻辑在下面运行

$.get("/user", function(data) {
    $("#user").html(data.userAuthentication.details.name);
    $(".unauthenticated").hide();
    $(".authenticated").show();
});

因此,从/user api 返回的 json 响应预计由 UI 具有 userAuthentication.details.name 没有该详细信息。现在,如果我在同一个项目中更新如下方法

@RequestMapping({"/user", "/me"})
public Map<String, Object> user(Principal principal) {
    Map<String, Object> map = new LinkedHashMap<>();
    map.put("name", principal.getName());
    OAuth2Authentication user = (OAuth2Authentication) principal;
    map.put("userAuthentication", new HashMap<String, Object>(){{
       put("details", user.getUserAuthentication().getDetails());
    }});
    return map;
}

然后检查应用程序,它可以工作

原答案

因此,您从 repo 运行错误项目的问题。您正在运行的项目是auth-server,用于启动您自己的oauth 服务器。您需要运行的项目位于manual 文件夹中。

现在如果你看下面的代码

OAuth2ClientAuthenticationProcessingFilter facebookFilter = new OAuth2ClientAuthenticationProcessingFilter(
        "/login/facebook");
OAuth2RestTemplate facebookTemplate = new OAuth2RestTemplate(facebook(), oauth2ClientContext);
facebookFilter.setRestTemplate(facebookTemplate);
UserInfoTokenServices tokenServices = new UserInfoTokenServices(facebookResource().getUserInfoUri(),
        facebook().getClientId());
tokenServices.setRestTemplate(facebookTemplate);
facebookFilter.setTokenServices(
        new UserInfoTokenServices(facebookResource().getUserInfoUri(), facebook().getClientId()));
return facebookFilter;

你运行的实际代码有

private Filter ssoFilter(ClientResources client, String path) {
    OAuth2ClientAuthenticationProcessingFilter filter = new OAuth2ClientAuthenticationProcessingFilter(
            path);
    OAuth2RestTemplate template = new OAuth2RestTemplate(client.getClient(), oauth2ClientContext);
    filter.setRestTemplate(template);
    UserInfoTokenServices tokenServices = new UserInfoTokenServices(
            client.getResource().getUserInfoUri(), client.getClient().getClientId());
    tokenServices.setRestTemplate(template);
    filter.setTokenServices(tokenServices);
    return filter;
}

在您当前,来自facebookuserdetails 不会被收集。这就是您看到错误的原因

因为当您登录用户时,您没有收集其用户详细信息。因此,当您访问详细信息时,它不存在。因此你得到一个错误

如果您运行正确的 manual 文件夹,它就可以工作

【讨论】:

  • 还是不行。看来你没看懂问题。您需要启动客户端和服务器 - 它是 2 个不同的应用程序!!!请从头开始重新阅读我的问题
  • 请说明您将哪个文件夹用于客户端应用程序?
  • 你可以在 src/test/java 中找到它
  • 你那边有什么消息吗?
  • @gstackoverflow,我和你不在同一页。 auth-server 文件夹中的代码在我更改后运行良好,它在 8080 上侦听,为什么还要同时运行 src/test/javasrc/main/java
【解决方案2】:

我在您的帖子中看到两个问题。

一个-

(index):44 Uncaught TypeError: Cannot read property 'details' of undefined

发生这种情况是因为您可能运行了一个有错误的错误项目(即 auth-server)。该回购包含其他类似的项目也没有错误。如果您运行项目 ma​​nualgithub,则不会出现此错误。在这些项目中,javascript 代码正确处理身份验证后服务器返回的数据。

两个-

/user回复 302 状态码:

要了解为什么会发生这种情况,让我们看看这个应用程序的安全配置。

端点"/""/login**""/logout" 可供所有人访问。 包括"/user" 在内的所有其他端点都需要身份验证,因为您已经使用过

.anyRequest().authenticated().and().exceptionHandling()
                .authenticationEntryPoint(new LoginUrlAuthenticationEntryPoint("/"))

因此,任何未经身份验证的请求都将被重定向到身份验证入口点,即"/",要求用户进行身份验证。它不取决于您的客户端应用程序是否已启动。只要请求未通过身份验证,它将被重定向到"/"。这就是为什么 spring 控制器以状态 302 响应的原因。一旦您通过 facebookgithub 进行了身份验证,随后对 "/user" 端点的请求将以 200 响应成功。

还有下一步-

您的应用程序中的端点"/me" 作为安全资源使用@EnableResourceServer 进行保护。由于ResourceServerConfiguration 具有比WebSecurityConfigurerAdapter 更高的优先级(默认为3)(默认为100,无论如何它已经在代码中使用@Order 注释明确排序低于3),因此ResourceServerConfiguration 将应用于此端点。这意味着如果请求未通过身份验证,则它不会被重定向到身份验证入口点,而是返回响应 401。一旦您通过身份验证,它将以 200 响应成功。

希望这能澄清您的所有问题。

UPDATE-回答您的问题

您在帖子中提供的存储库链接包含许多项目。 auth-serverma​​nualgithub 项目都是相似的(提供相同的功能,即通过 facebook 和 github 进行身份验证)。只是 auth-server 项目中的index.html 有一个错误。如果你更正这个错误,那就是替换

$("#user").html(data.userAuthentication.details.name);

$("#user").html(data.name);

它也会运行良好。所有三个项目都会给出相同的输出。

【讨论】:

  • “错误”是什么意思?我想演示这个。我怎样才能实现它?
  • 真的没用
  • 我运行正确的项目。我的问题与 auth-server 项目有关
  • @gstackoverflow- 可以快速聊天吗?如果有空,请加入聊天室 chat.stackoverflow.com/rooms/170569/…
【解决方案3】:

我终于找到了问题所在。如果您在 localhost 上启动这两个应用程序,我看到这种行为是由于客户端和服务器的 cookie 发生冲突。

这是由于上下文使用了错误的属性而发生的。

所以要修复你需要替换的应用程序:

server:
  context-path: /client

server:  
  servlet:
    context-path: /client

附言

我在 github 上创建了问题:

https://github.com/spring-guides/tut-spring-boot-oauth2/issues/80

并提出拉取请求:

https://github.com/spring-guides/tut-spring-boot-oauth2/pull/81

附言2

最后我的拉取请求被合并了: https://github.com/spring-guides/tut-spring-boot-oauth2/pull/81

【讨论】:

    猜你喜欢
    • 2023-04-01
    • 2016-08-04
    • 2019-06-15
    • 2021-06-21
    • 2017-03-19
    • 2014-07-25
    • 1970-01-01
    • 2017-05-10
    相关资源
    最近更新 更多