由于cookie冲突(授权代码机制)

时间:2018-04-20 13:20:47

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

根据教程Spring Boot and OAuth2

我有以下项目结构:

enter image description here

以下源代码:

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的结果:

enter image description here

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

更新

我从https://github.com/spring-guides/tut-spring-boot-oauth2

获取了此代码

重要的是:

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

P.S。

如何重现:

  

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

解答:

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

3 个答案:

答案 0 :(得分:15)

更新:2018年5月15日

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

Session ID replaced

更新:2018年5月10日

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

如果您查看manual repo和/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;
}

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

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

因此UI预期/user api返回的json响应没有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;
}

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

OAuth Success

原始答案

所以你从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;
}

在您当前,userdetails中的facebook未收集。这就是你看到错误的原因

Error

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

如果您运行正确的manual文件夹,则可以正常运行

Working

答案 1 :(得分:6)

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

ONE -

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

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

<强> TWO -

带有302状态代码的

/user 回复:

要了解发生这种情况的原因,请查看此应用程序的安全配置。

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

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

因此,未经过身份验证的任何请求都将重定向到身份验证入口点,即"/",要求用户进行身份验证。它不取决于您的客户端应用程序是否已启动。只要请求未经过身份验证,就会重定向到"/"。这就是弹簧控制器响应状态302的原因。一旦您使用 facebook github 进行身份验证,对"/user"终点的后续请求将成功响应200。

AND NEXT -

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

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

更新 - 回答您的问题

您在帖子中提供的存储库链接包含许多项目。项目 auth-server 手动 github 都相似(提供相同的功能,即使用facebook和github进行身份验证)。只有 auth-server 项目中的index.html有一个错误。如果你纠正了这个替换的错误

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

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

它也会正常运行。所有这三个项目都会给出相同的输出。

答案 2 :(得分:6)

最后我发现了问题。我看到这种行为是因为如果你在localhost上启动这两个应用程序,那么客户端和服务器会发生cookie冲突。

这是因为上下文使用了错误的属性。

因此,要修复应用程序,您需要替换:

server:
  context-path: /client

server:  
  servlet:
    context-path: /client

P.S。

我在github上创建了问题:

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

并提出拉取请求:

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

P.S.2

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