【发布时间】:2014-10-27 12:29:54
【问题描述】:
我正在使用带有用户、角色、权限实体的 Spring Security,并且用户已成功通过身份验证,我可以访问其权限集合。
我使用 AJAX 调用视图页面并在前端和后端之间发送 json。问题是我不知道如何配置我的 spring-security 文件,因为 @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-security 文件内容:
<?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());
}
}
【问题讨论】:
-
虽然你的配置有一些重复,但似乎已经够用了。您确定要保护的控制器与 Spring Security 上下文属于同一上下文的一部分吗?
-
是的,只有一个上下文。
标签: java spring-mvc spring-security authorization