2015-03-10 3 views
1

Я использую Spring Boot 1.2.1 со встроенной системой безопасности Starcat и Spring Boot Starter Security. Кроме того, я использую RestController для некоторых веб-сервисов, и я хочу, чтобы только определенные пользователи с определенными ролями могли обращаться к веб-службам. Но это не работает, безопасность не использует RoleVoter для проверки ролей. В следующем примере пользователь «пользователь» может получить доступ к веб-сервисам, хотя у него нет правильных ролей!Весенняя загрузка со встроенным Tomcat игнорирует Роли метода

Первые мои настройки приложения

@Configuration 
@EnableJms 
@ImportResource("classpath:net/bull/javamelody/monitoring-spring.xml") 
@EnableAspectJAutoProxy 
@ComponentScan 
@PropertySource("classpath:application.properties") 
@EnableAutoConfiguration 
@EnableGlobalMethodSecurity(securedEnabled = true) 
public class ItemConfiguration { ... } 

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

@Configuration 
@EnableWebSecurity 
@Order(SecurityProperties.ACCESS_OVERRIDE_ORDER) 
public class SecurityConfig extends WebSecurityConfigurerAdapter { 

    @Override 
    protected void configure(AuthenticationManagerBuilder auth) throws Exception { 
    auth.inMemoryAuthentication().withUser("user").password("password").roles("USER"); 
    } 

    @Override 
    protected void configure(HttpSecurity http) throws Exception { 
    http.authorizeRequests().anyRequest().fullyAuthenticated(); 
    http.httpBasic(); 
    http.csrf().disable(); 
    } 
} 

Restcontroller

@RestController 
public class QueryController { 

    @Secured({ "ROLE_ADMIN" }) 
    @RequestMapping(value = "/", method = { POST }, consumes = { MediaType.APPLICATION_JSON_VALUE }, 
     produces = MediaType.APPLICATION_JSON_VALUE) 
    ResponseEntity< List<BaseEntity> > query(@RequestBody @Valid final ItemQueryRequestData request) 
     throws Exception { 
     return new ResponseEntity<>("", HttpStatus.OK); 
    } 
} 

application.properties

spring.data.mongodb.database = item 
spring.data.mongodb.host = ${MONGODB_URI:pimpoc01} 
spring.data.mongodb.port = ${MONGODB_PORT:27017} 

spring.activemq.broker-url=${BROKER_URL:tcp://pimpoc01:61616} 
spring.activemq.user= 
spring.activemq.password= 
spring.activemq.pooled=true 

queue.item.in.channelId = item-in 
queue.item.in.concurrentConsumers = 1 
queue.item.in.destination = item-in 

queue.itemOption.in.channelId = itemOption-in 
queue.itemOption.in.concurrentConsumers = 1 
queue.itemOption.in.destination = itemOption-in 

queue.style.in.channelId = style-in 
queue.style.in.concurrentConsumers = 1 
queue.style.in.destination = style-in 

queue.concurrentConsumers = 50 
queue.dataCreation.response = dataCreationResponse 

queue.structureAttributeValue.in.channelId = structureAttributeValue-in 
queue.structureAttributeValue.in.concurrentConsumers = 1 
queue.structureAttributeValue.in.destination = structureAttributeValue-in 

validation.endpoint = ${VALIDATOR_URI:http://pimpoc01:8080/validator} 

Спасибо за любую помощь!

+0

Можете ли вы опубликовать содержимое своего приложения.properties? Возможно, у вас есть собственность, которая вмешивается здесь. – dunni

+0

@ mathias-noack Любые удачи? – mhnagaoka

ответ

0

Удалите нижнюю строку из конфигурации безопасности. Я думаю, что аннотация @Order переопределяет базовую аутентификацию.

@Order(SecurityProperties.ACCESS_OVERRIDE_ORDER) 
+0

Я удалил его, но ничего не изменилось. Для решения, если пользователь может получить доступ к веб-сервису, он вызывает только «WebExpressionVoter» вместо «RoleVoter»! Только «RoleVoter» проверяет роли пользователя. –

+0

В этой документации - http://docs.spring.io/spring-boot/docs/current/reference/html/boot-features-security.html, если вы перейдете к концу страницы. Он говорит, что если Actuator используется, ** пользователь по умолчанию будет иметь роль ADMIN, а также роль USER. **. Я не полностью понимаю это утверждение, но не уверен, что это проблема. – Mithun

+0

Да, я читал это уже, но я не использую Actuator. Как вы можете видеть выше, я также не использую стандартного пользователя. У меня только один пользователь с ролью «ПОЛЬЗОВАТЕЛЬ», но все же он может получить доступ к веб-сервисам. –

0

я столкнулась с подобной проблемой, и решить, сделав мои методы контроллера общественности, т.е. сделать QueryController.querypublic метод.

Смежные вопросы