Приложение Spring Boot с приводом - PullRequest
1 голос
/ 21 марта 2019

У меня есть приложение SpringBoot. 2.1.3.Релиз, обеспеченный JWT, я хочу добавить привод. Я добавил эту зависимость

<dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-actuator</artifactId>
        </dependency> 

это мой configFile:

@Profile("api")
@Configuration
@EnableWebSecurity
@EnableGlobalMethodSecurity(prePostEnabled = true)
public class ApiWebSecurityConfig extends WebSecurityConfigurerAdapter {

    private static final Logger LOG = LoggerFactory.getLogger(ApiWebSecurityConfig.class);

    @Autowired
    private JwtAuthenticationEntryPoint unauthorizedHandler;

    @Autowired
    private JwtTokenUtil jwtTokenUtil;


    @Autowired
    private UserSecurityService userSecurityService;

    @Value("${jwt.header}")
    private String tokenHeader;


    @Value("${server.servlet.context-path}")
    private String serverContextPath;

    /** The encryption SALT. */
    private static final String SALT = "fd&eekj§sfs23#$1*(_)nof";


    @Autowired
    public void configureGlobal(AuthenticationManagerBuilder auth) throws Exception {
        auth
                .userDetailsService(userSecurityService)
                .passwordEncoder(passwordEncoder());
    }


    @Bean
    public BCryptPasswordEncoder passwordEncoder() {
        return new BCryptPasswordEncoder(12, new SecureRandom(SALT.getBytes()));
    }


    @Bean
    @Override
    public AuthenticationManager authenticationManagerBean() throws Exception {
        return super.authenticationManagerBean();
    }


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

         httpSecurity
         // we don't need CSRF because our token is invulnerable
         .csrf().disable()

         .exceptionHandling().authenticationEntryPoint(unauthorizedHandler).and()

         // don't create session
         .sessionManagement().sessionCreationPolicy(SessionCreationPolicy.STATELESS).and()
         .authorizeRequests()

         // Un-secure H2 Database
         .antMatchers("/h2-console/**/**").permitAll()
         .antMatchers("/auth/**").permitAll()
         .anyRequest().authenticated();


     // Custom JWT based security filter
         JwtAuthorizationTokenFilter authenticationTokenFilter = new JwtAuthorizationTokenFilter(userDetailsService(), jwtTokenUtil, tokenHeader);
         httpSecurity
             .addFilterBefore(authenticationTokenFilter, UsernamePasswordAuthenticationFilter.class);


     // disable page caching
     httpSecurity
         .headers()
         .frameOptions().sameOrigin()  // required to set for H2 else H2 Console will be blank.
         .cacheControl();
    }


    @Override
    public void configure(WebSecurity web) throws Exception {
        // AuthenticationTokenFilter will ignore the below paths
        web
            .ignoring()
            .antMatchers(
                HttpMethod.POST,
                "/auth"
            )

            .antMatchers(
                    HttpMethod.GET,
                    "/actuator"
                )


            .antMatchers(
                HttpMethod.POST,
                    "/reg"
            );
    }
}

но когда я получаю доступ в почтальоне к http://127.0.0.1:8080/myApp/actuator/

Я получил

{
    "timestamp": "2019-03-21T16:39:47.877+0000",
    "status": 401,
    "error": "Unauthorized",
    "message": "Unauthorized",
    "path": "/myApp/actuator/"
}

и HTTP Status 404 – Not Found

при доступе http://127.0.0.1:8080/actuator/

Ответы [ 2 ]

1 голос
/ 21 марта 2019

По умолчанию URL-адрес:

http://localhost:8080/actuator

попробуйте изменить конфигурацию с

        .antMatchers(
                HttpMethod.GET,
                "/actuator"
            )

до

        .antMatchers(
                HttpMethod.GET,
                "/actuator/**"
            )
0 голосов
/ 24 марта 2019

Привод пружинной загрузки содержит несколько конечных точек, которые включают состояние, показатели и т. Д.

Доступ к конечным точкам осуществляется следующим образом:

http://{baseUrl}/autuator/health

http://{baseUrl}/autuator/metrics

, поэтомуполучить все конечные точки - http://{baseUrl}/autuator/** [GET Request]

, чтобы разрешить доступ к этой конечной точке в конфигурации безопасности, измените конфигурацию с.

            .antMatchers(
                    HttpMethod.GET,
                    "/actuator"
                )

на

            .antMatchers(
                    HttpMethod.GET,
                    "/actuator/**"
                )
...