如何在Java 8中进行条件方法链?

9
我有一个Spring Security配置方法。如果满足某个条件,我想将特定的方法链接到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();
    }

2
重新考虑在您的代码中设置关闭身份验证的标志。那是一场灾难等待发生。 - Boris the Spider
@sapy,这里有一个你可以考虑的替代方案:https://stackoverflow.com/a/74492221/511804 - Alexandr
2个回答

8
唯一的方法是将中间对象分配给一个变量。
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();

嗯,不错。让我等一下看看是否有人能提供内联版本。 - sapy

5

如果你只想基于布尔值允许对某些路径的访问,你可以尝试这样做:

 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();

如何在特定路由中实现 if env=prod denyAll() else permitAll() 的功能? - undefined

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接