今天尝试用 spring security 来保护 业务层 的方法。使用了@PreAuthorize
定义一个 接口 IUser
public interface IUser {
@PreAuthorize("hasRole('ROLE_ADMIN')")
public void say();
}
@PreAuthorize注解定义了当 拥有 ROLE_ADMIN 权限的时候才能够正确的使用这个方法. hasRole("XX")是 spEL的语法.
这就是保证合法、已认证的用户才能访问修改密码功能所要做的所有事情。Spring Security将会使用运行时的面向方面编程的切点(aspect oriented programming (AOP) pointcut)来对方法执行before advice,并在安全要求未满足的情况下抛出AccessDeniedException异常。
定义一个实现类:UserSerivece
@Component("userService")
public class UserSerivece implements IUser {
public class UserSerivece implements IUser {
@Overridepublic void say() {System.out.println("我访问了say方法");}}
spring-security 中加入:
只需要在 <http> 声明之前,添加下面的元素即可:
<global-method-security pre-post-annotations="enabled"/>
为了方便,直接在 。xml定义如下两个用户:
<user-service>
<user name="admin" authorities="ROLE_USER,ROLE_ADMIN" password="admin"/>
<user name="user" authorities="ROLE_USER" password="user"/>
</user-service>
因为我使用spring mvc 定义个如下Controller:
@Controller
public class BaseControle {
private IUser userService;
@RequestMapping(value="/lookup")
public String testIn(){
for(GrantedAuthority authority:SecurityContextHolder.getContext().getAuthentication().getAuthorities())
{
System.out.println(authority.getAuthority());
}
userService.say();
return "content";
}
public IUser getUserService() {
return userService;
}
@Resource(name="userService")
public void setUserService(IUser userService) {
this.userService = userService;
}
}
我用 user 登入,结果发现我竟然可以访问这个方法。。当时那个郁闷啊。。。
后来再网上查资料
发现service层Spring没有使用注解,而是在配置文件中配置bean元素,于是把@Component去掉,添加一个bean
<bean id="userService" class="com.security.service.UserSerivece"/>
就可以了。 越权访问,就会出现如下界面.
呵呵。没碰到这个问题还真不知道还spring没有个service定义注解。。