我想让Spring JPA审核与Spring Boot一起使用,我正在使用Spring Security的最新功能通过Keycloak进行身份验证。
springBootVersion = '2.1.0.RC1'
我正在跟踪春季安全团队https://github.com/jzheaux/messaging-app/tree/springone2018-demo/resource-server的示例
ResourceServerConfig.kt
@EnableWebSecurity
class OAuth2ResourceServerSecurityConfiguration(val resourceServerProperties: OAuth2ResourceServerProperties) : WebSecurityConfigurerAdapter() {
@Throws(Exception::class)
override fun configure(http: HttpSecurity) {
http
.authorizeRequests()
.antMatchers("/api/**").authenticated()
.anyRequest().anonymous()
.and()
.oauth2ResourceServer()
.authenticationEntryPoint(MoreInformativeAuthenticationEntryPoint())
.jwt()
.jwtAuthenticationConverter(GrantedAuthoritiesExtractor())
.decoder(jwtDecoder())
}
private fun jwtDecoder(): JwtDecoder {
val issuerUri = this.resourceServerProperties.jwt.issuerUri
val jwtDecoder = JwtDecoders.fromOidcIssuerLocation(issuerUri) as NimbusJwtDecoderJwkSupport
val withIssuer = JwtValidators.createDefaultWithIssuer(issuerUri)
val withAudience = DelegatingOAuth2TokenValidator(withIssuer, AudienceValidator())
jwtDecoder.setJwtValidator(withAudience)
return jwtDecoder
}
}
class MoreInformativeAuthenticationEntryPoint : AuthenticationEntryPoint {
private val delegate = BearerTokenAuthenticationEntryPoint()
private val mapper = ObjectMapper().setSerializationInclusion(JsonInclude.Include.NON_NULL)
@Throws(IOException::class, ServletException::class)
override fun commence(request: HttpServletRequest, response: HttpServletResponse,
reason: AuthenticationException) {
this.delegate.commence(request, response, reason)
if (reason.cause is JwtValidationException) {
val validationException = reason.cause as JwtValidationException
val errors = validationException.errors
this.mapper.writeValue(response.writer, errors)
}
}
}
class GrantedAuthoritiesExtractor : JwtAuthenticationConverter() {
override fun extractAuthorities(jwt: Jwt): Collection<GrantedAuthority> {
val scopes = jwt.claims["scope"].toString().split(" ")
return scopes.map { SimpleGrantedAuthority(it) }
}
}
class AudienceValidator : OAuth2TokenValidator<Jwt> {
override fun validate(token: Jwt): OAuth2TokenValidatorResult {
val audience = token.audience
return if (!CollectionUtils.isEmpty(audience) && audience.contains("mobile-client")) {
OAuth2TokenValidatorResult.success()
} else {
OAuth2TokenValidatorResult.failure(MISSING_AUDIENCE)
}
}
companion object {
private val MISSING_AUDIENCE = BearerTokenError("invalid_token", HttpStatus.UNAUTHORIZED,
"The token is missing a required audience.", null)
}
}
application.yaml
spring:
application:
name: sociter
datasource:
url: jdbc:postgresql://localhost:5432/sociter
username: postgres
password: 123123
driver-class-name: org.postgresql.Driver
jpa:
hibernate:
ddl-auto: update
security:
oauth2:
resourceserver:
jwt:
jwk-set-uri: http://localhost:8080/auth/realms/sociter/protocol/openid-connect/certs
issuer-uri: http://localhost:8080/auth/realms/sociter
JpaAuditingConfiguration.kt
@Configuration
@EnableJpaAuditing
(auditorAwareRef = "auditorProvider")
class JpaAuditingConfiguration {
@Bean
fun auditorProvider(): AuditorAware<String> {
return if (SecurityContextHolder.getContext().authentication != null) {
val oauth2 = SecurityContextHolder.getContext().authentication as JwtAuthenticationToken
val claims = oauth2.token.claims
val userId = claims["sub"]
AuditorAware { Optional.of(userId.toString()) }
} else
AuditorAware { Optional.of("Unknown") }
}
}
BaseEntity.kt
@MappedSuperclass
@JsonIgnoreProperties(value = ["createdOn, updatedOn"], allowGetters = true)
@EntityListeners(AuditingEntityListener::class)
abstract class BaseEntity {
@Id
@GeneratedValue(strategy = GenerationType.AUTO)
val id: UUID = UUID.randomUUID()
@Column(nullable = false, updatable = false)
@CreatedDate
var createdOn: LocalDateTime = LocalDateTime.now()
@Column(nullable = true)
@LastModifiedDate
var updatedOn: LocalDateTime? = null
@Column(nullable = true, updatable = false)
@CreatedBy
var createdBy: String? = null
@Column(nullable = true)
@LastModifiedBy
var updatedBy: String? = null
}
我正在将createdBy和UpdatedBy设置为未知。在调试过程中,auditProvider bean被调用,并将用户设置为Unknown,但是如果条件仍然为false,则在传递access_token时。
不确定我缺少什么。
答案 0 :(得分:5)
我能够复制您的问题,但是使用等效的Java设置。问题出在您的JpaAuditingConfiguration
类中。如果您仔细观察当前的JpaAuditingConfiguration
类,就会发生以下情况:
auditorProvider()
函数将尝试生成一个bean。AuditorAware
实例,该实例将始终返回Unknown
。您需要按如下方式更改此类(对不起,我用Java编写,请将其转换为Kotlin):
@Configuration
@EnableJpaAuditing(auditorAwareRef = "auditorProvider")
public class JPAAuditConfig {
@Bean
public AuditorAware<String> auditorProvider() {
return new AuditorAware<String>() {
@Override
public String getCurrentAuditor() {
if (SecurityContextHolder.getContext().getAuthentication() != null) {
OAuth2Authentication auth = (OAuth2Authentication) SecurityContextHolder.getContext().getAuthentication();
Object principal = auth.getUserAuthentication().getPrincipal();
CustomUserDetails userDetails = (CustomUserDetails) principal;
return userDetails.getUsername();
} else {
return "Unknown";
}
}
};
}
}
您可以尝试一下。另外,我怀疑在当前设置下,您将正确填充updatedOn和createdOn。如果是,那意味着所有的JPA和EntityListener魔术实际上都在起作用。您只需要在运行时返回AuditorAware的正确实现即可。
还请注意,我的配置未使用JwtAuthenticationToken
,而是使用了CustomUserDetails
实现。但这与您的问题无关,您当然可以使用当前的令牌类型(JwtAuthenticationToken
)。就是这样,我有一个自己的小应用程序正在运行,并在其中运行了您的问题。
答案 1 :(得分:2)
上述Arun Patra的答案对Java正确。我必须对Kotlin采取以下方式。
@Configuration
@EnableJpaAuditing(auditorAwareRef = "auditorProvider")
class JpaAuditingConfiguration {
@Bean
fun auditorProvider(): AuditorAware<String> {
return CustomAuditorAware()
}
}
private class CustomAuditorAware : AuditorAware<String> {
override fun getCurrentAuditor(): Optional<String> {
return if (SecurityContextHolder.getContext().authentication != null) {
val oauth2 = SecurityContextHolder.getContext().authentication as JwtAuthenticationToken
val loggedInUserId = oauth2.token.claims["sub"].toString()
Optional.of(loggedInUserId)
} else {
Optional.of("Unknown")
}
}
}