1

我有一个 Micronaut 3 应用程序,在使用 JWT 令牌时,检查方法上的 Authentication 属性为空,但是,我需要从 JWT 获取所有角色。

根据 Micronaut 的最新变化

安全规则更改

SecurityRule API 已更改。该方法的最后一个参数是表示用户属性的映射。相反,该参数被替换为对身份验证的引用。这样做的好处是规则现在可以访问登录用户的用户名以及访问便捷方法 getRoles()。

@Singleton
public class AuthorityHandler implements SecurityRule {
    @Override
    public Publisher<SecurityRuleResult> check(HttpRequest<?> request, RouteMatch<?> routeMatch, Authentication authentication) {
        if (routeMatch instanceof MethodBasedRouteMatch methodBasedRouteMatch) {
            if (methodBasedRouteMatch.hasAnnotation(IRequirement.class)) {
                AnnotationValue<IRequirement> requiredPermissionAnnotation = methodBasedRouteMatch.getAnnotation(IRequirement.class);
                Optional<String> resourceIdName = requiredPermissionAnnotation.stringValue("resourceName");
                String[] permissions = requiredPermissionAnnotation.stringValues("permission");
                if (permissions.length > 0 && resourceIdName.isPresent() && authentication != null) {
                    List<String> identityClaims = (List<String>) authentication.getRoles();
                    if (Arrays.stream(permissions).anyMatch(element -> identityClaims.contains(element)))
                        return Mono.just(SecurityRuleResult.ALLOWED);
                    else
                        return Mono.just(SecurityRuleResult.REJECTED);
                }
            }
        }
        return Mono.just(SecurityRuleResult.UNKNOWN);
    }
}

在此处输入图像描述

@Post
    @IRequirement(resourceName = ClaimType.TAG_PRODUCT, permission = {ClaimValue.TAG_OWNER,ClaimValue.TAG_CREATOR,ClaimValue.TAG_VIEWER })
    Mono<MutableHttpResponse<?>> post(@Body @Valid CategoryCommand model);

我登录到应用程序并从身份服务器收到的请求中传递 JWT 令牌,它也具有角色。我错过了什么或犯了什么错误?

配置

micronaut:
  application:
    name: fetebirdApigateway
  server:
    port: 8080
    cors:
      enabled: true
    http-version: 2.0
  security:
    enabled: true
    token:
      jwt:
        enabled: true
        signatures:
          jwks:
            IdentityServer:
              url: 'https://localhost:5001/.well-known/openid-configuration/jwks'
      propagation:
        enabled: true
        header:
          enabled: true
          header-name: "Authorization"
          prefix: "Bearer "
        service-id-regex: "fetebirdProductPublisher|feteBirdService"
    intercept-url-map:
      - pattern: /swagger-ui/**
        httpMethod: GET
        access:
          - isAnonymous()
      - pattern: /swagger/**
        access:
          - isAnonymous()
  router:
    static-resources:
      swagger:
        paths: classpath:META-INF/swagger
        mapping: /swagger/**
      swagger-ui:
        paths: classpath:META-INF/swagger/views/swagger-ui
        mapping: /swagger-ui/**
tracing:
  zipkin:
    enabled: true
    http:
      url: http://localhost:9411
    sampler:
      probability: 0.1
consul:
  client:
    registration:
      enabled: true
    defaultZone: ${CONSUL_HOST:localhost}:${CONSUL_PORT:8500}
jackson:
  serializationInclusion: ALWAYS

在此处输入图像描述

解码 JWT

{
  "nbf": 1634908283,
  "exp": 1634908483,
  "iss": "https://localhost:5001",
  "client_id": "Fete_Bird_UI",
  "sub": "673533cc-7c0b-40f3-80ac-222696df385d",
  "auth_time": 1634906895,
  "idp": "local",
  "http://schemas.xmlsoap.org/ws/2005/05/identity/claims/nameidentifier": "673533cc-7c0b-40f3-80ac-222696df385d",
  "http://schemas.xmlsoap.org/ws/2005/05/identity/claims/name": "admin@local.com",
  "http://schemas.xmlsoap.org/ws/2005/05/identity/claims/emailaddress": "admin@local.com",
  "AspNet.Identity.SecurityStamp": "812aa4cb-b9f1-48ac-9e39-1f0dceb6f1c4",
  "identityserver": "owner",
  "fb_product": "owner",
  "fb_order": "owner",
  "fb_payment": "owner",
  "jti": "4AD786103632F389C21E10794E87BEC2",
  "sid": "D0423E9D4C5DDC6575448F6C65537B63",
  "iat": 1634908283,
  "scope": [
    "openid",
    "profile",
    "email"
  ],
  "amr": [
    "pwd"
  ]
}

索赔

"identityserver": "owner",
  "fb_product": "owner",
  "fb_order": "owner",
  "fb_payment": "owner",
4

2 回答 2

1

向JwtValidator添加断点

并提高日志级别以确保安全。在 中添加以下行logback.xml

<logger name="io.micronaut.security" level="TRACE"/>
于 2021-10-22T15:58:04.813 回答
0

感谢 Sergio del Amo,我能够找到我的应用程序的问题。这是一个javax.net.ssl.SSLHandshakeException: sun.security.validator.ValidatorException: PKIX path building failed Error

java cacerts 中未添加 localhost 证书。

由于我使用 Intellj 下载 java 17,因此文件位置可能与其他 java sdk 不同

将应用程序证书添加到所用 JVM 的信任库文件中,该文件位于/Users/macbook/Library/Java/JavaVirtualMachines/openjdk-17.0.1/Contents/Home/lib/security/cacerts.

通过运行以下命令检查您的证书是否已在信任库中:keytool -list -keystore /Users/macbook/Library/Java/JavaVirtualMachines/openjdk-17.0.1/Contents/Home/lib/security/cacerts

从浏览器下载证书并使用以下命令将其添加到信任库:

keytool -import -noprompt -trustcacerts -alias <AliasName> -file   <certificate> -keystore <KeystoreFile> -storepass <Password>

例子

keytool -import -noprompt -trustcacerts -alias falconIdentity -file /Users/macbook/Desktop/localhost.cer -keystore /Users/macbook/Library/Java/JavaVirtualMachines/openjdk-17.0.1/Contents/Home/lib/security/cacerts/keystore.jks -storepass changeit
于 2021-10-23T06:09:17.487 回答