galovics commented on code in PR #5883:
URL: https://github.com/apache/fineract/pull/5883#discussion_r3302675714


##########
fineract-core/src/main/java/org/apache/fineract/infrastructure/core/config/FineractProperties.java:
##########
@@ -556,6 +557,27 @@ public static final class Registration implements 
Serializable {
             }
         }
 
+        @Getter
+        @Setter
+        public static class FineractSecurityOidcFederationProperties {
+
+            private boolean enabled;
+            // JWT claim name used to resolve the Fineract tenant ID.
+            // Falls back to HTTP header / query param if absent.
+            private String tenantClaimName = "fineract_tenant";
+            // Claim used as the Fineract username. Common values: 
preferred_username, email, sub.
+            private String usernameClaim = "preferred_username";
+            // When true, creates a Fineract AppUser on first successful OIDC 
login.
+            private boolean autoCreateUser = false;
+            // Comma-separated role names assigned to auto-created users.
+            private String defaultRoles = "";
+            // Controls the RP-Initiated Logout URL format.
+            // Values: keycloak | azure_ad | okta | auth0 | generic (default)
+            private String provider = "generic";

Review Comment:
   Wouldn't it make more sense to model `provider` as an enum? The `switch` in 
`OidcLogoutSuccessHandler.buildLogoutUrl()` operates on these exact string 
values, so a misconfiguration (`azure-ad` instead of `azure_ad`, say) silently 
falls through to `default -> null` and the logout just never reaches the IdP - 
no error, no warning. An enum bound via Spring's relaxed binding (`OidcProvider 
{ KEYCLOAK, AZURE_AD, OKTA, AUTH0, GENERIC }`) would catch that at startup. 
Thoughts?



##########
fineract-provider/src/main/java/org/apache/fineract/infrastructure/security/service/OidcAppUserResolutionServiceImpl.java:
##########
@@ -0,0 +1,125 @@
+/**
+ * Licensed to the Apache Software Foundation (ASF) under one
+ * or more contributor license agreements. See the NOTICE file
+ * distributed with this work for additional information
+ * regarding copyright ownership. The ASF licenses this file
+ * to you under the Apache License, Version 2.0 (the
+ * "License"); you may not use this file except in compliance
+ * with the License. You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing,
+ * software distributed under the License is distributed on an
+ * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
+ * KIND, either express or implied. See the License for the
+ * specific language governing permissions and limitations
+ * under the License.
+ */
+package org.apache.fineract.infrastructure.security.service;
+
+import jakarta.transaction.Transactional;

Review Comment:
   Please use `org.springframework.transaction.annotation.Transactional` here 
instead of the Jakarta one. The Jakarta `@Transactional` has subtly different 
propagation defaults in a Spring-managed context and can behave unexpectedly — 
for example around `REQUIRED` propagation when an outer Spring transaction is 
already active. This is something we try to keep consistent across the codebase.



##########
fineract-security/src/main/java/org/apache/fineract/infrastructure/security/filter/OidcTenantAwareFilter.java:
##########
@@ -0,0 +1,114 @@
+/**
+ * Licensed to the Apache Software Foundation (ASF) under one
+ * or more contributor license agreements. See the NOTICE file
+ * distributed with this work for additional information
+ * regarding copyright ownership. The ASF licenses this file
+ * to you under the Apache License, Version 2.0 (the
+ * "License"); you may not use this file except in compliance
+ * with the License. You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing,
+ * software distributed under the License is distributed on an
+ * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
+ * KIND, either express or implied. See the License for the
+ * specific language governing permissions and limitations
+ * under the License.
+ */
+package org.apache.fineract.infrastructure.security.filter;
+
+import com.nimbusds.jwt.JWTParser;
+import jakarta.servlet.FilterChain;
+import jakarta.servlet.ServletException;
+import jakarta.servlet.http.HttpServletRequest;
+import jakarta.servlet.http.HttpServletResponse;
+import java.io.IOException;
+import lombok.RequiredArgsConstructor;
+import lombok.extern.slf4j.Slf4j;
+import org.apache.fineract.infrastructure.core.config.FineractProperties;
+import org.apache.fineract.infrastructure.core.service.ThreadLocalContextUtil;
+import 
org.apache.fineract.infrastructure.security.service.AuthTenantDetailsService;
+import org.springframework.lang.NonNull;
+import 
org.springframework.security.oauth2.server.resource.web.BearerTokenResolver;
+import org.springframework.web.filter.OncePerRequestFilter;
+
+/**
+ * Resolves the Fineract tenant from an incoming request and sets it in {@link 
ThreadLocalContextUtil} before Spring
+ * Security validates the JWT signature.
+ *
+ * <p>
+ * Resolution priority:
+ * <ol>
+ * <li>A configurable claim inside the Bearer JWT (parsed without signature 
verification)</li>
+ * <li>The {@code Fineract-Platform-TenantId} HTTP header</li>
+ * <li>The {@code tenantIdentifier} query parameter</li>
+ * </ol>
+ *
+ * <p>
+ * If no tenant can be resolved the filter does not block the request — 
downstream authentication will fail with an
+ * appropriate error if the tenant context is required.
+ */
+@Slf4j
+@RequiredArgsConstructor
+public class OidcTenantAwareFilter extends OncePerRequestFilter {
+
+    private static final String TENANT_HEADER = "Fineract-Platform-TenantId";
+    private static final String TENANT_PARAM = "tenantIdentifier";
+
+    private final BearerTokenResolver bearerTokenResolver;
+    private final AuthTenantDetailsService tenantDetailsService;
+    private final FineractProperties fineractProperties;
+
+    @Override
+    protected void doFilterInternal(@NonNull HttpServletRequest request, 
@NonNull HttpServletResponse response,
+            @NonNull FilterChain filterChain) throws ServletException, 
IOException {
+        try {
+            String tenantId = resolveTenantId(request);
+            if (tenantId != null) {
+                
ThreadLocalContextUtil.setTenant(tenantDetailsService.loadTenantById(tenantId, 
false));
+                log.debug("OIDC tenant context set to '{}' for {}", tenantId, 
request.getRequestURI());
+            }
+            filterChain.doFilter(request, response);
+        } catch (Exception e) {
+            // don't block; real auth will fail later if token or tenant is 
invalid

Review Comment:
   I understand the reasoning - don't block the chain - but with no log line at 
all, nobody will know when this catch triggers. If the tenant service is down, 
for example, every OIDC request silently skips tenant resolution and you'd have 
to infer it from downstream errors. Could we at least add `log.debug("Tenant 
resolution failed, continuing without tenant context", e)` here? Wdyt?



##########
fineract-provider/src/main/java/org/apache/fineract/infrastructure/security/service/OidcAppUserResolutionServiceImpl.java:
##########
@@ -0,0 +1,125 @@
+/**
+ * Licensed to the Apache Software Foundation (ASF) under one
+ * or more contributor license agreements. See the NOTICE file
+ * distributed with this work for additional information
+ * regarding copyright ownership. The ASF licenses this file
+ * to you under the Apache License, Version 2.0 (the
+ * "License"); you may not use this file except in compliance
+ * with the License. You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing,
+ * software distributed under the License is distributed on an
+ * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
+ * KIND, either express or implied. See the License for the
+ * specific language governing permissions and limitations
+ * under the License.
+ */
+package org.apache.fineract.infrastructure.security.service;
+
+import jakarta.transaction.Transactional;
+import java.util.Arrays;
+import java.util.HashSet;
+import java.util.List;
+import java.util.Set;
+import java.util.stream.Stream;
+import lombok.RequiredArgsConstructor;
+import lombok.extern.slf4j.Slf4j;
+import org.apache.fineract.infrastructure.core.config.FineractProperties;
+import 
org.apache.fineract.infrastructure.security.exception.OidcUserNotFoundException;
+import org.apache.fineract.organisation.office.domain.Office;
+import org.apache.fineract.organisation.office.domain.OfficeRepository;
+import org.apache.fineract.useradministration.domain.AppUser;
+import org.apache.fineract.useradministration.domain.AppUserRepository;
+import org.apache.fineract.useradministration.domain.Role;
+import org.apache.fineract.useradministration.domain.RoleRepository;
+import org.springframework.security.core.authority.SimpleGrantedAuthority;
+import org.springframework.security.core.userdetails.User;
+import org.springframework.security.crypto.factory.PasswordEncoderFactories;
+import org.springframework.security.crypto.password.PasswordEncoder;
+import org.springframework.stereotype.Service;
+
+@Slf4j
+@Service
+@RequiredArgsConstructor
+public class OidcAppUserResolutionServiceImpl implements 
OidcAppUserResolutionService {
+
+    private final AppUserRepository appUserRepository;
+    private final RoleRepository roleRepository;
+    private final OfficeRepository officeRepository;
+    private final FineractProperties fineractProperties;
+
+    // Stateless encoder — safe to create once per class
+    private static final PasswordEncoder PASSWORD_ENCODER = 
PasswordEncoderFactories.createDelegatingPasswordEncoder();
+
+    @Override
+    @Transactional
+    public AppUser resolveOrCreate(String username, String email, String 
firstName, String lastName, Set<String> requestedRoles) {
+
+        // 1. Lookup by username
+        AppUser user = appUserRepository.findAppUserByName(username);
+        if (user != null) {
+            log.debug("OIDC user resolved by username: '{}'", username);
+            return user;
+        }
+
+        // 2. Fallback: lookup by email
+        if (email != null) {
+            user = appUserRepository.findActiveUserByEmail(email);
+            if (user != null) {
+                log.debug("OIDC user resolved by email: '{}'", email);
+                return user;
+            }
+        }
+
+        // 3. Auto-create when enabled
+        
FineractProperties.FineractSecurityProperties.FineractSecurityOidcFederationProperties
 oidcConfig = fineractProperties.getSecurity()
+                .getOidcFederation();
+
+        if (!oidcConfig.isAutoCreateUser()) {
+            log.warn("OIDC user '{}' not found in Fineract and auto-create is 
disabled", username);
+            throw new OidcUserNotFoundException(username);
+        }
+
+        log.info("Auto-creating Fineract user for OIDC subject '{}'", 
username);
+        return createUser(username, email, firstName, lastName, 
requestedRoles, oidcConfig);
+    }
+
+    private AppUser createUser(String username, String email, String 
firstName, String lastName, Set<String> requestedRoles,
+            
FineractProperties.FineractSecurityProperties.FineractSecurityOidcFederationProperties
 oidcConfig) {
+

Review Comment:
   Can we extract `1L` to a named constant - something like `HEAD_OFFICE_ID`? 
It's a Fineract convention that the head office always has id=1, but a bare 
`1L` reads like a magic number. Thanks.



-- 
This is an automated message from the Apache Git Service.
To respond to the message, please log on to GitHub and use the
URL above to go to the specific comment.

To unsubscribe, e-mail: [email protected]

For queries about this service, please contact Infrastructure at:
[email protected]

Reply via email to