Как пропустить авторизацию для браузера HAL в приложении весенней загрузки, использующем Spring Security - PullRequest
0 голосов
/ 03 октября 2019

Я хотел позволить браузеру HAL пропускать авторизацию в приложении с весенней загрузкой. Я использую 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 работает на порту 2128

http://localhost:2128/browser/index.html откроет браузер HAL до реализации весенней защиты. Я попытался добавить .antMatchers ("/ browser / index.html "). AllowAll () ** в методе настройки класса SecurityConfiguration, указанном ниже. Я также попытался переопределить метод public void configure (WebSecurity web) , чтобы игнорировать URL

Фон : HAL Browser работал до того, как я внедрил Spring Security Authorization,Он перестал работать после того, как была введена весенняя безопасность.



        @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;
            }
        }

Кто-нибудь сталкивался с подобными проблемами ...

1 Ответ

0 голосов
/ 12 октября 2019

Я закончил тем, что управлял с помощью активных профилей пружины.

Для получения дополнительной информации о профилях пружины см. Ссылку

. Я включил Spring Security для "secure"msgstr "профиль и отключил его для профиля" dev ". Таким образом, в профиле "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();
}
}

Для запуска приложения в профиле "dev"

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