Skip to content

Commit

Permalink
fix: oauth2 microservices to run (#278)
Browse files Browse the repository at this point in the history
* fix: more oauth2 microservices fix

* fix: make OAuthDTO accept null values
  • Loading branch information
sendilkumarn authored Apr 20, 2021
1 parent 27ea8d9 commit 6d3b434
Show file tree
Hide file tree
Showing 9 changed files with 99 additions and 106 deletions.
Original file line number Diff line number Diff line change
Expand Up @@ -40,16 +40,16 @@ import org.springframework.core.convert.converter.Converter
<%_ } _%>
<%_ if (applicationType !== 'microservice' || authenticationType !== 'oauth2') { _%>
import org.springframework.http.HttpMethod
<%_ } else { _%>
<%_ if (applicationType !== 'microservice' || authenticationType !== 'oauth2') { _%>
import org.springframework.security.config.annotation.web.builders.WebSecurity;
<%_ } _%>
<%_ } _%>
import org.springframework.security.config.annotation.method.configuration.EnableGlobalMethodSecurity
import org.springframework.security.config.annotation.web.builders.HttpSecurity
<%_ if (!(applicationType === 'microservice' && authenticationType === 'oauth2')) { _%>
<%_ if (applicationType !== 'microservice' || authenticationType !== 'oauth2') { _%>
import org.springframework.security.config.annotation.web.builders.WebSecurity
<%_ } _%>
<%_ } else { _%>
<%_ if (devDatabaseType === 'h2Disk' || devDatabaseType === 'h2Memory') { _%>
import org.springframework.security.config.annotation.web.builders.WebSecurity
<%_ } _%>
<%_ } _%>
import org.springframework.security.config.annotation.web.configuration.EnableWebSecurity
import org.springframework.security.config.annotation.web.configuration.WebSecurityConfigurerAdapter
<%_ if (authenticationType === 'jwt' || (authenticationType === 'oauth2' && applicationType === 'microservice')) { _%>
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -41,8 +41,7 @@ import tech.jhipster.config.JHipsterConstants
@Profile(JHipsterConstants.SPRING_PROFILE_API_DOCS)
@Configuration
class GatewaySwaggerResourcesProvider(
private val routeLocator: RouteLocator,
@Qualifier("SwaggerResources") private val swaggerResourcesProvider: SwaggerResourcesProvider
private val routeLocator: RouteLocator
) : SwaggerResourcesProvider {

@Value("\${eureka.instance.appname:<%= baseName.toLowerCase() %>}")
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -432,18 +432,18 @@ class <%= asEntity('User') %> (
activated,
langKey,
<%_ if (databaseType === 'mongodb' || databaseType === 'neo4j' || databaseType === 'couchbase' || databaseType === 'sql') { _%>
imageUrl<% if (authenticationType !== 'oauth2') { %>,<% } %>
imageUrl,
<%_ } _%>
<%_ if (authenticationType !== 'oauth2') { _%>
activationKey,
resetKey,
resetDate,
<%_ } _%>
mutableSetOf()<% if (databaseType === 'sql' || databaseType === 'mongodb' || databaseType === 'couchbase') { %>,
mutableSetOf(),<% if (databaseType === 'sql' || databaseType === 'mongodb' || databaseType === 'couchbase') { %>
createdBy,
createdDate,
lastModifiedBy,
lastModifiedDate<% } %>
lastModifiedDate,<% } %>
)
<%_ } _%>

Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -303,24 +303,25 @@ class UserRepositoryInternalImpl(val db: DatabaseClient, val r2dbcEntityTemplate
<%_ } _%>

override fun findAllWithAuthorities(pageable: Pageable): Flux<User> {
val property = pageable.sort.map(Sort.Order::getProperty).findFirst().get()
val direction = String.valueOf(pageable.sort.map(Sort.Order::getDirection).findFirst().get())
val property = pageable.sort.map(Sort.Order::getProperty).first()
val direction = pageable.sort.map(Sort.Order::getDirection).first()
val comparator = if (direction == Sort.DEFAULT_DIRECTION) { BeanComparator(property) } else { BeanComparator<Any>(property).reversed() }
val page = pageable.pageNumber
val size = pageable.size
val size = pageable.pageSize

return db
.sql("SELECT * FROM <%= jhiTablePrefix %>_user u LEFT JOIN <%= jhiTablePrefix %>_user_authority ua ON u.id=ua.user_id")
.map { row, metadata ->
.sql("SELECT * FROM jhi_user u LEFT JOIN jhi_user_authority ua ON u.id=ua.user_id")
.map { row, metadata ->
return@map Tuples.of(
r2dbcConverter.read(User::class.java, row, metadata),
r2dbcConverter.read(User::class.java, row, metadata),
Optional.ofNullable(row.get("authority_name", String::class.java))
)
}.all()
.groupBy { it.t1.login }
.flatMap { it.collectList().map { t -> updateUserWithAuthorities(t[0]?.t1, t)} }
.sort(Sort.Direction.fromString(direction) == Sort.DEFAULT_DIRECTION ? BeanComparator<*>(property) : BeanComparator<*>(property).reversed())
.skip(page * size)
.take(size)
.groupBy { it.t1.login }
.flatMap { it.collectList().map { t -> updateUserWithAuthorities(t[0].t1, t) } }
.sort(comparator)
.skip((page * size).toLong())
.take(size.toLong())
}

<%_ if (authenticationType !== 'oauth2') { _%>
Expand All @@ -337,7 +338,7 @@ class UserRepositoryInternalImpl(val db: DatabaseClient, val r2dbcEntityTemplate
<%_ } _%>
<%_ if (authenticationType === 'oauth2') { _%>
override fun create(user: User): Mono<User> {
return r2dbcEntityTemplate.into(User::class.java).using(user)
return r2dbcEntityTemplate.insert(User::class.java).using(user)
.defaultIfEmpty(user)
}

Expand All @@ -354,18 +355,16 @@ class UserRepositoryInternalImpl(val db: DatabaseClient, val r2dbcEntityTemplate
}.all()
.collectList()
.filter { it.isNotEmpty() }
.map { l -> updateUserWithAuthorities(l[0]?.t1, l) }
.map { l -> updateUserWithAuthorities(l[0].t1, l) }
}

private fun updateUserWithAuthorities(user: User?, tuples: List<Tuple2<User, Optional<String>>): User? {
user?.authorities = tuples.filter { it.t2.isPresent }
.map {
val authority = Authority()
authority.name = it.t2.get()
authority
}.toMutableSet()
user
}
private fun updateUserWithAuthorities(user: User, tuples: List<Tuple2<User, Optional<String>>>): User {
user.authorities = tuples.filter { it.t2.isPresent }
.map {
val authority = Authority()
authority.name = it.t2.get()
authority
}.toMutableSet()
return user
}
}
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -42,7 +42,6 @@ import java.time.Instant
import java.util.*
import java.util.regex.Pattern


@Component
class AuthorizationHeaderUtil(
private val clientService: OAuth2AuthorizedClientService,
Expand All @@ -51,7 +50,6 @@ class AuthorizationHeaderUtil(

private val log = LoggerFactory.getLogger(javaClass)


fun getAuthorizationHeader(): String? {
when (val authentication = SecurityContextHolder.getContext().authentication) {
is OAuth2AuthenticationToken -> {
Expand All @@ -63,7 +61,7 @@ class AuthorizationHeaderUtil(

val tokenType = accessToken.tokenType.value

if(isExpired(accessToken)) {
if (isExpired(accessToken)) {
log.info("AccessToken expired, refreshing automatically")
val accessTokenValue = refreshToken(client, authentication)

Expand All @@ -90,7 +88,7 @@ class AuthorizationHeaderUtil(
return null
}

val refreshToken = atr.refreshToken?: client.refreshToken
val refreshToken = atr.refreshToken ?: client.refreshToken
val updatedClient = OAuth2AuthorizedClient(
client.clientRegistration,
client.principalName,
Expand Down Expand Up @@ -119,23 +117,22 @@ class AuthorizationHeaderUtil(
log.error("Unable to refresh token $e")
throw OAuth2AuthenticationException(e.error, e)
}

}

private fun toOAuth2AccessTokenResponse(oAuthIdpResponse: OAuthIdpTokenResponseDTO): OAuth2AccessTokenResponse {
val additionalParameters = hashMapOf<String, Any>(
"id_token" to oAuthIdpResponse.idToken,
"not-before-policy" to oAuthIdpResponse.notBefore,
"refresh_expires_in" to oAuthIdpResponse.refreshExpiresIn,
"session_state" to oAuthIdpResponse.sessionState
)

return OAuth2AccessTokenResponse.withToken(oAuthIdpResponse.accessToken)
.expiresIn(oAuthIdpResponse.expiresIn)
.refreshToken(oAuthIdpResponse.refreshToken)
.additionalParameters(additionalParameters)
.scopes(Pattern.compile("\\s").split(oAuthIdpResponse.scope).toHashSet())
.build()
val additionalParameters = hashMapOf<String, Any?>(
"id_token" to oAuthIdpResponse.idToken,
"not-before-policy" to oAuthIdpResponse.notBefore,
"refresh_expires_in" to oAuthIdpResponse.refreshExpiresIn,
"session_state" to oAuthIdpResponse.sessionState
)

return OAuth2AccessTokenResponse.withToken(oAuthIdpResponse.accessToken)
.expiresIn(oAuthIdpResponse.expiresIn!!)
.refreshToken(oAuthIdpResponse.refreshToken)
.additionalParameters(additionalParameters)
.scopes(Pattern.compile("\\s").split(oAuthIdpResponse.scope).toHashSet())
.build()
}

private fun restTemplate(clientId: String?, clientSecret: String?): RestTemplate {
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -5,37 +5,37 @@ import java.util.*

open class OAuthIdpTokenResponseDTO(
@JsonProperty("token_type")
var tokenType: String,
var tokenType: String? = null,

var scope: String,
var scope: String? = null,

@JsonProperty("expires_in")
var expiresIn: Long,
var expiresIn: Long? = null,


@JsonProperty("ext_expires_in")
var extExpiresIn: Long,
var extExpiresIn: Long? = null,

@JsonProperty("expires_on")
var expiresOn: Long,
var expiresOn: Long? = null,

@JsonProperty("not-before-policy")
var notBefore: Long,
var notBefore: Long? = null,

var resource: UUID,
var resource: UUID? = null,

@JsonProperty("access_token")
var accessToken: String,
var accessToken: String? = null,

@JsonProperty("refresh_token")
var refreshToken: String,
var refreshToken: String? = null,

@JsonProperty("id_token")
var idToken: String,
var idToken: String? = null,

@JsonProperty("session_state")
var sessionState: String,
var sessionState: String? = null,

@JsonProperty("refresh_expires_in")
var refreshExpiresIn: String
var refreshExpiresIn: String? = null
)
Original file line number Diff line number Diff line change
Expand Up @@ -615,13 +615,13 @@ class UserService<% if (databaseType !== 'no') { %>(
<%_ if (reactive) { _%>
<%_ if (databaseType === 'sql' && authenticationType === 'oauth2') { _%>
@Transactional
fun saveUser(User user) = saveUser(user, false)
fun saveUser(user: User) = saveUser(user, false)

<%_ } _%>
<%_ if (databaseType === 'sql') { _%>
@Transactional
<%_ } _%>
<% if (databaseType !== 'sql') { %>private <% } %> fun saveUser(user: <%= asEntity('User') %><% if (databaseType === 'sql' && authenticationType === 'oauth2') { %>, forceCreate: boolean<% } %>): Mono<<%= asEntity('User') %>> {
<% if (databaseType !== 'sql') { %>private <% } %> fun saveUser(user: <%= asEntity('User') %><% if (databaseType === 'sql' && authenticationType === 'oauth2') { %>, forceCreate: Boolean<% } %>): Mono<<%= asEntity('User') %>> {
<%_ if (databaseType === 'cassandra') { _%>
return userRepository.save(user)
<%_ } else { _%>
Expand Down
Loading

0 comments on commit 6d3b434

Please sign in to comment.