Не удается заставить @Secured работать в Spring MVC

Я использую Spring MVC для предоставления услуг RESTful. Я уже включил аутентификацию через HTTPBasicAuthentication, и с помощью <security:http> я могу контролировать, какие роли могут получать доступ к URL-адресам.

Теперь я хочу использовать аннотацию @Secured. Я попытался добавить его в методы контроллера, но он не работает. Он просто ничего не делает.

Вот мой класс Controller:

@Controller
@RequestMapping("/*")
public class HomeController {
private static final Logger logger = LoggerFactory.getLogger(HomeController.class);

private static final String USERS = "/users";
private static final String USER = USERS+"/{userId:.*}";

    @RequestMapping(value=USER, method=RequestMethod.GET)
    @Secured(value = {"ROLE_ADMIN"})
    public @ResponseBody User signin(@PathVariable String userId) {
        logger.info("GET users/"+userId+" received");
        User user= service.getUser(userId);
        if(user==null)
                throw new ResourceNotFoundException();
        return user;
    }
}

Это мой security-context.xml:

<http auto-config='true'>
    <intercept-url pattern="/**" access="ROLE_USER"/>
</http>

<global-method-security secured-annotations="enabled" />

<authentication-manager>
    <authentication-provider>
        <user-service>
            <user name="[email protected]" password="admin"
                authorities="ROLE_USER, ROLE_ADMIN" />
            <user name="[email protected]" password="pswd"
                authorities="ROLE_USER" />
        </user-service>
    </authentication-provider>
</authentication-manager>

И мой root-context.xml:

<context:component-scan base-package="org.mypackage" />

<import resource="database/DataSource.xml"/> 

<import resource="database/Hibernate.xml"/>

<import resource="beans-context.xml"/> 

<import resource="security-context.xml"/> 

Все работает нормально, но если я добавлю @Secured, он просто ничего не сделает: я также могу получить доступ к защищенному методу с [email protected], который не имеет привилегий ROLE_ADMIN. Я уже пытался переместить <security:global-method-security> в root-context.xml, не получается. Я также пытался защитить тот же метод с помощью тега <security:http>, он отлично работает, но я хочу использовать аннотацию @Secured.

Спасибо.

EDIT: у меня также есть файлы конфигурации servlet-context.xml и controllers.xml в подкаталоге appServlet.

Вот servlet-context.xml:

<mvc:resources mapping="/resources/**" location="/resources/" />

<beans:bean class="org.springframework.web.servlet.view.InternalResourceViewResolver">
    <beans:property name="prefix" value="/WEB-INF/views/" />
    <beans:property name="suffix" value=".jsp" />
</beans:bean>

<beans:import resource="controllers.xml" />

И controllers.xml:

<context:component-scan base-package="org.mose.emergencyalert.controllers" />

<beans:bean id="multipartResolver" class="org.springframework.web.multipart.commons.CommonsMultipartResolver" />     

<beans:bean id="homeController" class="org.mose.emergencyalert.controllers.HomeController"/> 

person user1781028    schedule 21.01.2013    source источник
comment
почему у вас есть префикс security: для global-method-security, где authentication-manager нет?   -  person Arun P Johny    schedule 21.01.2013
comment
ошибка вырезания/вставки при перемещении тега из корневого контекста, извините. Однако все еще не работает.   -  person user1781028    schedule 21.01.2013
comment
Просто для ясности: вся ваша конфигурация находится в контексте корневого приложения или часть в контексте дочернего DispatcherServlet? Кроме того, ваш контроллер реализует какой-либо интерфейс?   -  person Eugen    schedule 21.01.2013
comment
попробуйте принудительно использовать прокси cglib: ‹global-method-security secure-annotations=enabled proxy-target-class=true /›   -  person Eugen    schedule 21.01.2013
comment
Я добавил определение класса контроллера, без реализации интерфейса. В подкаталоге appServlet у меня есть servlet-context.xml и controllers.xml. Может быть, мне нужно указать <global-method-security> в serlvet-context.xml?   -  person user1781028    schedule 21.01.2013
comment
Да у тебя есть. stackoverflow.com/questions/6651119/   -  person axtavt    schedule 21.01.2013


Ответы (2)


Решено, я добавил тег <global-method-security> в servlet-context.xml вместо security-context.xml.

Вот новый security-context.xml:

<annotation-driven />

<security:global-method-security secured-annotations="enabled"/>

<resources mapping="/resources/**" location="/resources/" />

<beans:bean class="org.springframework.web.servlet.view.InternalResourceViewResolver">
    <beans:property name="prefix" value="/WEB-INF/views/" />
    <beans:property name="suffix" value=".jsp" />
</beans:bean>

NB: теперь Eclipse предупреждает меня в строке <security:global-method-security>: "advises org.mypackage.HomeController.signin(String, Principal)", доказывая, что @Secured теперь работает.

person user1781028    schedule 21.01.2013
comment
Спасибо, забыл, что эти контексты разделены! - person Stefan; 17.04.2014

РЕШЕНО

Добавьте этот тег в свой файл конфигурации, содержащий конфигурацию ViewResolve: xml диспетчера НЕ в XML вашего приложения <security:global-method-security pre-post-annotations="enabled" secured annotations="enabled">

туто

person becher henchiri    schedule 10.06.2016