shiro开放接口权限自定义注解,并在ShiroFilterFactoryBean中添加,用java语言编写
时间: 2024-03-02 17:47:59 浏览: 203
好的,针对您的问题,您可以使用Shiro提供的权限注解 `@RequiresPermissions`,并通过自定义注解来实现权限控制。
以下是一个示例代码,其实现了一个自定义注解 `@ApiPermission`,并在 `ShiroFilterFactoryBean` 中添加了该注解,用于控制开放接口的访问权限:
```java
@Retention(RetentionPolicy.RUNTIME)
@Target(ElementType.METHOD)
public @interface ApiPermission {
String[] value() default {};
}
public class ApiPermissionFilter extends AuthorizationFilter {
@Override
protected boolean isAccessAllowed(ServletRequest request, ServletResponse response, Object mappedValue) throws Exception {
Subject subject = getSubject(request, response);
String[] permissions = (String[]) mappedValue;
if (permissions == null || permissions.length == 0) {
return true;
}
for (String permission : permissions) {
if (subject.isPermitted(permission)) {
return true;
}
}
return false;
}
}
@Configuration
public class ShiroConfig {
@Bean
public ShiroFilterFactoryBean shiroFilterFactoryBean(DefaultWebSecurityManager securityManager) {
ShiroFilterFactoryBean factoryBean = new ShiroFilterFactoryBean();
factoryBean.setSecurityManager(securityManager);
Map<String, Filter> filterMap = new LinkedHashMap<>();
filterMap.put("apiPermission", new ApiPermissionFilter());
factoryBean.setFilters(filterMap);
Map<String, String> filterChainDefinitionMap = new LinkedHashMap<>();
filterChainDefinitionMap.put("/login", "anon");
filterChainDefinitionMap.put("/logout", "logout");
filterChainDefinitionMap.put("/api/**", "apiPermission[api:read]");
filterChainDefinitionMap.put("/**", "authc");
factoryBean.setFilterChainDefinitionMap(filterChainDefinitionMap);
return factoryBean;
}
}
@RestController
public class ApiController {
@GetMapping("/api/test")
@ApiPermission("api:read")
public String test() {
return "Hello, World!";
}
}
```
在上述代码中,我们定义了一个 `ApiPermissionFilter`,用于判断用户是否具有访问开放接口的权限。然后,在 `ShiroFilterFactoryBean` 中添加了该过滤器,并在 `filterChainDefinitionMap` 中使用 `apiPermission[api:read]` 来控制 `/api/**` 下的所有请求的访问权限。
最后,在 `ApiController` 中使用 `@ApiPermission("api:read")` 注解来标识需要具有 `api:read` 权限才能访问的接口。
阅读全文