身份验证为空 Micronaut 3

Authentication is null Micronaut 3

我有一个 Micronaut 3 应用程序,在使用 JWT 令牌时,检查方法上的 Authentication 属性为 null,但是,我需要从 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",

添加断点到JwtValidator

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

<logger name="io.micronaut.security" level="TRACE"/>

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

本地主机证书未添加到 java cacerts。

因为我用的是Intellj下载java17文件位置可能和其他的不一样javasdk

正在将申请的证书添加到位于/Users/macbook/Library/Java/JavaVirtualMachines/openjdk-17.0.1/Contents/Home/lib/security/cacerts.

的所用JVM的truststore文件中

通过运行以下命令检查您的证书是否已在信任库中: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