Spring Security 替换AuthorizationRequest后HttpSession为空

sbdsn5lh  于 5个月前  发布在  Spring
关注(0)|答案(2)|浏览(75)

问题是

DefaultOAuth2RequestFactory的自定义实现将当前的AuthorizationRequest替换为已保存的AuthorizationRequest后,HttpSession变为null。这会导致对/oauth/token的后续请求失败,因为/oauth/token端点之前的Spring Security过滤器链中的CsrfFilter无法在nullsessionrequestCsrf token进行比较。

出错时的控制流

下面的流程图说明了步骤14步骤15以某种方式null-ify HttpSession。(或者可能不匹配JSESSIONID。)在步骤14中,CustomOAuth2RequestFactory.java开始处的SYSO表明确实存在一个HttpSession,它实际上包含正确的CsrfToken。然而,不知何故,当步骤15触发从localhost:8080/login url的客户端返回localhost:9999/oauth/token端点的调用时,HttpSession已经变成了null
断点被添加到下面的调试日志中提到的HttpSessionSecurityContextRepository的每一行。(它位于authserver eclipse项目的Maven Dependencies文件夹中。)这些断点确认了在下面的流程图中对/oauth/token发出最终请求时,HttpSessionnull。(流程图左下角)nullHttpSession可能是由于自定义DefaultOAuth2RequestFactory代码运行后,保留在浏览器中的JSESSIONID过期。

如何修复此问题,以便在流程图中的步骤15结束后,在对/oauth/token端点的最后调用期间保持相同的HttpSession

x1c 0d1x的数据

相关代码和日志

我们可以猜测nullsession是由于1.)CustomOAuth2RequestFactory中的代码没有在浏览器中更新JSESSIONID,或者2.)HttpSession实际上被null-化了。
Sping Boot 调试日志在Step 15之后对/oauth/token的调用明确指出,到那时没有HttpSession,可以如下所示:

2016-05-30 15:33:42.630 DEBUG 13897 --- [io-9999-exec-10] o.s.security.web.FilterChainProxy        : /oauth/token at position 1 of 12 in additional filter chain; firing Filter: 'WebAsyncManagerIntegrationFilter'
2016-05-30 15:33:42.631 DEBUG 13897 --- [io-9999-exec-10] o.s.security.web.FilterChainProxy        : /oauth/token at position 2 of 12 in additional filter chain; firing Filter: 'SecurityContextPersistenceFilter'
2016-05-30 15:33:42.631 DEBUG 13897 --- [io-9999-exec-10] w.c.HttpSessionSecurityContextRepository : No HttpSession currently exists
2016-05-30 15:33:42.631 DEBUG 13897 --- [io-9999-exec-10] w.c.HttpSessionSecurityContextRepository : No SecurityContext was available from the HttpSession: null. A new one will be created.
2016-05-30 15:33:42.631 DEBUG 13897 --- [io-9999-exec-10] o.s.security.web.FilterChainProxy        : /oauth/token at position 3 of 12 in additional filter chain; firing Filter: 'HeaderWriterFilter'
2016-05-30 15:33:42.631 DEBUG 13897 --- [io-9999-exec-10] o.s.s.w.header.writers.HstsHeaderWriter  : Not injecting HSTS header since it did not match the requestMatcher org.springframework.security.web.header.writers.HstsHeaderWriter$SecureRequestMatcher@2fe29f4b
2016-05-30 15:33:42.631 DEBUG 13897 --- [io-9999-exec-10] o.s.security.web.FilterChainProxy        : /oauth/token at position 4 of 12 in additional filter chain; firing Filter: 'CsrfFilter'
2016-05-30 15:33:42.644 DEBUG 13897 --- [io-9999-exec-10] o.s.security.web.csrf.CsrfFilter         : Invalid CSRF token found for http://localhost:9999/uaa/oauth/token
2016-05-30 15:33:42.644 DEBUG 13897 --- [io-9999-exec-10] w.c.HttpSessionSecurityContextRepository : SecurityContext is empty or contents are anonymous - context will not be stored in HttpSession.
2016-05-30 15:33:42.644 DEBUG 13897 --- [io-9999-exec-10] s.s.w.c.SecurityContextPersistenceFilter : SecurityContextHolder now cleared, as request processing completed

字符串

在您的计算机上重现问题

您可以通过以下简单的步骤在任何计算机上重现问题:
1.下载该应用程序的压缩版本(编者注:不幸的是,这不再可用)。
1.通过键入以下内容解压缩应用程序:tar -zxvf oauth2.tar(4).gz
1.通过导航到oauth2/authserver,然后键入mvn spring-boot:run,启动authserver应用程序。
1.导航到oauth2/resource,然后键入mvn spring-boot:run,启动resource应用程序
1.导航到oauth2/ui,然后键入mvn spring-boot:run,启动ui应用程序
1.打开Web浏览器并导航到http : // localhost : 8080
1.单击Login,然后输入Frodo作为用户,MyRing作为密码,然后单击提交。
1.输入Pin Code作为Pin Code,然后单击提交。这将触发上面显示的错误。

Sping Boot 调试日志会显示大量的SYSO,它给出了流程图中每个步骤的XSRF-TOKENHttpSession等变量的值SYSO帮助分割调试日志,以便更容易解释。并且所有的SYSO都是由一个类调用其他类来完成的,因此,您可以操纵SYSO生成类来更改控制流中任何地方的报告。SYSO生成类的名称是TestHTTP,其源代码可以在同一个demo包中找到。

使用调试器

1.选择正在运行authserver应用程序的终端窗口,然后键入Ctrl-C以停止authserver应用程序。
1.将三个应用程序(authserverresourceui)作为现有maven项目导入eclipse。
1.在authserver应用的eclipse Project Explorer中,单击展开**Maven Dependencies文件夹**,然后向下滚动,单击以展开**Spring-Security-web... jar**如下图中以橙子圈出的。然后滚动以查找并展开org.springframework.security.web.context包。然后双击以打开在屏幕截图中以蓝色突出显示的HttpSessionSecurityContextRepository类下面。在这个类中的每一行添加断点。你可能想对同一个包中的SecurityContextPersistenceFilter类做同样的事情。这些断点将使你能够看到HttpSession的值,在控制流结束之前,它目前变成了null,但是需要具有可以Map到XSRF-TOKEN的有效值,以便解析此OP。



1.在应用程序的demo包中,在CustomOAuth2RequestFactory.java中添加断点。然后Debug As... Spring Boot App启动调试器。
1.然后重复上面的步骤6到8。您可能希望在每次新尝试之前清除浏览器的缓存。您可能希望打开浏览器开发人员工具的网络选项卡。

4ktjp1zp

4ktjp1zp1#

在最后一次调用localhost :9999/uaa/oauth/token时,您的authserver应用中的会话不为空不仅存在会话,而且有效会话的JSESSIONIDcsrf令牌匹配控制流中存在的值,该值位于用户提交正确pin的点和向/oauth/token发出失败请求的点之间。

问题是有两个JSESSIONID值,并且选择了两个值中的错误值来进入对/oauth/token的调用。因此,解决方案应该来自修改过滤器以删除坏的JSESSIONID,以便可以发送正确的值。
下文将进行总结:

HttpSessionListener标识了有效的JSESSIONID

为了隔离这个问题,我创建了一个HttpSessionListener的实现,然后从HttpLListener的自定义实现调用它,如下所示:

public class HttpSessionCollector implements HttpSessionListener, ServletContextListener {

    private static final Set<HttpSession> sessions = ConcurrentHashMap.newKeySet();

    public void sessionCreated(HttpSessionEvent event) {
        sessions.add(event.getSession());
    }

    public void sessionDestroyed(HttpSessionEvent event) {
        sessions.remove(event.getSession());
    }

    public static Set<HttpSession> getSessions() {
        return sessions;
    }

    public void contextCreated(ServletContextEvent event) {
        event.getServletContext().setAttribute("HttpSessionCollector.instance", this);
    }

    public static HttpSessionCollector getCurrentInstance(ServletContext context) {
        return (HttpSessionCollector) context.getAttribute("HttpSessionCollector.instance");
    }

    @Override
    public void contextDestroyed(ServletContextEvent arg0) {
    }

    @Override
    public void contextInitialized(ServletContextEvent arg0) {
    }

}

字符串
然后,我在OncePerRequestFilter的自定义实现中调用了上述HttpSessionListener,并将其插入到authserver应用程序的Spring Security Filter Chain中以提供诊断信息,如下所示:

@Component
public class DiagnoseSessionFilter extends OncePerRequestFilter implements ServletContextAware {

    @Override
    protected void doFilterInternal(HttpServletRequest req, HttpServletResponse res, FilterChain fc) throws ServletException, IOException {

    System.out.println("...........///////////// START OF DiagnoseSessionFilter.doFilterInternal() ///////////...........");
    //start of request stuff
    System.out.println("\\\\\\\\\\ REQUEST ATTRIBUTES ARE: ");
    if(req.getAttribute("_csrf")!=null){
        System.out.println("_csrf is: " + req.getAttribute("_csrf").toString());
    }
    if(req.getAttribute("org.springframework.security.web.csrf.CsrfToken")!=null){
        CsrfToken ucsrf = (CsrfToken) req.getAttribute("org.springframework.security.web.csrf.CsrfToken");
        System.out.println("ucsrf.getToken() is: " + ucsrf.getToken());
    }
    String reqXSRF = req.getHeader("XSRF-TOKEN");
    System.out.println("request XSRF-TOKEN header is: " + reqXSRF);
    String reqCookie = req.getHeader("Cookie");
    System.out.println("request Cookie header is: " + reqCookie);
    String reqSetCookie = req.getHeader("Set-Cookie");
    System.out.println("request Set-Cookie header is: " + reqSetCookie);
    String reqReferrer = req.getHeader("referrer");
    System.out.println("request referrer header is: " + reqReferrer);
    HttpSession rsess = req.getSession(false);
    System.out.println("request.getSession(false) is: " + rsess);
    if(rsess!=null){
        String sessid = rsess.getId();
        System.out.println("session.getId() is: "+sessid);
    }
    System.out.println("/////////// END OF REQUEST ATTRIBUTES ");

    //end of request stuff
    ServletContext servletContext = req.getServletContext();
    System.out.println("\\\\\\\\\\ START OF SESSION COLLECTOR STUFF ");

    HttpSessionCollector collector = HttpSessionCollector.getCurrentInstance(servletContext);
    Set<HttpSession> sessions = collector.getSessions();

    System.out.println("sessions.size() is: " + sessions.size());
    for(HttpSession sess : sessions){
        System.out.println("sess is: " + sess);
        System.out.println("sess.getId() is: " + sess.getId());
        CsrfToken sessCsrf = (CsrfToken) sess.getAttribute("org.springframework.security.web.csrf.HttpSessionCsrfTokenRepository.CSRF_TOKEN");
        System.out.println("csrf is: " + sessCsrf);
        if(sessCsrf!=null){
            if(sessCsrf.getToken()!=null){
                System.out.println("sessCsrf.getToken() is: " + sessCsrf.getToken());
            } else { System.out.println("sessCsrf.getToken() is: null "); }
        } else { System.out.println("sessCsrf is: null "); }

        System.out.println("sess.getAttribute(SPRING_SECURITY_SAVED_REQUEST) is: " + sess.getAttribute("SPRING_SECURITY_SAVED_REQUEST") );
        if(sess.getAttribute("SPRING_SECURITY_SAVED_REQUEST") instanceof DefaultSavedRequest){
            System.out.println("_____ START PRINTING SAVED REQUEST");
            DefaultSavedRequest savedReq = (DefaultSavedRequest) sess.getAttribute("SPRING_SECURITY_SAVED_REQUEST");
            List<Cookie> savedCookies = savedReq.getCookies();
            for(Cookie cook : savedCookies){
                String name = cook.getName();String value = cook.getValue();
                System.out.println("cookie name, value are: " + name + " , " + value);
            }
            Collection<String> savedHeaderNames = savedReq.getHeaderNames();
            for(String headerName : savedHeaderNames){
                System.out.println("headerName is: " + headerName);
            }
            List<Locale> savedLocales = savedReq.getLocales();
            for(Locale loc : savedLocales){
                System.out.println("loc.getLanguage() is: " + loc.getLanguage());
            }
            String savedMethod = savedReq.getMethod();
            System.out.println("savedMethod is: " + savedMethod);
            Map<String, String[]> savedParamMap = savedReq.getParameterMap();
            Iterator<Entry<String, String[]>> it = savedParamMap.entrySet().iterator();
            while (it.hasNext()) {
                Entry<String, String[]> pair = it.next();
                System.out.println("savedParamMap: " + pair.getKey() + " = " + pair.getValue());
                it.remove(); // avoids a ConcurrentModificationException
            }
            Collection<String> savedParamNames = savedReq.getParameterNames();
            for(String savedParamName : savedParamNames){
                System.out.println("savedParamName: " + savedParamNames);
            }
            System.out.println("_____ DONE PRINTING SAVED REQUEST");

        }

//      System.out.println("sess.getAttribute(SPRING_SECURITY_CONTEXT) is: " + sess.getAttribute("SPRING_SECURITY_CONTEXT") );
        if(sess.getAttribute("SPRING_SECURITY_CONTEXT") instanceof SecurityContextImpl){
            SecurityContext ctxt = (SecurityContext) sess.getAttribute("SPRING_SECURITY_CONTEXT");
            Authentication auth = ctxt.getAuthentication();

            if(auth.getDetails() instanceof WebAuthenticationDetails){
                WebAuthenticationDetails dets = (WebAuthenticationDetails) auth.getDetails();
                System.out.println( "dets.getSessionId() is: " + dets.getSessionId() );
            }
            System.out.println("auth.getAuthorities() is: " + auth.getAuthorities() );
            System.out.println("auth.isAuthenticated() is: " + auth.isAuthenticated() );
        }
    }

    SecurityContext context = SecurityContextHolder.getContext();
    System.out.println("...........///////////// END OF DiagnoseSessionFilter.doFilterInternal() ///////////...........");
    fc.doFilter(req, res);

    }
}

隔离问题代码:

下面结合并总结了来自HttpSessionListener和web浏览器的开发者工具的诊断数据,这些诊断数据是从用户在提交pin代码视图上单击提交到浏览器从/oauth/token端点返回拒绝之间的步骤。
正如你所看到的,**有两个JSESSIONID值在浮动。其中一个值是正确的,而另一个值是错误的。**错误的值被传递到/oauth/token的请求中,并导致拒绝,即使传递的csrf是正确的。因此,这个问题的解决方案可能来自改变下面的步骤,以停止将坏JSESSIONID放置在好JSESSIONID的位置:

1.) POST http://localhost:9999/uaa/secure/two_factor_authentication
    request headers:
        Referer: 9999/uaa/secure/two_factor_authentication
        Cookie: 
            JSESSIONID: ....95CB77     
                        ....918636
            XSRF-TOKEN: ....862a73
    filter chain:
        DiagnoseSessionFilter:
            request stuff:
                Cookie header:
                    JSESSIONID: ....95CB77
                                ....918636
                    XSRF-TOKEN: ....862a73
                request.getSession(false).getId(): ....95CB77
            session collector stuff:
                JSESSIONID: ....95CB77
                csrf: ....862a73
                SPRING_SECURITY_SAVED_REQUEST is null
            user details (from Authentication object with user/request
                JSESSIONID: ....ED927C
                Authenticated = true, with roles
        Complete the filter chain
        DiagnoseSessionFilter (again)
            request stuff:
                csrf attribute: ....862a73
                Cookie header: 
                    JSESSIONID: ....95CB77 
                                ....918636
                    XSRF-TOKEN: ....862a73
                request.getSession(false).getId(): 95CB77
            session collector stuff:
                JSESSIONID: ....95CB77
                csrf is: 862a73
                SPRING_SECURITY_SAVED_REQUEST is null
            user details (Authentication for user/session/request)
                JSESSIONID: ....ED927C
                Authenticated = true, with authorities
        POST/secure/two_factor_authenticationControllerMethod
            do some stuff
    response:
        Location: 9999/uaa/oauth/authorize?....
        XSRF-TOKEN: ....862a73

2.) GET http://localhost:9999/uaa/oauth/authorize?...
    request headers:
        Host: localhost:9999
        Referer: 9999/uaa/secure/two_factor_authentication
        Cookie: 
            JSESSIONID: ....95CB77    
                        ....918636
            XSRF-TOKEN: ....862a73
    FilterChain
        DiagnoseSessionFilter
            request stuff:
                Cookie header is: JSESSIONID: ....95CB77
                                              ....918636
                                  XSRF-TOKEN: ....862a73
                request.getSession(false).getId(): 95CB77
            session collector stuff: 
                JSESSIONID: ....95CB77
                csrf is: ....862a73
                SPRING_SECURITY_SAVED_REQUEST is: null
            user details (Authentication object with user/session/req)
                JSESSIONID: ....ED927C
                Authenticated = true with ALL roles.
        rest of filter chain
        TwoFactorAuthenticationFilter
            request stuff:
                csrf request attribute is: ....862a73
                cookie header:
                    JSESSIONID: ....95CB77
                                ....918636
                    XSRF-TOKEN: ....862a73
                request.getSession(false).getId() is: ....95CB77
                updateCsrf is: ....862a73
            response stuff:
                XSRF-TOKEN header (after manual update): ....862a73
        DiagnoseSessionFilter:
            request stuff:
                _csrf request attribute: ....862a73
                Cookie header:
                    JSESSIONID: ....95CB77
                                ....918636
                    XSRF-TOKEN: ....862a73
                    request.getSession(false).getId() is: ....95CB77
            session collector stuff: 
                JSESSIONID: ....95CB77
                csrf is: ....862a73
                SPRING_SECURITY_SAVED_REQUEST is: null
            user details (Authentication for user/session/request) 
                JSESSIONID: ....ED927C
                Authenticated is true, with ALL roles.
        CustomOAuth2RequestFactory
            request stuff:  
                _csrf request parameter is: ....862a73
                Cookie header: 
                    JSESSIONID: ....95CB77
                                ....918636
                    XSRF-TOKEN: ....862a73
                request.getSession(false).getId() is: ....95CB77
                updateCsrf: ....862a73
            response stuff:
                XSRF-TOKEN header: ....862a73
            session attribute printout
                csrf: ....862a73
                SPRING_SECURITY_CONTEXT (not printed, so don't know values)
    response:
        Location: 8080/login?code=myNwd7&state=f6b3Km
        XSRF-TOKEN: ....862a73

3.) GET http://localhost:8080/login?code=myNwd7&state=f6b3Km
    request headers:
        Host: localhost:8080
        Referer: 9999/uaa/secure/two_factor_authentication
        Cookie:  
            JSESSIONID: ....918636
            XSRF-TOKEN: ....862a73
    UiAppFilterChain:
        HttpSessionSecurityContextRepository
            creates new SPRING_SECURITY_CONTEXT to replace null one
        OAuth2ClientAuthenticationProcessingFilter (position 8 of 14)
            AuthorizationCodeAccessTokenProvider
                Retrieving token from 9999/uaa/oauth/token
    AuthServerFilterChain:
        DiagnoseSessionFilter
            request stuff:
                XSRF-TOKEN header is: null
                Cookie header is: null
                Set-Cookie header is: null
                referrer header is: null
                request.getSession(false) is: null
            session collector stuff:
                JSESSIONID: ....95CB77
                sessCsrf.getToken() is: 862a73
                SPRING_SECURITY_SAVED_REQUEST is: null
                Authenticated is true but with ONLY these roles: 
                    ROLE_HOBBIT, ROLE_TWO_FACTOR_AUTHENTICATION_ENABLED
            SecurityContextPersistenceFilter
                reports no HttpSession and no SPRING_SECURITY_CONTEXT
            CsrfFilter
                rejects request to /oauth/token due to no session % csrf

    response headers:
        Set-Cookie: 
            XSRF-TOKEN: ....527fbe
            X-Frame-Options: DENY


考虑到你提供的要点,我将尝试花更多的时间来进一步隔离解决方案。但是上面的内容应该会大大缩小问题的范围。
我在它完全完成之前发布这个,因为你的赏金期限即将到期。

vojdkbi0

vojdkbi02#

你的问题解决了吗?我一直在寻找2FA和spring-security-oauth2的完整示例。很高兴你已经发布了完整的概念和完整的源代码。
我试过你的软件包,你的问题可以简单地通过改变你的AuthserverApplication.java中的一行代码来解决。

@Override
    protected void configure(HttpSecurity http) throws Exception {
        // @formatter:off
        http
            .formLogin().loginPage("/login").permitAll()
        .and()
                .requestMatchers().antMatchers("/login", "/oauth/authorize", "/secure/two_factor_authentication", "/pincode")
        .and()
                .authorizeRequests().anyRequest().authenticated();
        // @formatter:on
    }

字符串
您的原始配置通过了Spring Security的身份验证链,该链返回了一个null身份验证对象。
我还建议您将CustomOAuth 2 RequestFactory的Bean创建更改为以下内容,以覆盖链中的所有OAuth2 RequestFactory

@Bean
    public OAuth2RequestFactory customOAuth2RequestFactory(){
        return new CustomOAuth2RequestFactory(clientDetailsService);
    }


对于您添加的用于处理CSRF的代码,您可以简单地删除它们,例如2FA控制器:

@Controller
@RequestMapping(TwoFactorAuthenticationController.PATH)
public class TwoFactorAuthenticationController {
    private static final Logger LOG = LoggerFactory.getLogger(TwoFactorAuthenticationController.class);
    public static final String PATH = "/secure/two_factor_authentication";
    public static final String AUTHORIZE_PATH = "/oauth/authorize";
    public static final String ROLE_TWO_FACTOR_AUTHENTICATED = "ROLE_TWO_FACTOR_AUTHENTICATED";

    private RedirectStrategy redirectStrategy = new DefaultRedirectStrategy();

    @RequestMapping(method = RequestMethod.GET)
    public String auth(HttpServletRequest request, HttpSession session, HttpServletResponse resp/*, ....*/) {
        System.out.println("-------- inside GET /secure/two_factor_authentication --------------");
        if (AuthenticationUtil.isAuthenticatedWithAuthority(ROLE_TWO_FACTOR_AUTHENTICATED)) {
            LOG.info("User {} already has {} authority - no need to enter code again", ROLE_TWO_FACTOR_AUTHENTICATED);
//            throw ....;
        }
        else if (session.getAttribute(CustomOAuth2RequestFactory.SAVED_AUTHORIZATION_REQUEST_SESSION_ATTRIBUTE_NAME) == null) {
//            LOG.warn("Error while entering 2FA code - attribute {} not found in session.", CustomOAuth2RequestFactory.SAVED_AUTHORIZATION_REQUEST_SESSION_ATTRIBUTE_NAME);
//          throw ....;
        }
        return "pinCode";
    }

    @RequestMapping(method = RequestMethod.POST)
    public String auth(FormData formData, HttpServletRequest req, HttpServletResponse resp,
                                            SessionStatus sessionStatus, Principal principal, Model model)
        throws IOException{

        if (formData.getPinVal()!=null) {
            if(formData.getPinVal().equals("5309")){
                AuthenticationUtil.addAuthority(ROLE_TWO_FACTOR_AUTHENTICATED);
                return "redirect:"+AUTHORIZE_PATH;
            };
        };

        return "pinCode";
    }
}


请让我知道如果你想要一个完整的源代码后清理。

相关问题