gpt4 book ai didi

spring-security-rest - 如何在使用 spring security 的 spring boot 应用程序中跳过对 HAL 浏览器的授权

转载 作者:行者123 更新时间:2023-12-05 05:08:33 33 4
gpt4 key购买 nike

我想让 HAL 浏览器跳过对 spring boot 应用程序的授权。我正在使用 Spring Security 进行授权。

这是 build.gradle 文件中条目的快照

 implementation 'org.springframework.boot:spring-boot-starter-data-rest'
implementation 'org.springframework.boot:spring-boot-starter-hateoas'
implementation 'org.springframework.boot:spring-boot-starter-validation'
implementation 'org.springframework.boot:spring-boot-starter-security'

我的 Spring Boot 应用程序在端口 2128 上运行

http://localhost:2128/browser/index.html会在 spring security 实现之前打开 HAL 浏览器。我尝试在下面给出的 SecurityConfiguration 类的配置方法中添加 .antMatchers("/browser/index.html").permitAll()** 。我还尝试覆盖 public void configure(WebSecurity web) 方法来忽略 URL

背景:HAL 浏览器在我实现 Spring Security 授权之前就可以正常工作。实现 spring security 后它停止工作。

        @Configuration        @EnableWebSecurity        public class SecurityConfiguration extends WebSecurityConfigurerAdapter {            @Override            protected void configure(AuthenticationManagerBuilder auth) throws Exception {                auth.authenticationProvider(daoAuthenticationProvider());            }            @Override            protected void configure(HttpSecurity http) throws Exception {                http                        .csrf().disable()                        .sessionManagement().sessionCreationPolicy(SessionCreationPolicy.STATELESS)                        .and()                        .addFilter(new AuthorizationFilter(authenticationManager(), userRepository))                        .authorizeRequests()                        // configure access rules                        .antMatchers("/browser/index.html**").permitAll()                        .anyRequest().authenticated();                http.headers().frameOptions().disable();            }            @Override            public void configure(WebSecurity web) throws Exception {                web.ignoring().antMatchers("/browser/index.html");            }        }     
        public class AuthorizationFilter extends BasicAuthenticationFilter {            public static final String HEADER_STRING_REMOTE_USER = "Remote-User";            /**             * Security pipe line is composed of different filters so we need to delegate to the rest of the pipeline.             *             * @param request             * @param response             * @param chain             * @throws IOException             * @throws ServletException             */            @Override            protected void doFilterInternal (HttpServletRequest request, HttpServletResponse response, FilterChain chain) throws IOException, ServletException {                // Read the Authorization header, where we get the userId                String userId = request.getHeader(HEADER_STRING_REMOTE_USER);                // If header does not contain userId or is null delegate to Spring impl and exit                if (userId == null) {                    chain.doFilter(request, response);                    return;                }                // If userId is present, try grab user principal from database and perform authorization                Authentication authentication = getUsernamePasswordAuthentication(userId);                SecurityContextHolder.getContext().setAuthentication(authentication);                // Continue filter execution                chain.doFilter(request, response);            }            private Authentication getUsernamePasswordAuthentication (String userId) {                // Search in the DB if we find the user by userId                // If so, then grab user details and create spring auth token using username, pass, authorities/roles                if (userId != null) {                    List user = userRepository.findByUserId(userId);                    UserPrincipal principal = new UserPrincipal(user.get(0));                    UsernamePasswordAuthenticationToken auth = new UsernamePasswordAuthenticationToken(principal, null, principal.getAuthorities());                    return auth;                }                return null;            }        }

有没有人遇到过类似的问题...

最佳答案

我最终做的是使用 spring 事件配置文件进行管理。

有关 Spring 型材的更多信息,请参阅 link

我为“安全”配置文件启用了 Spring Security,为“开发”配置文件禁用了它。因此,在“dev”配置文件中,HAL 浏览器可以在没有任何安全中断的情况下工作。

@Configuration
@EnableWebSecurity
@Profile("secure")
public class WebSecurityConfigEnable extends WebSecurityConfigurerAdapter {

@Autowired
UserPrincipalDetailsService userPrincipalDetailsService;

private UserRepository userRepository;

@Value("${spring.profiles.active}")
private String activeProfile;

public WebSecurityConfigEnable (UserPrincipalDetailsService
userPrincipalDetailsService, UserRepository userRepository) {
this.userPrincipalDetailsService = userPrincipalDetailsService;
this.userRepository = userRepository;
}

@Override
protected void configure (AuthenticationManagerBuilder auth) throws
Exception {
auth.authenticationProvider(daoAuthenticationProvider());
}

@Override
protected void configure (HttpSecurity http) throws Exception {
http
.cors().configurationSource(request -> new
CorsConfiguration().applyPermitDefaultValues())
.and()
.csrf().disable()

.sessionManagement().sessionCreationPolicy(SessionCreationPolicy.STATELESS)
.and()
.addFilter(new AuthorizationFilter(authenticationManager(),
userRepository, activeProfile))
.authorizeRequests()
// configure access rules
.anyRequest().authenticated();
}

@Bean
DaoAuthenticationProvider daoAuthenticationProvider () {
DaoAuthenticationProvider daoAuthenticationProvider = new DaoAuthenticationProvider();
daoAuthenticationProvider.setPasswordEncoder(this.passwordEncoder());
daoAuthenticationProvider.setUserDetailsService(this.userPrincipalDetailsService);

return daoAuthenticationProvider;
}

@Bean
PasswordEncoder passwordEncoder () {
return new BCryptPasswordEncoder();
}
}

用于在“开发”配置文件中运行应用程序

java -jar -Dspring.profiles.active=dev build\libs\springApp-0.1.1-SNAPSHOT.jar

关于spring-security-rest - 如何在使用 spring security 的 spring boot 应用程序中跳过对 HAL 浏览器的授权,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/58224608/

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