@PreAuthorize不使用控制器

时间:2016-12-06 18:14:57

标签: java spring spring-mvc spring-security

我尝试使用preAuthorize来保护网址。只有在课程中注册的人才能访问该课程。这是我的代码:

控制器:

@Controller
@RequestMapping(value = "/course/{courseId}")
@PreAuthorize("@userService.isCurrentUserinCourse(authentication, courseId)")
public class SyllabusController {
    @RequestMapping(value = { "/syllabus" }, method = RequestMethod.GET)
    public ModelAndView syllabusPage(@PathVariable("courseId") int courseId) {
    ...}

UserServiceImpl:

@Service("userService")
public class UserServiceImpl implements UserService {
    @Autowired
    private UserDAO userDAO;
    @Override
    public boolean isUserinCourse(int userId, int courseId) {
        return userDAO.isUserinCourse(userId, courseId);
    }

    @Override
    public boolean isCurrentUserinCourse(Authentication authentication, int courseId) {
    if (!(authentication instanceof AnonymousAuthenticationToken)) {
            return isUserinCourse(((UserModel) authentication.getPrincipal()).getId(), courseId);
    }
    return false;
}

弹簧security.xml文件:

<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.0.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" />
<!-- enable use-expressions -->
<http auto-config="true" use-expressions="true">

我们在没有登录的情况下转到/ course / {id} / syllabus,它显示了不应该登录的页面。并且调试不是进入UserServiceImpl中的isCurrentUserinCourse(Authentication authentication,int courseId)方法。

1 个答案:

答案 0 :(得分:0)

@PreAuthorize("@userService.isCurrentUserinCourse(authentication, courseId)")

您可以通过以下静态方法获取身份验证

SecurityContextHolder.getContext().getAuthentication()

courseId您需要更改为#coureseId,并且您需要将其移至方法,而不是类,因此您可以更改为

    @PreAuthorize("@userService.isCurrentUserinCourse(#courseId)")
    @RequestMapping(value = { "/syllabus" }, method = RequestMethod.GET)
    public ModelAndView syllabusPage(@PathVariable("courseId") int courseId) {
    ...}