我正在尝试用micronaut 2.2.1实现自定义安全规则,但它不起作用。
public @interface RequiredPermission {
String resourceIdName();
String permission();
}
安全规则
@Singleton
public class AdminRequirement implements SecurityRule {
@Override
public SecurityRuleResult check(HttpRequest<?> request, @Nullable RouteMatch<?> routeMatch, @Nullable Map<String, Object> claims) {
if (routeMatch instanceof MethodBasedRouteMatch) {
MethodBasedRouteMatch methodBasedRouteMatch = (MethodBasedRouteMatch) routeMatch;
if (methodBasedRouteMatch.hasAnnotation(RequiredPermission.class)) {
AnnotationValue<RequiredPermission> requiredPermissionAnnotation = methodBasedRouteMatch.getAnnotation(RequiredPermission.class);
// Get parameters from annotation on method
Optional<String> resourceIdName = requiredPermissionAnnotation.stringValue("resourceIdName");
Optional<String> permission = requiredPermissionAnnotation.stringValue("permission");
if (permission.isPresent() && resourceIdName.isPresent() && claims != null) {
// Use name of parameter to get the value passed in as an argument to the method
String resourceId = methodBasedRouteMatch.getVariableValues().get(resourceIdName.get()).toString();
// Get claim from jwt using the resource ID
Object permissionForResource = ((Map) claims.get("https://your-domain.com/claims")).get(resourceId);
if (permissionForResource != null && permissionForResource.equals(permission.get())) {
// if the permission exists and it's equal, allow access
return SecurityRuleResult.ALLOWED;
}
}
}
}
return SecurityRuleResult.UNKNOWN;
}
}
控制器
@Secured(SecurityRule.IS_AUTHENTICATED)
@Controller("/product")
public record ProductController(IProducer iProducer) {
@Get(uri = "/{text}")
@RequiredPermission(resourceIdName = "Admin", permission = "Admin")
public Single<String> get(String text){
return iProducer.sendText(text);
}
}
``` `AdminRequirement implements SecurityRule` override check()方法从未执行过,这是我缺少的。
应用程序.yml
micronaut:
application:
name: demo
security:
enabled: true
token:
jwt:
enabled: true
signatures:
jwks:
okta:
url: 'https://dev-6271510.okta.com/oauth2/default/v1/keys'
intercept-url-map:
- pattern: /swagger-ui/**
httpMethod: GET
access:
- isAnonymous()
- pattern: /swagger/**
access:
- isAnonymous()
如果我更新代码如下
@Controller("/product")
@RequiredPermission(resourceIdName = "Admin", permission = "Admin")
public record ProductController(IProducer iProducer) {}
上面的代码可以工作,但它不是一个合适的解决方案
@所需权限(resourceidname=“admin”,permission=“admin”)
回购-https://github.com/anandjaisy/micronaut-customsecurityrule
1条答案
按热度按时间kwvwclae1#
安全规则实现有序接口。要实现这一点,您必须在自定义安全规则类中添加以下行。