java在Spring security中使用@PreAuthorize和角色和权限
我正在对用户、角色、正确的实体使用spring安全性,并且用户已成功通过身份验证,我可以访问其权限集合
我使用AJAX调用视图页面,并在前端和后端之间发送json。问题是,我不知道如何配置我的spring安全文件,因为@PreAuthorize注释不起作用。加载应用程序时会显示“我的登录”页面,如果控制器以json格式发送的凭据不正确,则会重定向到“登录”页面。如果你能帮我解决这个问题,我将不胜感激
@PreAuthorize("hasRole('ROLE_RIGHT_READ_USER_LIST')")
// @Secured("ROLE_RIGHT_READ_USER_LIST")
@RequestMapping(value = "/findAll", method = RequestMethod.GET, produces = {"application/json"})
@ResponseBody
public String findAll(HttpServletRequest request) {
以下是我的spring安全文件内容:
<?xml version="1.0" encoding="UTF-8"?>
<beans:beans xmlns="http://www.springframework.org/schema/security"
xmlns:beans="http://www.springframework.org/schema/beans"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans-3.2.xsd
http://www.springframework.org/schema/security http://www.springframework.org/schema/security/spring-security-3.2.xsd">
<global-method-security pre-post-annotations="enabled" secured-annotations="enabled"/>
<http auto-config="true" use-expressions="true">
<intercept-url pattern="/user/findAll/" access="hasRole('ROLE_RIGHT_READ_USER_LIST')" />
</http>
<beans:bean id="jdbcAuthenticationProvider" class="com.my.app.spring.JdbcAuthenticationProvider"/>
<authentication-manager>
<authentication-provider ref="jdbcAuthenticationProvider"/>
</authentication-manager>
</beans:beans>
这是我的控制器:
@Controller
@RequestMapping("/auth")
public class SecurityHandler extends AbstractHandler {
@Autowired
protected UserService userService;
@Resource(name = "authenticationProvider")
AuthenticationProvider authenticationProvider;
@RequestMapping(value = "/login", method = RequestMethod.POST, produces = {"application/json"})
@ResponseBody
public String logon(
@RequestParam(value = "username", required = true) String username,
@RequestParam(value = "password", required = true) String password,
HttpServletRequest request) {
Authentication req = new UsernamePasswordAuthenticationToken( username, password );
Authentication result = authenticationProvider.authenticate( req );
SecurityContextHolder.getContext().setAuthentication( result );
UserDetails userDetails=null;
Authentication auth = SecurityContextHolder.getContext().getAuthentication();
if (!(auth instanceof AnonymousAuthenticationToken)) {
userDetails
= (UserDetails) SecurityContextHolder.getContext().getAuthentication().getPrincipal();
}
User user = (User)userDetails;
Collection<? extends GrantedAuthority> ga = userDetails.getAuthorities();
HttpSession session = request.getSession(true);
session.setAttribute(SESSION_ATTRIB_USER, user);
return getJsonSuccessData(user);
} else {
return getJsonErrorMsg(ar.getMsg());
}
}
# 1 楼答案
好的,我真的不知道您是如何配置您的上下文的,但是,我将在这里粘贴一个我正在使用的基于Java的配置:
如果您使用的是基于XML的配置,只需使用