@PreAuthorize无法正常工作。可能是什么问题?

【字号: 日期:2024-01-24浏览:53作者:雯心
如何解决@PreAuthorize无法正常工作。可能是什么问题??

要在您的Spring MVC控制器中使用基于注释的方法安全性,您需要在dispatcherServlet的上下文配置文件中设置以下内容。

<security:global-method-security pre-post-annotations='enabled' secured-annotations='enabled' />

似乎您将其放入其他配置文件中。

解决方法

有一个管理页面,我在该页面上使用@PreAuthorize了角色注释ROLE_ADMIN,但是没有该角色的用户也可以访问此页面。

此安全上下文文件

<?xml version='1.0' encoding='UTF-8'?><beans xmlns='http://www.springframework.org/schema/beans'xmlns:xsi='http://www.w3.org/2001/XMLSchema-instance' xmlns:security='http://www.springframework.org/schema/security'xmlns:p='http://www.springframework.org/schema/p'xsi:schemaLocation='http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans.xsd http://www.springframework.org/schema/security http://www.springframework.org/schema/security/spring-security-4.0.xsd'><security:global-method-security pre-post-annotations='enabled' secured-annotations='enabled' /><security:http auto-config='true' use-expressions='true'> <security:intercept-url pattern='/app/login'access='permitAll' /> <security:intercept-url pattern='/app/admin'access='hasRole(’ROLE_USER’) and over18' /> <security:intercept-url pattern='/app/**'access='hasRole(’ROLE_USER’)' /> <security:form-login login-page='/app/login'default-target-url='/app/base/' always-use-default-target='true'authentication-failure-url='/app/login?error=true' /> <security:logout delete-cookies='JSESSIONID'logout-success-url='/app/logout' /> <security:access-denied-handlererror-page='/app/User/error/403' /> <security:remember-me key='webapp-key' /> <security:expression-handler ref='expressionHandler' /></security:http><bean class='org.springframework.security.authentication.dao.DaoAuthenticationProvider'> <property name='userDetailsService' ref='userDetailsService'></property></bean><bean class='org.springframework.security.authentication.ProviderManager'> <constructor-arg><list> <ref bean='daoAuthenticationProvider' /></list> </constructor-arg></bean><security:authentication-manager> <security:authentication-provideruser-service-ref='userDetailsService'><security:password-encoder hash='md5'></security:password-encoder> </security:authentication-provider></security:authentication-manager></beans>

控制器是:

@Controller@RequestMapping('/admin')public class AdminController {@PreAuthorize('hasRole(’ROLE_ADMIN’)')@RequestMappingpublic String showAdminPage(){ return 'adminPage';}}

编辑:

flag

我添加了代码以签出用户和授予的权限,然后将它们打印出来。这是输出

*************************************** [ROLE_USER] uddeshya *************************************** forSystem.out.println('***************************************nnn'); System.out.println(SecurityContextHolder.getContext() .getAuthentication().getAuthorities()); System.out.println(principal.getName()); System.out.println('nnn***************************************');

相关文章: