我正在使用彈簧安全與用戶,角色,權利實體和用戶身份驗證成功,我可以訪問其權限集合。在彈簧安全中使用@PreAuthorize與角色和權利
我使用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) {
這裏是我的春天,安全文件內容:
<?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安全環境除外的同一上下文的一部分嗎? – Modi 2014-10-28 05:09:38
是的,只有一個上下文。 – sina 2014-10-28 07:20:31