java Spring Boot 安全性 - 默认映射上的匿名用户访问 /

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/28465375/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-11-02 13:38:46  来源:igfitidea点击:

Spring Boot Security - Anonymous User access on default mapping /

javaspring-bootspring-security

提问by Kul Bhushan Prasad

We have Spring boot based Application and We wanted to give the default / mapping access to Anonymous user. we have added the default index.html(basic page).

我们有基于 Spring Boot 的应用程序,我们希望为匿名用户提供默认/映射访问权限。我们添加了默认index.html(基本页​​面)。

In Controller

在控制器中

@RequestMapping("/")
public ModelAndView defaultViewManager(HttpServletRequest request) {
    logger.info("Default mapping.");
    ModelAndView modelAndView = new ModelAndView("index");
    return modelAndView;
} 

SecurityConfig

安全配置

@Configuration
@EnableWebSecurity
public class SecurityConfig extends WebSecurityConfigurerAdapter {

private static final String SSO_HEADER = "AUTH_USER";

public static final String ADMIN = "ROLE_ADMIN";
public static final String USER = "ROLE_USER";
public static final String ANONYMOUS = "ROLE_ANONYMOUS";

@Autowired
private PreAuthUserDetailsService userDetailsService;

@Autowired
public void configureGlobal(AuthenticationManagerBuilder auth) throws Exception {
    auth.authenticationProvider(preAuthenticatedAuthProvider());
}

@Bean
public PreAuthenticatedAuthenticationProvider preAuthenticatedAuthProvider() {
    UserDetailsByNameServiceWrapper<PreAuthenticatedAuthenticationToken> wrapper =
            new UserDetailsByNameServiceWrapper<PreAuthenticatedAuthenticationToken>    (userDetailsService);

    PreAuthenticatedAuthenticationProvider authProvider = new PreAuthenticatedAuthenticationProvider();
    authProvider.setPreAuthenticatedUserDetailsService(wrapper);
    return authProvider;
}

@Bean
public RequestHeaderAuthenticationFilter headerAuthFilter() throws Exception {
    RequestHeaderAuthenticationFilter filter = new RequestHeaderAuthenticationFilter();
    filter.setPrincipalRequestHeader(SSO_HEADER);
    filter.setAuthenticationManager(authenticationManagerBean());
    return filter;
}

The above mentioned code probably not necessary, but for background, we are using a PreAuthenticatedAuthentication Provider

上面提到的代码可能不是必需的,但作为背景,我们使用的是 PreAuthenticatedAuthentication Provider

@Override
protected void configure(HttpSecurity http) throws Exception {

    // @formatter:off
    http.addFilter(headerAuthFilter())
        .authorizeRequests()
            .antMatchers("/").permitAll()
            .antMatchers("/admin/**").hasAuthority(ADMIN)
            .antMatchers("/**").hasAuthority(USER)

        .and()
            .logout()
                .deleteCookies("remove")
                .invalidateHttpSession(true)
                .logoutUrl("/logout")
                .logoutSuccessUrl("/login?logout")
        .and()
            .csrf().disable()
            .headers().frameOptions().disable();
    // @formatter:on
}
}

FYI, I have added the Interceptor too. The Interceptor appears to be triggered, even with the exclude pattern

仅供参考,我也添加了拦截器。即使使用排除模式,拦截器似乎也被触发

public void addInterceptors(InterceptorRegistry registry) {     
         registry.addInterceptor(wikiRequestHandlerInterceptor()).
excludePathPatterns("/").addPathPatterns("/**");   

}

In the above SecurityConfigcode. I tried to permit using .antMatchers("/").permitAll()and added Authority for rest means all /**and /admin/**. But this is not working. please help to mention correct antMatchers to provide the anonymous access to default /mapping only.

在上面的SecurityConfig代码中。我试图允许使用.antMatchers("/").permitAll()并添加权限休息意味着所有/**/admin/**。但这行不通。请帮助提及正确的 antMatchers 以仅提供对默认 /mapping 的匿名访问。

Thanks in Advance.

提前致谢。

回答by Tim

Looks like the antMatchers would need to be re-arranged to fix the precedence. To permit "all requests" at "/"first add anyRequest().permitAll(), then add the restricted directories, and finally the catch-all /**like so:

看起来 antMatchers 需要重新安排以修复优先级。要允许“所有请求”"/"首先添加anyRequest().permitAll(),然后添加受限目录,最后/**像这样添加所有请求:

http.addFilter(headerAuthFilter())
    .authorizeRequests()
    .anyRequest().permitAll()
    .antMatchers("/admin/**").hasAuthority(ADMIN)
    .antMatchers("/**").hasAuthority(USER)

A view controller can be setup to map directly to the indexroot.html in the template directory (assuming ThymeLeaf):

可以设置一个视图控制器直接映射到模板目录中的 indexroot.html(假设 ThymeLeaf):

public void addViewControllers(ViewControllerRegistry registry) {
    registry.addViewController("/").setViewName("indexroot");
}

I believe the interceptor can still be excluded with simply "/", in any order:

我相信拦截器仍然可以用简单的“/”以任何顺序排除:

public void addInterceptors(InterceptorRegistry registry) {
    registry.addInterceptor(wikiRequestHandlerInterceptor())
            .addPathPatterns("/admin/**")
            .excludePathPatterns("/");
}