Shiro java 配置白名单 示例 各种情况尽可能详尽
时间: 2024-10-21 07:04:00 浏览: 24
JavaEESecurityExample:Java EE 和 Shiro 安全示例
在Shiro中,使用白名单配置允许特定的请求或路径直接访问而无需身份验证,这对于API接口或已知安全的静态资源非常有用。以下是一个详细的Shiro Java配置白名单示例,涵盖了几种常见的情况:
```java
import org.apache.shiro.SecurityUtils;
import org.apache.shiro.config.IniSecurityManagerFactory;
import org.apache.shiro.mgt.SecurityManager;
import org.apache.shiro.spring.LifecycleBeanPostProcessor;
import org.apache.shiro.spring.security.interceptor.AuthorizationAttributeSourceAdvisor;
import org.apache.shiro.web.env.EnvironmentLoaderListener;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.transaction.annotation.EnableTransactionManagement;
@Configuration
@EnableTransactionManagement
public class ShiroConfig {
@Autowired
private IniSecurityManagerFactory securityManagerFactory;
// 白名单配置
@Bean
public AuthorizationPolicy whiteListAuthorizationPolicy() {
SimpleAuthorizationPolicy policy = new SimpleAuthorizationPolicy();
policy.setPermissions(new HashSet<Permission>(Arrays.asList(
new AuthorizationInfo.Builder().urls("/**").permissions("ALL").build(),
new AuthorizationInfo.Builder().urls("/api/*").permissions("API").build(),
new AuthorizationInfo.Builder().urls("/static/**").permissions("STATIC").build()
)));
return policy;
}
// 创建自定义的权限管理器
@Bean
public CustomShiroRealm customShiroRealm() {
CustomShiroRealm realm = new CustomShiroRealm();
realm.setAuthorizationInfoProvider(authzInfoProvider());
return realm;
}
// 自定义获取权限信息的方法
private AuthorizationInfoProvider authzInfoProvider() {
return (username, context) -> {
if (username.equals("admin")) { // 假设我们有一个管理员用户
return new AuthorizationInfo.Builder()
.authorizations(whiteListAuthorizationPolicy())
.build();
}
return null;
};
}
// 设置安全管理器,初始化白名单策略
@Bean
public SecurityManager securityManager() throws Exception {
SecurityManager sm = securityManagerFactory.createSecurityManager();
((CustomShiroRealm) sm.getAuthorizingRealm()).setAuthorizationInfoProvider(authzInfoProvider());
EnvironmentLoaderListener listener = new EnvironmentLoaderListener();
listener.afterPropertiesSet(sm);
return sm;
}
// Spring集成Shiro
@Bean
public LifecycleBeanPostProcessor lifecycleBeanPostProcessor() {
return new LifecycleBeanPostProcessor();
}
// 注册AuthorizationAttributeSourceAdvisor
@Bean
public AuthorizationAttributeSourceAdvisor authorizationAttributeSourceAdvisor() {
AuthorizationAttributeSourceAdvisor advisor = new AuthorizationAttributeSourceAdvisor();
advisor.setSecurityManager(securityManager());
return advisor;
}
}
```
这里的关键点:
- `whiteListAuthorizationPolicy`方法创建了一个只允许特定路径的简单授权策略。
- `customShiroRealm`实现了自定义的 Realm,其中包含一个用于提供授权信息的方法(`authzInfoProvider`),可以根据用户名判断是否提供白名单策略。
- `securityManager`整合了自定义的 Realm 和白名单策略。
- `lifecycleBeanPostProcessor`和`authorizationAttributeSourceAdvisor`分别用于Spring和Shiro之间的集成。
阅读全文