【问题标题】:How to do Conditional Method chaining in Java 8如何在 Java 8 中进行条件方法链接
【发布时间】:2019-01-11 18:49:04
【问题描述】:

我有一个弹簧安全配置方法。我希望仅在条件匹配时才链接特定方法antMatchers("/**/**").permitAll()。像这样{dev == true ? .antMatchers("/**/**").permitAll(): ()->{}}。当然这不是一个有效的语法,最简洁的做法是什么。寻找最低限度的编码。

@Override
    protected void configure(HttpSecurity http) throws Exception {
        http
            .csrf().disable()
            .cors().disable()
            .authorizeRequests()
            {dev == true ? .antMatchers("/**/**").permitAll(): ()->{}} //dev only. NEVER enable on prod 
                .antMatchers("/", "/signup", "/static/**", "/api/sigin", "/api/signup", "**/favicon.ico").permitAll()
                .anyRequest().authenticated()
                .and()
            .formLogin()
                .loginPage("/")
                .loginProcessingUrl("/api/signin")
                .successHandler(authSuccessHandler())
                .failureHandler(authFailureHandler())
                .permitAll()
                .and()
            .logout()
                .permitAll();
    }

【问题讨论】:

  • 重新考虑在您的代码中设置一个关闭身份验证的标志。这是一场灾难性的等待。

标签: java spring-boot java-8 method-chaining


【解决方案1】:

唯一的方法是将中间对象分配给一个变量。

WhateverAuthorizeRequestsReturns partial = http
    .csrf().disable()
    .cors().disable()
    .authorizeRequests();

if (dev) // note: you don't need 'dev == true' like you had
{
    partial.someOptionalThing();
    // if the type is immutable then you need to reassign e.g.:
    // partial = partial.someOptionalThing()
}

partial.something()
    .somethingElse()
    .andTheRest();

【讨论】:

  • 嗯。好一个。如果有人能想出这个的内联版本,让我等一下。
【解决方案2】:

如果您只想允许基于布尔值访问特定路径,您可以试试这个:

 http
        .csrf().disable()
        .cors().disable()
        .authorizeRequests()
        .antMatchers(dev ? "/**/**":"invalid-path").permitAll()
            .antMatchers("/", "/signup", "/static/**", "/api/sigin", "/api/signup", "**/favicon.ico").permitAll()
            .anyRequest().authenticated()
            .and()
        .formLogin()
            .loginPage("/")
            .loginProcessingUrl("/api/signin")
            .successHandler(authSuccessHandler())
            .failureHandler(authFailureHandler())
            .permitAll()
            .and()
        .logout()
            .permitAll();

【讨论】:

    猜你喜欢
    • 2018-03-21
    • 1970-01-01
    • 1970-01-01
    • 2019-02-25
    • 1970-01-01
    • 2012-12-13
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多