Shiro - Java注解实现

本文介绍了Shiro提供的五种权限验证注解:@RequiresAuthentication、@RequiresGuest、@RequiresPermissions、@RequiresRoles 和 @RequiresUser。这些注解用于实现不同场景下的权限控制,如需用户认证、检查权限或角色等。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

Shiro提供了五种注解在后台使用以实现权限验证。

@RequiresAuthentication;
@RequiresGuest;
@RequiresPermissions;
@RequiresRoles;
@RequiresUser;

【1】@RequiresAuthentication

表示当前Subject已经通过login 进行了身份验证;即Subject. isAuthenticated() 返回true。

可以用于类/属性/方法,用于表明当前用户需是经过认证的用户。

@RequiresAuthentication  
public void updateAccount(Account userAccount) {  
    //this method will only be invoked by a   
    //Subject that is guaranteed authenticated  
    ...  
} 

【2】@RequiresGuest

表示当前Subject没有身份验证或通过记住我登录过,即是游客身份。

@RequiresGuest 
public voidindexPage() {  
    //this method will only be invoked by a   
    //Subject that is guaranteed authenticated  
    ...  
} 

**【3】@RequiresPermissions **

@RequiresPermissions(value={“user:a”, “user:b”}, logical= Logical.OR),表示当前Subject 需要权限user:a或user:b。

如下示例表示用户需要拥有account:create权限:

@RequiresPermissions("account:create")  
public void createAccount(Account account) {  
    //this method will only be invoked by a Subject  
    //that is permitted to create an account  
    ...  
}  

如果多个权限都可以访问该方法,如下:

@RequiresPermissions({"account:create","admin"}) ; 

**【4】@RequiresRoles **

@RequiresRoles(value={“admin”, “user”}, logical= Logical.AND),表示当前Subject 需要角色admin 和user。

如下示例表示用户需要拥有user角色:

@RequiresRoles("user")  
public void createUser(User user) {  
    //this method will only be invoked by a Subject  
    //that is permitted to create an account  
    ...  
}  

如果多个角色都可以访问该方法,如下:

@RequiresRoles ({"user","admin"}) ; 

【5】@RequiresUser

当前用户需为已认证用户或已记住用户,即已经认证(登录) 或 系统记住 。
注意:@RequiresUser == !@RequiresGuest 。

@RequiresUser
public void userList() {  
    //this method will only be invoked by a Subject  
    //that is permitted to create an account  
    ...  
}  
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

流烟默

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值