Spring security rest 如何在使用spring security的spring引导应用程序中跳过HAL浏览器的授权

Spring security rest 如何在使用spring security的spring引导应用程序中跳过HAL浏览器的授权,spring-security-rest,Spring Security Rest,我想允许HAL浏览器跳过spring启动应用程序的授权。我正在使用Spring Security进行授权 下面是build.gradle文件中条目的快照 implementation 'org.springframework.boot:spring-boot-starter-data-rest' implementation 'org.springframework.boot:spring-boot-starter-hateoas' implementation 'org.springfr

我想允许HAL浏览器跳过spring启动应用程序的授权。我正在使用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上运行

将在实施spring security之前打开HAL浏览器。 我尝试在下面给出的SecurityConfiguration类的configure方法中添加.antMatchers(“/browser/index.html”).permitAll()。我还尝试重写public void configure(WebSecurity web)方法来忽略URL

背景:在我实施Spring安全授权之前,HAL浏览器正在工作。它在spring安全性实现后停止工作

@配置 @启用Web安全性 公共类安全配置扩展了WebSecurity配置适配器{ @凌驾 受保护的无效配置(AuthenticationManagerBuilder auth)引发异常{ auth.authenticationProvider(daoAuthenticationProvider()); } @凌驾 受保护的无效配置(HttpSecurity http)引发异常{ http .csrf().disable() .sessionManagement().sessionCreationPolicy(sessionCreationPolicy.STATELESS) .及() .addFilter(新的AuthorizationFilter(authenticationManager(),userRepository)) .授权请求() //配置访问规则 .antMatchers(“/browser/index.html**”).permitAll() .anyRequest().authenticated(); http.headers().frameOptions().disable(); } @凌驾 public void configure(WebSecurity web)引发异常{ 忽略().antMatchers(“/browser/index.html”); } } 公共类授权筛选器扩展了基本身份验证筛选器{ 公共静态最终字符串头\u String\u REMOTE\u USER=“REMOTE USER”; /** *安全管道由不同的过滤器组成,因此我们需要将其委托给管道的其余部分。 * *@param请求 *@param响应 *@param链 *@抛出异常 *@ServletException */ @凌驾 受保护的void doFilterInternal(HttpServletRequest请求、HttpServletResponse响应、FilterChain链)引发IOException、ServletException{ //读取授权标头,从中获取用户ID String userId=request.getHeader(HEADER\u String\u REMOTE\u USER); //若标题不包含userId或为null,则委托Spring impl并退出 if(userId==null){ 链式过滤器(请求、响应); 返回; } //若存在userId,请尝试从数据库中获取用户主体并执行授权 身份验证=getUsernamePasswordAuthentication(userId); SecurityContextHolder.getContext().setAuthentication(身份验证); //继续执行筛选器 链式过滤器(请求、响应); } 私有身份验证getUsernamePasswordAuthentication(字符串用户ID){ //如果我们通过userId找到用户,则在数据库中进行搜索 //如果是这样,那么获取用户详细信息并使用用户名、密码、权限/角色创建spring身份验证令牌 if(userId!=null){ List user=userRepository.findByUserId(userId); UserPrincipal=newuserprincipal(user.get(0)); UsernamePasswordAuthenticationToken auth=新的UsernamePasswordAuthenticationToken(主体,null,主体.getAuthories()); 返回auth; } 返回null; } }
有没有人遇到过类似的问题…

我最后做的是使用spring活动配置文件进行管理

有关弹簧轮廓的更多信息,请参见

我为“安全”配置文件启用了Spring安全性,并为“开发”配置文件禁用了它。因此,在“开发”配置文件中,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();
}
}
用于在“dev”配置文件中运行应用程序


您是否尝试过
.antMatchers(“/browser/**”).permitAll()
?。除了index.html(js、css、图像)之外,还需要更多的资源。当然,对于api调用,您需要auth,因此您要么需要会话cookie,要么可以在hal资源管理器中指定授权头(如果使用)。PS:如果您使用新的hal浏览器而不是hal浏览器,请使用
.antMatchers(“/explorer/**”).permitAll()
是的,我一开始就试过了。它会给SecurityManager生成的防火墙请求带来问题,但这是最好的方法吗?? 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; } }
@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