gpt4 book ai didi

java - 如何防止Spring AuthenticationProvider对静态或图像资源执行?

转载 作者:太空宇宙 更新时间:2023-11-04 11:40:42 26 4
gpt4 key购买 nike

我有一个 java web Spring Boot 应用程序,带有一些自定义 Spring Sceurity 配置。当我运行我的应用程序时,图像正在执行 AuthenticationProvider,这导致我出现异常(因为我在用户首次登录时进行了一些更新)。

如何防止 AuthenticationProvider 在访问图像时运行?

我的配置如下:

@Order(1)
@Configuration
@EnableWebSecurity
public class BaseSecurityConfig extends WebSecurityConfigurerAdapter {

@Autowired
private AuthenticationEntryPoint restUnauthorizedEntryPoint;

@Autowired
private AccessDeniedHandler restAccessDeniedHandler;

@Override
public void configure(WebSecurity web) throws Exception {
LOG.info("Ignoring resources in Spring Security");
web.ignoring()
.antMatchers("/images/*")
.antMatchers("/app/errors/*.html");
}

@Override
public void configure(HttpSecurity http) throws SecurityConfigException {
try {
http
.antMatcher("/api/**")
.authorizeRequests()
.accessDecisionManager(accessDecisionManager())
.antMatchers("/api/users/**").hasAnyRole("ADMIN")
.anyRequest().authenticated()

.and()
.exceptionHandling()
.authenticationEntryPoint(restUnauthorizedEntryPoint)
.accessDeniedHandler(restAccessDeniedHandler)

.and()
.addFilterAfter(new CsrfHeaderFilter(), CsrfFilter.class)
.csrf().csrfTokenRepository(csrfTokenRepository())

.and()
.headers().frameOptions().sameOrigin()

.and();
} catch (Exception ex) {
throw new SecurityConfigException(ex);
}
}

@Bean
public AffirmativeBased accessDecisionManager() {
List<AccessDecisionVoter<? extends Object>> decisionVoters = new ArrayList<>();
decisionVoters.add(new WebExpressionVoter());
decisionVoters.add(new RoleHierarchyVoter(roleHierarchy()));
return new AffirmativeBased(decisionVoters);
}

/**
* Create the role hierarchy as an implementation of Spring Security {@link RoleHierarchyVoter} where the Spring
* roles are created from a combination of {@link Module}_{@link Role}. The AccessDecisionVoter provided with Spring
* Security expects the role names to begin with the prefix 'ROLE_'. The hierarchy is as follows:
* <p/>
* {@code ROLE_COMMON_ADMIN > ROLE_COMMON_USER_ADMIN } and {@code ROLE_COMMON_ADMIN > ROLE_CUSTOM_USER}
*/
@Bean
public RoleHierarchyImpl roleHierarchy() {
StringBuilder h = new StringBuilder();

// Common tree, root is COMMON_ADMIN
appendIncludesRule(h, Module.COMMON, Role.ADMIN, Module.COMMON, Role.USER_ADMIN);

// Custom tree, root is COMMON_ADMIN
appendIncludesRule(h, Module.COMMON, Role.ADMIN, Module.CUSTOM, Role.USER);

RoleHierarchyImpl roleHierarchy = new RoleHierarchyImpl();
roleHierarchy.setHierarchy(h.toString());
return roleHierarchy;
}

private void appendIncludesRule(StringBuilder h, Module lModule, Role lRole, Module rModule, Role rRole) {
h.append(GrantedAuthorityFactory.ROLE_PREFIX).append(lModule).append('_').append(lRole).append('>');
h.append(GrantedAuthorityFactory.ROLE_PREFIX).append(rModule).append('_').append(rRole).append(' ');
}

/**
* Creates a replacement CsrfTokenRepository for use by Spring CSRF protection. It looks for a header called
* X-XSRF-TOKEN, which AngularJS sets by default. AngularJS obtains this from the XSRF-TOKEN cookie (set in
* CsrfHeaderFilter).
*
* @return CsrfTokenRepository
*/
private CsrfTokenRepository csrfTokenRepository() {
HttpSessionCsrfTokenRepository repository = new HttpSessionCsrfTokenRepository();
repository.setHeaderName(CSRF_HEADER_NAME);
return repository;
}
}

第二个配置类:

@Configuration
@EnableWebSecurity
@EnableGlobalMethodSecurity(prePostEnabled = true)
@Profile({ "prod" })
public class UidSecurityConfig extends WebSecurityConfigurerAdapter {

@Autowired
private UserAccountService userAccountService;

@Override
public void configure(WebSecurity web) throws Exception {
LOG.info("Ignoring resources in Spring Security");
web.ignoring()
.antMatchers("/images/*")
.antMatchers("/app/errors/*.html");
}

@Override
public void configure(AuthenticationManagerBuilder auth) {
LOG.info("AuthenticationManagerBuilder: PreAuthenticatedAuthenticationProvider configured");
auth.authenticationProvider(preauthAuthProvider());
}

@Override
public void configure(HttpSecurity http) throws SecurityConfigException {
try {
http.addFilterBefore(ssoFilter(), RequestHeaderAuthenticationFilter.class);
http.headers().cacheControl().disable();
} catch (SecurityConfigException ex) {
LOG.error("SecurityConfigException:", ex);
throw ex;
} catch (Exception ex) {
LOG.error("SecurityConfigException:", ex);
throw new SecurityConfigException(ex);
}
}

@Bean
public PreAuthenticatedAuthenticationProvider preauthAuthProvider() {
PreAuthenticatedAuthenticationProvider preauthAuthProvider = new PreAuthenticatedAuthenticationProvider();
preauthAuthProvider.setPreAuthenticatedUserDetailsService(userDetailsServiceWrapper());
return preauthAuthProvider;
}

@Bean
public UserDetailsByNameServiceWrapper<PreAuthenticatedAuthenticationToken> userDetailsServiceWrapper() {
UserDetailsByNameServiceWrapper<PreAuthenticatedAuthenticationToken> wrapper = new UserDetailsByNameServiceWrapper<>();
wrapper.setUserDetailsService(userAccountService);
return wrapper;
}

@Bean
public SsoHeaderFilter ssoFilter() throws SecurityConfigException {
SsoHeaderFilter filter = new SsoHeaderFilter();
try {
filter.setAuthenticationManager(authenticationManager());
} catch (Exception ex) {
LOG.error("SsoHeaderFilter Excpetion:", ex);
throw new SecurityConfigException(ex);
}
return filter;
}
}

我真的不明白为什么即使在我将 Spring 配置为忽略所有/images/* 模式之后,AuthenticationProvider 仍会对图像执行。

如果我按 F5 主屏幕,我不会遇到异常(因为更新是在用户第一次访问应用程序时进行的),但身份验证提供程序似乎仍在运行。

编辑

图片路径:images/mylogo.png

最佳答案

我认为你的 antMatchers 可能有点不对劲。

尝试 /images/** 而不是 /images/*,对于静态页面尝试 /app/**/*.html

这是 JHipster 的示例。 CSS 和图像位于内容目录下:

@Override
public void configure(WebSecurity web) throws Exception {
web.ignoring()
.antMatchers(HttpMethod.OPTIONS, "/**")
.antMatchers("/app/**/*.{js,html}")
.antMatchers("/bower_components/**")
.antMatchers("/i18n/**")
.antMatchers("/content/**")
.antMatchers("/swagger-ui/index.html")
.antMatchers("/test/**");
}

关于java - 如何防止Spring AuthenticationProvider对静态或图像资源执行?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/42814306/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com