Skip to content

Commit

Permalink
Clean up code
Browse files Browse the repository at this point in the history
  • Loading branch information
TheLydonKing committed Aug 15, 2024
1 parent 8249377 commit 6656966
Show file tree
Hide file tree
Showing 6 changed files with 59 additions and 98 deletions.
19 changes: 6 additions & 13 deletions api/src/main/scala/za/co/absa/loginsvc/rest/SecurityConfig.scala
Original file line number Diff line number Diff line change
Expand Up @@ -18,7 +18,6 @@ package za.co.absa.loginsvc.rest

import org.springframework.beans.factory.annotation.Autowired
import org.springframework.context.annotation.{Bean, Configuration}
import org.springframework.security.authentication.{AuthenticationManager, ProviderManager}
import org.springframework.security.config.annotation.web.builders.HttpSecurity
import org.springframework.security.config.annotation.web.configuration.EnableWebSecurity
import org.springframework.security.config.http.SessionCreationPolicy
Expand All @@ -29,10 +28,9 @@ import za.co.absa.loginsvc.rest.provider.kerberos.KerberosSPNEGOAuthenticationPr

@Configuration
@EnableWebSecurity
class SecurityConfig@Autowired()(authConfigsProvider: AuthConfigProvider) {
class SecurityConfig @Autowired()(authConfigsProvider: AuthConfigProvider) {

//TODO: Neaten up checking for Config
private val KerberosConfig = authConfigsProvider.getLdapConfig.orNull
private val ldapConfig = authConfigsProvider.getLdapConfig.orNull

@Bean
def filterChain(http: HttpSecurity): SecurityFilterChain = {
Expand All @@ -57,19 +55,14 @@ class SecurityConfig@Autowired()(authConfigsProvider: AuthConfigProvider) {
.and()
.httpBasic()

//TODO: Neaten up checking for Config
if(KerberosConfig != null)
if(ldapConfig != null)
{
if(KerberosConfig.enableKerberos.isDefined)
if(ldapConfig.enableKerberos.isDefined)
{
val kerberos = new KerberosSPNEGOAuthenticationProvider(KerberosConfig)

val provider = kerberos.kerberosAuthenticationProvider()
val serviceProvider = kerberos.kerberosServiceAuthenticationProvider()
val kerberos = new KerberosSPNEGOAuthenticationProvider(ldapConfig)

http.addFilterBefore(
kerberos.spnegoAuthenticationProcessingFilter(
new ProviderManager(provider, serviceProvider)),
kerberos.spnegoAuthenticationProcessingFilter,
classOf[BasicAuthenticationFilter])
}
}
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -72,9 +72,10 @@ class TokenController @Autowired()(jwtService: JWTService) {
@ResponseStatus(HttpStatus.OK)
@SecurityRequirement(name = "basicAuth")
def generateToken(authentication: Authentication, @RequestParam("group-prefixes") groupPrefixes: Optional[String]): CompletableFuture[TokensWrapper] = {

val user: User = authentication.getPrincipal match {
case u: User => u
case k: KerberosUserDetails => User(k.username, k.groups, k.optionalAttributes);
case k: KerberosUserDetails => k.getUser
case _ => throw new ResponseStatusException(HttpStatus.UNAUTHORIZED, "User not authenticated or unknown principal type")
}
val groupPrefixesStrScala = groupPrefixes.toScalaOption
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -19,19 +19,20 @@ package za.co.absa.loginsvc.rest.model
import org.springframework.security.core.GrantedAuthority
import org.springframework.security.core.authority.SimpleGrantedAuthority
import org.springframework.security.core.userdetails.UserDetails
import za.co.absa.loginsvc.model.User

import java.util
import scala.collection.JavaConverters._

case class KerberosUserDetails(username: String, groups: Seq[String], optionalAttributes: Map[String, Option[AnyRef]])
case class KerberosUserDetails(user: User)
extends UserDetails
{
override def getAuthorities: util.Collection[_ <: GrantedAuthority] =
groups.map(new SimpleGrantedAuthority(_)).toList.asJava
user.groups.map(new SimpleGrantedAuthority(_)).toList.asJava

override def getPassword: String = ""

override def getUsername: String = username
override def getUsername: String = user.name

override def isAccountNonExpired: Boolean = true

Expand All @@ -40,4 +41,6 @@ extends UserDetails
override def isCredentialsNonExpired: Boolean = true

override def isEnabled: Boolean = true

def getUser: User = user
}

This file was deleted.

Original file line number Diff line number Diff line change
Expand Up @@ -18,25 +18,19 @@ package za.co.absa.loginsvc.rest.provider.kerberos

import org.slf4j.LoggerFactory
import org.springframework.core.io.FileSystemResource
import org.springframework.security.authentication.{AuthenticationManager, BadCredentialsException}
import org.springframework.security.core.userdetails.{UserDetails, UserDetailsService}
import org.springframework.security.authentication.ProviderManager
import org.springframework.security.kerberos.authentication.{KerberosAuthenticationProvider, KerberosServiceAuthenticationProvider}
import org.springframework.security.kerberos.authentication.sun.{SunJaasKerberosClient, SunJaasKerberosTicketValidator}
import org.springframework.security.kerberos.web.authentication.SpnegoAuthenticationProcessingFilter
import za.co.absa.loginsvc.rest.config.auth.ActiveDirectoryLDAPConfig
import za.co.absa.loginsvc.rest.model.KerberosUserDetails
import za.co.absa.loginsvc.rest.service.search.LdapUserRepository

import scala.collection.JavaConverters._

class KerberosSPNEGOAuthenticationProvider(activeDirectoryLDAPConfig: ActiveDirectoryLDAPConfig) {

//TODO: Split into Multiple files for neater implementation
private val ldapConfig = activeDirectoryLDAPConfig
private val kerberos = ldapConfig.enableKerberos.get
private val kerberosDebug = kerberos.debug.getOrElse(false)
private val logger = LoggerFactory.getLogger(classOf[KerberosSPNEGOAuthenticationProvider])
logger.debug(s"KerberosSPNEGOAuthenticationProvider init")
logger.info(s"KerberosSPNEGOAuthenticationProvider init")

System.setProperty("javax.net.debug", kerberosDebug.toString)
System.setProperty("sun.security.krb5.debug", kerberosDebug.toString)
Expand All @@ -47,35 +41,35 @@ class KerberosSPNEGOAuthenticationProvider(activeDirectoryLDAPConfig: ActiveDire
System.setProperty("java.security.krb5.conf", kerberos.krbFileLocation)
}

def spnegoAuthenticationProcessingFilter(authenticationManager: AuthenticationManager): SpnegoAuthenticationProcessingFilter =
def spnegoAuthenticationProcessingFilter: SpnegoAuthenticationProcessingFilter =
{
val filter: SpnegoAuthenticationProcessingFilter = new SpnegoAuthenticationProcessingFilter()
filter.setAuthenticationManager(authenticationManager)
filter.setAuthenticationManager(new ProviderManager(kerberosAuthenticationProvider, kerberosServiceAuthenticationProvider))
filter.afterPropertiesSet()
filter
}

def kerberosAuthenticationProvider(): KerberosAuthenticationProvider =
def kerberosAuthenticationProvider: KerberosAuthenticationProvider =
{
val provider: KerberosAuthenticationProvider = new KerberosAuthenticationProvider()
val client: SunJaasKerberosClient = new SunJaasKerberosClient()

client.setDebug(kerberosDebug)
provider.setKerberosClient(client)
provider.setUserDetailsService(dummyUserDetailsService)
provider.setUserDetailsService(kerberosUserDetailsService)
provider
}

def kerberosServiceAuthenticationProvider(): KerberosServiceAuthenticationProvider =
def kerberosServiceAuthenticationProvider: KerberosServiceAuthenticationProvider =
{
val provider: KerberosServiceAuthenticationProvider = new KerberosServiceAuthenticationProvider()
provider.setTicketValidator(sunJaasKerberosTicketValidator())
provider.setUserDetailsService(dummyUserDetailsService)
provider.setTicketValidator(sunJaasKerberosTicketValidator)
provider.setUserDetailsService(kerberosUserDetailsService)
provider.afterPropertiesSet()
provider
}

private def sunJaasKerberosTicketValidator(): SunJaasKerberosTicketValidator =
private def sunJaasKerberosTicketValidator: SunJaasKerberosTicketValidator =
{
val ticketValidator: SunJaasKerberosTicketValidator = new SunJaasKerberosTicketValidator()
ticketValidator.setServicePrincipal(kerberos.spn)
Expand All @@ -85,24 +79,5 @@ class KerberosSPNEGOAuthenticationProvider(activeDirectoryLDAPConfig: ActiveDire
ticketValidator
}

private def dummyUserDetailsService = DummyUserDetailsService(ldapConfig)
}

case class DummyUserDetailsService(activeDirectoryLDAPConfig: ActiveDirectoryLDAPConfig) extends UserDetailsService {
private val logger = LoggerFactory.getLogger(classOf[DummyUserDetailsService])
override def loadUserByUsername(username: String): UserDetails =
{
val userName = if(username.contains("@")) {
username.split("@").head
} else {
username
}
val ldapContext = new LdapUserRepository(activeDirectoryLDAPConfig)
val user = ldapContext.searchForUser(userName)
if(user.isEmpty)
throw new BadCredentialsException("Cannot Find User in Ldap")

logger.info("Found Kerberos User:" + user.get.name)
KerberosUserDetails(user.get.name, user.get.groups, user.get.optionalAttributes)
}
private def kerberosUserDetailsService = KerberosUserDetailsService(ldapConfig)
}
Original file line number Diff line number Diff line change
@@ -0,0 +1,34 @@
package za.co.absa.loginsvc.rest.provider.kerberos

import org.slf4j.LoggerFactory
import org.springframework.security.authentication.BadCredentialsException
import org.springframework.security.core.userdetails.{UserDetails, UserDetailsService}
import za.co.absa.loginsvc.rest.config.auth.ActiveDirectoryLDAPConfig
import za.co.absa.loginsvc.rest.model.KerberosUserDetails
import za.co.absa.loginsvc.rest.service.search.LdapUserRepository

case class KerberosUserDetailsService(activeDirectoryLDAPConfig: ActiveDirectoryLDAPConfig) extends UserDetailsService {

private val logger = LoggerFactory.getLogger(classOf[KerberosUserDetailsService])

override def loadUserByUsername(username: String): UserDetails =
{
val name = if(username.contains("@")) {
username.split("@").head
} else {
username
}

val ldapContext = new LdapUserRepository(activeDirectoryLDAPConfig)
logger.info(s"Searching for user:$name")
val userOption = ldapContext.searchForUser(name)

if(userOption.isEmpty)
throw new BadCredentialsException(s"Cannot Find User, $name, in Ldap")

val user = userOption.get
logger.info(s"Found Kerberos User: ${user.name}")
KerberosUserDetails(user)
}
}

0 comments on commit 6656966

Please sign in to comment.