repo
stringclasses
1k values
file_url
stringlengths
96
373
file_path
stringlengths
11
294
content
stringlengths
0
32.8k
language
stringclasses
1 value
license
stringclasses
6 values
commit_sha
stringclasses
1k values
retrieved_at
stringdate
2026-01-04 14:45:56
2026-01-04 18:30:23
truncated
bool
2 classes
eugenp/tutorials
https://github.com/eugenp/tutorials/blob/4463e58ffb73fe599bac2479abd84598c6e70a1a/jhipster-modules/jhipster-uaa/uaa/src/main/java/com/baeldung/jhipster/uaa/domain/package-info.java
jhipster-modules/jhipster-uaa/uaa/src/main/java/com/baeldung/jhipster/uaa/domain/package-info.java
/** * JPA domain objects. */ package com.baeldung.jhipster.uaa.domain;
java
MIT
4463e58ffb73fe599bac2479abd84598c6e70a1a
2026-01-04T14:45:57.069771Z
false
eugenp/tutorials
https://github.com/eugenp/tutorials/blob/4463e58ffb73fe599bac2479abd84598c6e70a1a/jhipster-modules/jhipster-uaa/uaa/src/main/java/com/baeldung/jhipster/uaa/domain/Authority.java
jhipster-modules/jhipster-uaa/uaa/src/main/java/com/baeldung/jhipster/uaa/domain/Authority.java
package com.baeldung.jhipster.uaa.domain; import org.hibernate.annotations.Cache; import org.hibernate.annotations.CacheConcurrencyStrategy; import javax.persistence.Entity; import javax.persistence.Id; import javax.persistence.Table; import javax.persistence.Column; import javax.validation.constraints.NotNull; import javax.validation.constraints.Size; import java.io.Serializable; /** * An authority (a security role) used by Spring Security. */ @Entity @Table(name = "jhi_authority") @Cache(usage = CacheConcurrencyStrategy.NONSTRICT_READ_WRITE) public class Authority implements Serializable { private static final long serialVersionUID = 1L; @NotNull @Size(max = 50) @Id @Column(length = 50) private String name; public String getName() { return name; } public void setName(String name) { this.name = name; } @Override public boolean equals(Object o) { if (this == o) { return true; } if (o == null || getClass() != o.getClass()) { return false; } Authority authority = (Authority) o; return !(name != null ? !name.equals(authority.name) : authority.name != null); } @Override public int hashCode() { return name != null ? name.hashCode() : 0; } @Override public String toString() { return "Authority{" + "name='" + name + '\'' + "}"; } }
java
MIT
4463e58ffb73fe599bac2479abd84598c6e70a1a
2026-01-04T14:45:57.069771Z
false
eugenp/tutorials
https://github.com/eugenp/tutorials/blob/4463e58ffb73fe599bac2479abd84598c6e70a1a/jhipster-modules/jhipster-uaa/uaa/src/main/java/com/baeldung/jhipster/uaa/domain/PersistentAuditEvent.java
jhipster-modules/jhipster-uaa/uaa/src/main/java/com/baeldung/jhipster/uaa/domain/PersistentAuditEvent.java
package com.baeldung.jhipster.uaa.domain; import javax.persistence.*; import javax.validation.constraints.NotNull; import java.io.Serializable; import java.time.Instant; import java.util.HashMap; import java.util.Map; /** * Persist AuditEvent managed by the Spring Boot actuator. * * @see org.springframework.boot.actuate.audit.AuditEvent */ @Entity @Table(name = "jhi_persistent_audit_event") public class PersistentAuditEvent implements Serializable { private static final long serialVersionUID = 1L; @Id @GeneratedValue(strategy = GenerationType.IDENTITY) @Column(name = "event_id") private Long id; @NotNull @Column(nullable = false) private String principal; @Column(name = "event_date") private Instant auditEventDate; @Column(name = "event_type") private String auditEventType; @ElementCollection @MapKeyColumn(name = "name") @Column(name = "value") @CollectionTable(name = "jhi_persistent_audit_evt_data", joinColumns=@JoinColumn(name="event_id")) private Map<String, String> data = new HashMap<>(); public Long getId() { return id; } public void setId(Long id) { this.id = id; } public String getPrincipal() { return principal; } public void setPrincipal(String principal) { this.principal = principal; } public Instant getAuditEventDate() { return auditEventDate; } public void setAuditEventDate(Instant auditEventDate) { this.auditEventDate = auditEventDate; } public String getAuditEventType() { return auditEventType; } public void setAuditEventType(String auditEventType) { this.auditEventType = auditEventType; } public Map<String, String> getData() { return data; } public void setData(Map<String, String> data) { this.data = data; } }
java
MIT
4463e58ffb73fe599bac2479abd84598c6e70a1a
2026-01-04T14:45:57.069771Z
false
eugenp/tutorials
https://github.com/eugenp/tutorials/blob/4463e58ffb73fe599bac2479abd84598c6e70a1a/jhipster-modules/jhipster-uaa/uaa/src/main/java/com/baeldung/jhipster/uaa/domain/User.java
jhipster-modules/jhipster-uaa/uaa/src/main/java/com/baeldung/jhipster/uaa/domain/User.java
package com.baeldung.jhipster.uaa.domain; import com.baeldung.jhipster.uaa.config.Constants; import com.fasterxml.jackson.annotation.JsonIgnore; import org.apache.commons.lang3.StringUtils; import org.hibernate.annotations.BatchSize; import org.hibernate.annotations.Cache; import org.hibernate.annotations.CacheConcurrencyStrategy; import javax.validation.constraints.Email; import javax.persistence.*; import javax.validation.constraints.NotNull; import javax.validation.constraints.Pattern; import javax.validation.constraints.Size; import java.io.Serializable; import java.util.HashSet; import java.util.Locale; import java.util.Objects; import java.util.Set; import java.time.Instant; /** * A user. */ @Entity @Table(name = "jhi_user") @Cache(usage = CacheConcurrencyStrategy.NONSTRICT_READ_WRITE) public class User extends AbstractAuditingEntity implements Serializable { private static final long serialVersionUID = 1L; @Id @GeneratedValue(strategy = GenerationType.IDENTITY) private Long id; @NotNull @Pattern(regexp = Constants.LOGIN_REGEX) @Size(min = 1, max = 50) @Column(length = 50, unique = true, nullable = false) private String login; @JsonIgnore @NotNull @Size(min = 60, max = 60) @Column(name = "password_hash", length = 60, nullable = false) private String password; @Size(max = 50) @Column(name = "first_name", length = 50) private String firstName; @Size(max = 50) @Column(name = "last_name", length = 50) private String lastName; @Email @Size(min = 5, max = 254) @Column(length = 254, unique = true) private String email; @NotNull @Column(nullable = false) private boolean activated = false; @Size(min = 2, max = 6) @Column(name = "lang_key", length = 6) private String langKey; @Size(max = 256) @Column(name = "image_url", length = 256) private String imageUrl; @Size(max = 20) @Column(name = "activation_key", length = 20) @JsonIgnore private String activationKey; @Size(max = 20) @Column(name = "reset_key", length = 20) @JsonIgnore private String resetKey; @Column(name = "reset_date") private Instant resetDate = null; @JsonIgnore @ManyToMany @JoinTable( name = "jhi_user_authority", joinColumns = {@JoinColumn(name = "user_id", referencedColumnName = "id")}, inverseJoinColumns = {@JoinColumn(name = "authority_name", referencedColumnName = "name")}) @Cache(usage = CacheConcurrencyStrategy.NONSTRICT_READ_WRITE) @BatchSize(size = 20) private Set<Authority> authorities = new HashSet<>(); public Long getId() { return id; } public void setId(Long id) { this.id = id; } public String getLogin() { return login; } // Lowercase the login before saving it in database public void setLogin(String login) { this.login = StringUtils.lowerCase(login, Locale.ENGLISH); } public String getPassword() { return password; } public void setPassword(String password) { this.password = password; } public String getFirstName() { return firstName; } public void setFirstName(String firstName) { this.firstName = firstName; } public String getLastName() { return lastName; } public void setLastName(String lastName) { this.lastName = lastName; } public String getEmail() { return email; } public void setEmail(String email) { this.email = email; } public String getImageUrl() { return imageUrl; } public void setImageUrl(String imageUrl) { this.imageUrl = imageUrl; } public boolean getActivated() { return activated; } public void setActivated(boolean activated) { this.activated = activated; } public String getActivationKey() { return activationKey; } public void setActivationKey(String activationKey) { this.activationKey = activationKey; } public String getResetKey() { return resetKey; } public void setResetKey(String resetKey) { this.resetKey = resetKey; } public Instant getResetDate() { return resetDate; } public void setResetDate(Instant resetDate) { this.resetDate = resetDate; } public String getLangKey() { return langKey; } public void setLangKey(String langKey) { this.langKey = langKey; } public Set<Authority> getAuthorities() { return authorities; } public void setAuthorities(Set<Authority> authorities) { this.authorities = authorities; } @Override public boolean equals(Object o) { if (this == o) { return true; } if (o == null || getClass() != o.getClass()) { return false; } User user = (User) o; return !(user.getId() == null || getId() == null) && Objects.equals(getId(), user.getId()); } @Override public int hashCode() { return Objects.hashCode(getId()); } @Override public String toString() { return "User{" + "login='" + login + '\'' + ", firstName='" + firstName + '\'' + ", lastName='" + lastName + '\'' + ", email='" + email + '\'' + ", imageUrl='" + imageUrl + '\'' + ", activated='" + activated + '\'' + ", langKey='" + langKey + '\'' + ", activationKey='" + activationKey + '\'' + "}"; } }
java
MIT
4463e58ffb73fe599bac2479abd84598c6e70a1a
2026-01-04T14:45:57.069771Z
false
eugenp/tutorials
https://github.com/eugenp/tutorials/blob/4463e58ffb73fe599bac2479abd84598c6e70a1a/jhipster-modules/jhipster-uaa/uaa/src/main/java/com/baeldung/jhipster/uaa/domain/AbstractAuditingEntity.java
jhipster-modules/jhipster-uaa/uaa/src/main/java/com/baeldung/jhipster/uaa/domain/AbstractAuditingEntity.java
package com.baeldung.jhipster.uaa.domain; import com.fasterxml.jackson.annotation.JsonIgnore; import org.hibernate.envers.Audited; import org.springframework.data.annotation.CreatedBy; import org.springframework.data.annotation.CreatedDate; import org.springframework.data.annotation.LastModifiedBy; import org.springframework.data.annotation.LastModifiedDate; import org.springframework.data.jpa.domain.support.AuditingEntityListener; import java.io.Serializable; import java.time.Instant; import javax.persistence.Column; import javax.persistence.EntityListeners; import javax.persistence.MappedSuperclass; /** * Base abstract class for entities which will hold definitions for created, last modified by and created, * last modified by date. */ @MappedSuperclass @Audited @EntityListeners(AuditingEntityListener.class) public abstract class AbstractAuditingEntity implements Serializable { private static final long serialVersionUID = 1L; @CreatedBy @Column(name = "created_by", nullable = false, length = 50, updatable = false) @JsonIgnore private String createdBy; @CreatedDate @Column(name = "created_date", nullable = false, updatable = false) @JsonIgnore private Instant createdDate = Instant.now(); @LastModifiedBy @Column(name = "last_modified_by", length = 50) @JsonIgnore private String lastModifiedBy; @LastModifiedDate @Column(name = "last_modified_date") @JsonIgnore private Instant lastModifiedDate = Instant.now(); public String getCreatedBy() { return createdBy; } public void setCreatedBy(String createdBy) { this.createdBy = createdBy; } public Instant getCreatedDate() { return createdDate; } public void setCreatedDate(Instant createdDate) { this.createdDate = createdDate; } public String getLastModifiedBy() { return lastModifiedBy; } public void setLastModifiedBy(String lastModifiedBy) { this.lastModifiedBy = lastModifiedBy; } public Instant getLastModifiedDate() { return lastModifiedDate; } public void setLastModifiedDate(Instant lastModifiedDate) { this.lastModifiedDate = lastModifiedDate; } }
java
MIT
4463e58ffb73fe599bac2479abd84598c6e70a1a
2026-01-04T14:45:57.069771Z
false
eugenp/tutorials
https://github.com/eugenp/tutorials/blob/4463e58ffb73fe599bac2479abd84598c6e70a1a/jhipster-modules/jhipster-uaa/uaa/src/main/java/com/baeldung/jhipster/uaa/repository/UserRepository.java
jhipster-modules/jhipster-uaa/uaa/src/main/java/com/baeldung/jhipster/uaa/repository/UserRepository.java
package com.baeldung.jhipster.uaa.repository; import com.baeldung.jhipster.uaa.domain.User; import org.springframework.cache.annotation.Cacheable; import org.springframework.data.domain.Page; import org.springframework.data.domain.Pageable; import org.springframework.data.jpa.repository.EntityGraph; import org.springframework.data.jpa.repository.JpaRepository; import org.springframework.stereotype.Repository; import java.util.List; import java.util.Optional; import java.time.Instant; /** * Spring Data JPA repository for the User entity. */ @Repository public interface UserRepository extends JpaRepository<User, Long> { String USERS_BY_LOGIN_CACHE = "usersByLogin"; String USERS_BY_EMAIL_CACHE = "usersByEmail"; Optional<User> findOneByActivationKey(String activationKey); List<User> findAllByActivatedIsFalseAndCreatedDateBefore(Instant dateTime); Optional<User> findOneByResetKey(String resetKey); Optional<User> findOneByEmailIgnoreCase(String email); Optional<User> findOneByLogin(String login); @EntityGraph(attributePaths = "authorities") Optional<User> findOneWithAuthoritiesById(Long id); @EntityGraph(attributePaths = "authorities") @Cacheable(cacheNames = USERS_BY_LOGIN_CACHE) Optional<User> findOneWithAuthoritiesByLogin(String login); @EntityGraph(attributePaths = "authorities") @Cacheable(cacheNames = USERS_BY_EMAIL_CACHE) Optional<User> findOneWithAuthoritiesByEmail(String email); Page<User> findAllByLoginNot(Pageable pageable, String login); }
java
MIT
4463e58ffb73fe599bac2479abd84598c6e70a1a
2026-01-04T14:45:57.069771Z
false
eugenp/tutorials
https://github.com/eugenp/tutorials/blob/4463e58ffb73fe599bac2479abd84598c6e70a1a/jhipster-modules/jhipster-uaa/uaa/src/main/java/com/baeldung/jhipster/uaa/repository/package-info.java
jhipster-modules/jhipster-uaa/uaa/src/main/java/com/baeldung/jhipster/uaa/repository/package-info.java
/** * Spring Data JPA repositories. */ package com.baeldung.jhipster.uaa.repository;
java
MIT
4463e58ffb73fe599bac2479abd84598c6e70a1a
2026-01-04T14:45:57.069771Z
false
eugenp/tutorials
https://github.com/eugenp/tutorials/blob/4463e58ffb73fe599bac2479abd84598c6e70a1a/jhipster-modules/jhipster-uaa/uaa/src/main/java/com/baeldung/jhipster/uaa/repository/CustomAuditEventRepository.java
jhipster-modules/jhipster-uaa/uaa/src/main/java/com/baeldung/jhipster/uaa/repository/CustomAuditEventRepository.java
package com.baeldung.jhipster.uaa.repository; import com.baeldung.jhipster.uaa.config.Constants; import com.baeldung.jhipster.uaa.config.audit.AuditEventConverter; import com.baeldung.jhipster.uaa.domain.PersistentAuditEvent; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import org.springframework.boot.actuate.audit.AuditEvent; import org.springframework.boot.actuate.audit.AuditEventRepository; import org.springframework.stereotype.Repository; import org.springframework.transaction.annotation.Propagation; import org.springframework.transaction.annotation.Transactional; import java.time.Instant; import java.util.*; /** * An implementation of Spring Boot's AuditEventRepository. */ @Repository public class CustomAuditEventRepository implements AuditEventRepository { private static final String AUTHORIZATION_FAILURE = "AUTHORIZATION_FAILURE"; /** * Should be the same as in Liquibase migration. */ protected static final int EVENT_DATA_COLUMN_MAX_LENGTH = 255; private final PersistenceAuditEventRepository persistenceAuditEventRepository; private final AuditEventConverter auditEventConverter; private final Logger log = LoggerFactory.getLogger(getClass()); public CustomAuditEventRepository(PersistenceAuditEventRepository persistenceAuditEventRepository, AuditEventConverter auditEventConverter) { this.persistenceAuditEventRepository = persistenceAuditEventRepository; this.auditEventConverter = auditEventConverter; } @Override public List<AuditEvent> find(String principal, Instant after, String type) { Iterable<PersistentAuditEvent> persistentAuditEvents = persistenceAuditEventRepository.findByPrincipalAndAuditEventDateAfterAndAuditEventType(principal, after, type); return auditEventConverter.convertToAuditEvent(persistentAuditEvents); } @Override @Transactional(propagation = Propagation.REQUIRES_NEW) public void add(AuditEvent event) { if (!AUTHORIZATION_FAILURE.equals(event.getType()) && !Constants.ANONYMOUS_USER.equals(event.getPrincipal())) { PersistentAuditEvent persistentAuditEvent = new PersistentAuditEvent(); persistentAuditEvent.setPrincipal(event.getPrincipal()); persistentAuditEvent.setAuditEventType(event.getType()); persistentAuditEvent.setAuditEventDate(event.getTimestamp()); Map<String, String> eventData = auditEventConverter.convertDataToStrings(event.getData()); persistentAuditEvent.setData(truncate(eventData)); persistenceAuditEventRepository.save(persistentAuditEvent); } } /** * Truncate event data that might exceed column length. */ private Map<String, String> truncate(Map<String, String> data) { Map<String, String> results = new HashMap<>(); if (data != null) { for (Map.Entry<String, String> entry : data.entrySet()) { String value = entry.getValue(); if (value != null) { int length = value.length(); if (length > EVENT_DATA_COLUMN_MAX_LENGTH) { value = value.substring(0, EVENT_DATA_COLUMN_MAX_LENGTH); log.warn("Event data for {} too long ({}) has been truncated to {}. Consider increasing column width.", entry.getKey(), length, EVENT_DATA_COLUMN_MAX_LENGTH); } } results.put(entry.getKey(), value); } } return results; } }
java
MIT
4463e58ffb73fe599bac2479abd84598c6e70a1a
2026-01-04T14:45:57.069771Z
false
eugenp/tutorials
https://github.com/eugenp/tutorials/blob/4463e58ffb73fe599bac2479abd84598c6e70a1a/jhipster-modules/jhipster-uaa/uaa/src/main/java/com/baeldung/jhipster/uaa/repository/PersistenceAuditEventRepository.java
jhipster-modules/jhipster-uaa/uaa/src/main/java/com/baeldung/jhipster/uaa/repository/PersistenceAuditEventRepository.java
package com.baeldung.jhipster.uaa.repository; import com.baeldung.jhipster.uaa.domain.PersistentAuditEvent; import org.springframework.data.domain.Page; import org.springframework.data.domain.Pageable; import org.springframework.data.jpa.repository.JpaRepository; import java.time.Instant; import java.util.List; /** * Spring Data JPA repository for the PersistentAuditEvent entity. */ public interface PersistenceAuditEventRepository extends JpaRepository<PersistentAuditEvent, Long> { List<PersistentAuditEvent> findByPrincipal(String principal); List<PersistentAuditEvent> findByAuditEventDateAfter(Instant after); List<PersistentAuditEvent> findByPrincipalAndAuditEventDateAfter(String principal, Instant after); List<PersistentAuditEvent> findByPrincipalAndAuditEventDateAfterAndAuditEventType(String principal, Instant after, String type); Page<PersistentAuditEvent> findAllByAuditEventDateBetween(Instant fromDate, Instant toDate, Pageable pageable); }
java
MIT
4463e58ffb73fe599bac2479abd84598c6e70a1a
2026-01-04T14:45:57.069771Z
false
eugenp/tutorials
https://github.com/eugenp/tutorials/blob/4463e58ffb73fe599bac2479abd84598c6e70a1a/jhipster-modules/jhipster-uaa/uaa/src/main/java/com/baeldung/jhipster/uaa/repository/AuthorityRepository.java
jhipster-modules/jhipster-uaa/uaa/src/main/java/com/baeldung/jhipster/uaa/repository/AuthorityRepository.java
package com.baeldung.jhipster.uaa.repository; import com.baeldung.jhipster.uaa.domain.Authority; import org.springframework.data.jpa.repository.JpaRepository; /** * Spring Data JPA repository for the Authority entity. */ public interface AuthorityRepository extends JpaRepository<Authority, String> { }
java
MIT
4463e58ffb73fe599bac2479abd84598c6e70a1a
2026-01-04T14:45:57.069771Z
false
eugenp/tutorials
https://github.com/eugenp/tutorials/blob/4463e58ffb73fe599bac2479abd84598c6e70a1a/jhipster-modules/jhipster-uaa/uaa/src/main/java/com/baeldung/jhipster/uaa/security/IatTokenEnhancer.java
jhipster-modules/jhipster-uaa/uaa/src/main/java/com/baeldung/jhipster/uaa/security/IatTokenEnhancer.java
package com.baeldung.jhipster.uaa.security; import org.springframework.security.oauth2.common.DefaultOAuth2AccessToken; import org.springframework.security.oauth2.common.OAuth2AccessToken; import org.springframework.security.oauth2.provider.OAuth2Authentication; import org.springframework.security.oauth2.provider.token.TokenEnhancer; import org.springframework.stereotype.Component; import java.util.LinkedHashMap; import java.util.Map; /** * Adds the standard "iat" claim to tokens so we know when they have been created. * This is needed for a session timeout due to inactivity (ignored in case of "remember-me"). */ @Component public class IatTokenEnhancer implements TokenEnhancer { @Override public OAuth2AccessToken enhance(OAuth2AccessToken accessToken, OAuth2Authentication authentication) { addClaims((DefaultOAuth2AccessToken) accessToken); return accessToken; } private void addClaims(DefaultOAuth2AccessToken accessToken) { DefaultOAuth2AccessToken token = accessToken; Map<String, Object> additionalInformation = token.getAdditionalInformation(); if (additionalInformation.isEmpty()) { additionalInformation = new LinkedHashMap<String, Object>(); } //add "iat" claim with current time in secs //this is used for an inactive session timeout additionalInformation.put("iat", new Integer((int)(System.currentTimeMillis()/1000L))); token.setAdditionalInformation(additionalInformation); } }
java
MIT
4463e58ffb73fe599bac2479abd84598c6e70a1a
2026-01-04T14:45:57.069771Z
false
eugenp/tutorials
https://github.com/eugenp/tutorials/blob/4463e58ffb73fe599bac2479abd84598c6e70a1a/jhipster-modules/jhipster-uaa/uaa/src/main/java/com/baeldung/jhipster/uaa/security/package-info.java
jhipster-modules/jhipster-uaa/uaa/src/main/java/com/baeldung/jhipster/uaa/security/package-info.java
/** * Spring Security configuration. */ package com.baeldung.jhipster.uaa.security;
java
MIT
4463e58ffb73fe599bac2479abd84598c6e70a1a
2026-01-04T14:45:57.069771Z
false
eugenp/tutorials
https://github.com/eugenp/tutorials/blob/4463e58ffb73fe599bac2479abd84598c6e70a1a/jhipster-modules/jhipster-uaa/uaa/src/main/java/com/baeldung/jhipster/uaa/security/SpringSecurityAuditorAware.java
jhipster-modules/jhipster-uaa/uaa/src/main/java/com/baeldung/jhipster/uaa/security/SpringSecurityAuditorAware.java
package com.baeldung.jhipster.uaa.security; import com.baeldung.jhipster.uaa.config.Constants; import java.util.Optional; import org.springframework.data.domain.AuditorAware; import org.springframework.stereotype.Component; /** * Implementation of AuditorAware based on Spring Security. */ @Component public class SpringSecurityAuditorAware implements AuditorAware<String> { @Override public Optional<String> getCurrentAuditor() { return Optional.of(SecurityUtils.getCurrentUserLogin().orElse(Constants.SYSTEM_ACCOUNT)); } }
java
MIT
4463e58ffb73fe599bac2479abd84598c6e70a1a
2026-01-04T14:45:57.069771Z
false
eugenp/tutorials
https://github.com/eugenp/tutorials/blob/4463e58ffb73fe599bac2479abd84598c6e70a1a/jhipster-modules/jhipster-uaa/uaa/src/main/java/com/baeldung/jhipster/uaa/security/UserNotActivatedException.java
jhipster-modules/jhipster-uaa/uaa/src/main/java/com/baeldung/jhipster/uaa/security/UserNotActivatedException.java
package com.baeldung.jhipster.uaa.security; import org.springframework.security.core.AuthenticationException; /** * This exception is thrown in case of a not activated user trying to authenticate. */ public class UserNotActivatedException extends AuthenticationException { private static final long serialVersionUID = 1L; public UserNotActivatedException(String message) { super(message); } public UserNotActivatedException(String message, Throwable t) { super(message, t); } }
java
MIT
4463e58ffb73fe599bac2479abd84598c6e70a1a
2026-01-04T14:45:57.069771Z
false
eugenp/tutorials
https://github.com/eugenp/tutorials/blob/4463e58ffb73fe599bac2479abd84598c6e70a1a/jhipster-modules/jhipster-uaa/uaa/src/main/java/com/baeldung/jhipster/uaa/security/SecurityUtils.java
jhipster-modules/jhipster-uaa/uaa/src/main/java/com/baeldung/jhipster/uaa/security/SecurityUtils.java
package com.baeldung.jhipster.uaa.security; import org.springframework.security.core.context.SecurityContext; import org.springframework.security.core.context.SecurityContextHolder; import org.springframework.security.core.userdetails.UserDetails; import java.util.Optional; /** * Utility class for Spring Security. */ public final class SecurityUtils { private SecurityUtils() { } /** * Get the login of the current user. * * @return the login of the current user */ public static Optional<String> getCurrentUserLogin() { SecurityContext securityContext = SecurityContextHolder.getContext(); return Optional.ofNullable(securityContext.getAuthentication()) .map(authentication -> { if (authentication.getPrincipal() instanceof UserDetails) { UserDetails springSecurityUser = (UserDetails) authentication.getPrincipal(); return springSecurityUser.getUsername(); } else if (authentication.getPrincipal() instanceof String) { return (String) authentication.getPrincipal(); } return null; }); } /** * Check if a user is authenticated. * * @return true if the user is authenticated, false otherwise */ public static boolean isAuthenticated() { SecurityContext securityContext = SecurityContextHolder.getContext(); return Optional.ofNullable(securityContext.getAuthentication()) .map(authentication -> authentication.getAuthorities().stream() .noneMatch(grantedAuthority -> grantedAuthority.getAuthority().equals(AuthoritiesConstants.ANONYMOUS))) .orElse(false); } /** * If the current user has a specific authority (security role). * <p> * The name of this method comes from the isUserInRole() method in the Servlet API * * @param authority the authority to check * @return true if the current user has the authority, false otherwise */ public static boolean isCurrentUserInRole(String authority) { SecurityContext securityContext = SecurityContextHolder.getContext(); return Optional.ofNullable(securityContext.getAuthentication()) .map(authentication -> authentication.getAuthorities().stream() .anyMatch(grantedAuthority -> grantedAuthority.getAuthority().equals(authority))) .orElse(false); } }
java
MIT
4463e58ffb73fe599bac2479abd84598c6e70a1a
2026-01-04T14:45:57.069771Z
false
eugenp/tutorials
https://github.com/eugenp/tutorials/blob/4463e58ffb73fe599bac2479abd84598c6e70a1a/jhipster-modules/jhipster-uaa/uaa/src/main/java/com/baeldung/jhipster/uaa/security/AuthoritiesConstants.java
jhipster-modules/jhipster-uaa/uaa/src/main/java/com/baeldung/jhipster/uaa/security/AuthoritiesConstants.java
package com.baeldung.jhipster.uaa.security; /** * Constants for Spring Security authorities. */ public final class AuthoritiesConstants { public static final String ADMIN = "ROLE_ADMIN"; public static final String USER = "ROLE_USER"; public static final String ANONYMOUS = "ROLE_ANONYMOUS"; private AuthoritiesConstants() { } }
java
MIT
4463e58ffb73fe599bac2479abd84598c6e70a1a
2026-01-04T14:45:57.069771Z
false
eugenp/tutorials
https://github.com/eugenp/tutorials/blob/4463e58ffb73fe599bac2479abd84598c6e70a1a/jhipster-modules/jhipster-uaa/uaa/src/main/java/com/baeldung/jhipster/uaa/security/DomainUserDetailsService.java
jhipster-modules/jhipster-uaa/uaa/src/main/java/com/baeldung/jhipster/uaa/security/DomainUserDetailsService.java
package com.baeldung.jhipster.uaa.security; import com.baeldung.jhipster.uaa.domain.User; import com.baeldung.jhipster.uaa.repository.UserRepository; import org.hibernate.validator.internal.constraintvalidators.hv.EmailValidator; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import org.springframework.security.core.GrantedAuthority; import org.springframework.security.core.authority.SimpleGrantedAuthority; import org.springframework.security.core.userdetails.UserDetails; import org.springframework.security.core.userdetails.UserDetailsService; import org.springframework.security.core.userdetails.UsernameNotFoundException; import org.springframework.stereotype.Component; import org.springframework.transaction.annotation.Transactional; import java.util.*; import java.util.stream.Collectors; /** * Authenticate a user from the database. */ @Component("userDetailsService") public class DomainUserDetailsService implements UserDetailsService { private final Logger log = LoggerFactory.getLogger(DomainUserDetailsService.class); private final UserRepository userRepository; public DomainUserDetailsService(UserRepository userRepository) { this.userRepository = userRepository; } @Override @Transactional public UserDetails loadUserByUsername(final String login) { log.debug("Authenticating {}", login); if (new EmailValidator().isValid(login, null)) { return userRepository.findOneWithAuthoritiesByEmail(login) .map(user -> createSpringSecurityUser(login, user)) .orElseThrow(() -> new UsernameNotFoundException("User with email " + login + " was not found in the database")); } String lowercaseLogin = login.toLowerCase(Locale.ENGLISH); return userRepository.findOneWithAuthoritiesByLogin(lowercaseLogin) .map(user -> createSpringSecurityUser(lowercaseLogin, user)) .orElseThrow(() -> new UsernameNotFoundException("User " + lowercaseLogin + " was not found in the database")); } private org.springframework.security.core.userdetails.User createSpringSecurityUser(String lowercaseLogin, User user) { if (!user.getActivated()) { throw new UserNotActivatedException("User " + lowercaseLogin + " was not activated"); } List<GrantedAuthority> grantedAuthorities = user.getAuthorities().stream() .map(authority -> new SimpleGrantedAuthority(authority.getName())) .collect(Collectors.toList()); return new org.springframework.security.core.userdetails.User(user.getLogin(), user.getPassword(), grantedAuthorities); } }
java
MIT
4463e58ffb73fe599bac2479abd84598c6e70a1a
2026-01-04T14:45:57.069771Z
false
eugenp/tutorials
https://github.com/eugenp/tutorials/blob/4463e58ffb73fe599bac2479abd84598c6e70a1a/jhipster-modules/jhipster-uaa/uaa/src/main/java/com/baeldung/jhipster/uaa/config/ApplicationProperties.java
jhipster-modules/jhipster-uaa/uaa/src/main/java/com/baeldung/jhipster/uaa/config/ApplicationProperties.java
package com.baeldung.jhipster.uaa.config; import org.springframework.boot.context.properties.ConfigurationProperties; /** * Properties specific to Uaa. * <p> * Properties are configured in the application.yml file. * See {@link io.github.jhipster.config.JHipsterProperties} for a good example. */ @ConfigurationProperties(prefix = "application", ignoreUnknownFields = false) public class ApplicationProperties { }
java
MIT
4463e58ffb73fe599bac2479abd84598c6e70a1a
2026-01-04T14:45:57.069771Z
false
eugenp/tutorials
https://github.com/eugenp/tutorials/blob/4463e58ffb73fe599bac2479abd84598c6e70a1a/jhipster-modules/jhipster-uaa/uaa/src/main/java/com/baeldung/jhipster/uaa/config/CloudDatabaseConfiguration.java
jhipster-modules/jhipster-uaa/uaa/src/main/java/com/baeldung/jhipster/uaa/config/CloudDatabaseConfiguration.java
package com.baeldung.jhipster.uaa.config; import io.github.jhipster.config.JHipsterConstants; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import org.springframework.cache.CacheManager; import org.springframework.cloud.config.java.AbstractCloudConfig; import org.springframework.context.annotation.*; import javax.sql.DataSource; @Configuration @Profile(JHipsterConstants.SPRING_PROFILE_CLOUD) public class CloudDatabaseConfiguration extends AbstractCloudConfig { private final Logger log = LoggerFactory.getLogger(CloudDatabaseConfiguration.class); @Bean public DataSource dataSource(CacheManager cacheManager) { log.info("Configuring JDBC datasource from a cloud provider"); return connectionFactory().dataSource(); } }
java
MIT
4463e58ffb73fe599bac2479abd84598c6e70a1a
2026-01-04T14:45:57.069771Z
false
eugenp/tutorials
https://github.com/eugenp/tutorials/blob/4463e58ffb73fe599bac2479abd84598c6e70a1a/jhipster-modules/jhipster-uaa/uaa/src/main/java/com/baeldung/jhipster/uaa/config/DefaultProfileUtil.java
jhipster-modules/jhipster-uaa/uaa/src/main/java/com/baeldung/jhipster/uaa/config/DefaultProfileUtil.java
package com.baeldung.jhipster.uaa.config; import io.github.jhipster.config.JHipsterConstants; import org.springframework.boot.SpringApplication; import org.springframework.core.env.Environment; import java.util.*; /** * Utility class to load a Spring profile to be used as default * when there is no <code>spring.profiles.active</code> set in the environment or as command line argument. * If the value is not available in <code>application.yml</code> then <code>dev</code> profile will be used as default. */ public final class DefaultProfileUtil { private static final String SPRING_PROFILE_DEFAULT = "spring.profiles.default"; private DefaultProfileUtil() { } /** * Set a default to use when no profile is configured. * * @param app the Spring application */ public static void addDefaultProfile(SpringApplication app) { Map<String, Object> defProperties = new HashMap<>(); /* * The default profile to use when no other profiles are defined * This cannot be set in the <code>application.yml</code> file. * See https://github.com/spring-projects/spring-boot/issues/1219 */ defProperties.put(SPRING_PROFILE_DEFAULT, JHipsterConstants.SPRING_PROFILE_DEVELOPMENT); app.setDefaultProperties(defProperties); } /** * Get the profiles that are applied else get default profiles. * * @param env spring environment * @return profiles */ public static String[] getActiveProfiles(Environment env) { String[] profiles = env.getActiveProfiles(); if (profiles.length == 0) { return env.getDefaultProfiles(); } return profiles; } }
java
MIT
4463e58ffb73fe599bac2479abd84598c6e70a1a
2026-01-04T14:45:57.069771Z
false
eugenp/tutorials
https://github.com/eugenp/tutorials/blob/4463e58ffb73fe599bac2479abd84598c6e70a1a/jhipster-modules/jhipster-uaa/uaa/src/main/java/com/baeldung/jhipster/uaa/config/DatabaseConfiguration.java
jhipster-modules/jhipster-uaa/uaa/src/main/java/com/baeldung/jhipster/uaa/config/DatabaseConfiguration.java
package com.baeldung.jhipster.uaa.config; import io.github.jhipster.config.JHipsterConstants; import io.github.jhipster.config.h2.H2ConfigurationHelper; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import org.springframework.context.annotation.Bean; import org.springframework.context.annotation.Configuration; import org.springframework.context.annotation.Profile; import org.springframework.data.jpa.repository.config.EnableJpaAuditing; import org.springframework.data.jpa.repository.config.EnableJpaRepositories; import org.springframework.transaction.annotation.EnableTransactionManagement; import java.sql.SQLException; @Configuration @EnableJpaRepositories("com.baeldung.jhipster.uaa.repository") @EnableJpaAuditing(auditorAwareRef = "springSecurityAuditorAware") @EnableTransactionManagement public class DatabaseConfiguration { private final Logger log = LoggerFactory.getLogger(DatabaseConfiguration.class); /** * Open the TCP port for the H2 database, so it is available remotely. * * @return the H2 database TCP server * @throws SQLException if the server failed to start */ @Bean(initMethod = "start", destroyMethod = "stop") @Profile(JHipsterConstants.SPRING_PROFILE_DEVELOPMENT) public Object h2TCPServer() throws SQLException { log.debug("Starting H2 database"); return H2ConfigurationHelper.createServer(); } }
java
MIT
4463e58ffb73fe599bac2479abd84598c6e70a1a
2026-01-04T14:45:57.069771Z
false
eugenp/tutorials
https://github.com/eugenp/tutorials/blob/4463e58ffb73fe599bac2479abd84598c6e70a1a/jhipster-modules/jhipster-uaa/uaa/src/main/java/com/baeldung/jhipster/uaa/config/UaaProperties.java
jhipster-modules/jhipster-uaa/uaa/src/main/java/com/baeldung/jhipster/uaa/config/UaaProperties.java
package com.baeldung.jhipster.uaa.config; import org.springframework.boot.context.properties.ConfigurationProperties; import org.springframework.stereotype.Component; /** * Properties for UAA-based OAuth2 security. */ @Component @ConfigurationProperties(prefix = "uaa", ignoreUnknownFields = false) public class UaaProperties { private KeyStore keyStore = new KeyStore(); public KeyStore getKeyStore() { return keyStore; } private WebClientConfiguration webClientConfiguration = new WebClientConfiguration(); public WebClientConfiguration getWebClientConfiguration() { return webClientConfiguration; } /** * Keystore configuration for signing and verifying JWT tokens. */ public static class KeyStore { //name of the keystore in the classpath private String name = "config/tls/keystore.p12"; //password used to access the key private String password = "password"; //name of the alias to fetch private String alias = "selfsigned"; public String getName() { return name; } public void setName(String name) { this.name = name; } public String getPassword() { return password; } public void setPassword(String password) { this.password = password; } public String getAlias() { return alias; } public void setAlias(String alias) { this.alias = alias; } } public static class WebClientConfiguration { //validity of the short-lived access token in secs (min: 60), don't make it too long private int accessTokenValidityInSeconds = 5 * 60; //validity of the refresh token in secs (defines the duration of "remember me") private int refreshTokenValidityInSecondsForRememberMe = 7 * 24 * 60 * 60; private String clientId = "web_app"; private String secret = "changeit"; public int getAccessTokenValidityInSeconds() { return accessTokenValidityInSeconds; } public void setAccessTokenValidityInSeconds(int accessTokenValidityInSeconds) { this.accessTokenValidityInSeconds = accessTokenValidityInSeconds; } public int getRefreshTokenValidityInSecondsForRememberMe() { return refreshTokenValidityInSecondsForRememberMe; } public void setRefreshTokenValidityInSecondsForRememberMe(int refreshTokenValidityInSecondsForRememberMe) { this.refreshTokenValidityInSecondsForRememberMe = refreshTokenValidityInSecondsForRememberMe; } public String getClientId() { return clientId; } public void setClientId(String clientId) { this.clientId = clientId; } public String getSecret() { return secret; } public void setSecret(String secret) { this.secret = secret; } } }
java
MIT
4463e58ffb73fe599bac2479abd84598c6e70a1a
2026-01-04T14:45:57.069771Z
false
eugenp/tutorials
https://github.com/eugenp/tutorials/blob/4463e58ffb73fe599bac2479abd84598c6e70a1a/jhipster-modules/jhipster-uaa/uaa/src/main/java/com/baeldung/jhipster/uaa/config/CacheConfiguration.java
jhipster-modules/jhipster-uaa/uaa/src/main/java/com/baeldung/jhipster/uaa/config/CacheConfiguration.java
package com.baeldung.jhipster.uaa.config; import io.github.jhipster.config.JHipsterConstants; import io.github.jhipster.config.JHipsterProperties; import com.hazelcast.config.*; import com.hazelcast.core.HazelcastInstance; import com.hazelcast.core.Hazelcast; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.boot.autoconfigure.web.ServerProperties; import org.springframework.cache.CacheManager; import org.springframework.cache.annotation.EnableCaching; import org.springframework.cloud.client.ServiceInstance; import org.springframework.cloud.client.discovery.DiscoveryClient; import org.springframework.cloud.client.serviceregistry.Registration; import org.springframework.context.annotation.*; import org.springframework.core.env.Environment; import javax.annotation.PreDestroy; @Configuration @EnableCaching public class CacheConfiguration { private final Logger log = LoggerFactory.getLogger(CacheConfiguration.class); private final Environment env; private final ServerProperties serverProperties; private final DiscoveryClient discoveryClient; private Registration registration; public CacheConfiguration(Environment env, ServerProperties serverProperties, DiscoveryClient discoveryClient) { this.env = env; this.serverProperties = serverProperties; this.discoveryClient = discoveryClient; } @Autowired(required = false) public void setRegistration(Registration registration) { this.registration = registration; } @PreDestroy public void destroy() { log.info("Closing Cache Manager"); Hazelcast.shutdownAll(); } @Bean public CacheManager cacheManager(HazelcastInstance hazelcastInstance) { log.debug("Starting HazelcastCacheManager"); CacheManager cacheManager = new com.hazelcast.spring.cache.HazelcastCacheManager(hazelcastInstance); return cacheManager; } @Bean public HazelcastInstance hazelcastInstance(JHipsterProperties jHipsterProperties) { log.debug("Configuring Hazelcast"); HazelcastInstance hazelCastInstance = Hazelcast.getHazelcastInstanceByName("uaa"); if (hazelCastInstance != null) { log.debug("Hazelcast already initialized"); return hazelCastInstance; } Config config = new Config(); config.setInstanceName("uaa"); config.getNetworkConfig().getJoin().getMulticastConfig().setEnabled(false); if (this.registration == null) { log.warn("No discovery service is set up, Hazelcast cannot create a cluster."); } else { // The serviceId is by default the application's name, // see the "spring.application.name" standard Spring property String serviceId = registration.getServiceId(); log.debug("Configuring Hazelcast clustering for instanceId: {}", serviceId); // In development, everything goes through 127.0.0.1, with a different port if (env.acceptsProfiles(JHipsterConstants.SPRING_PROFILE_DEVELOPMENT)) { log.debug("Application is running with the \"dev\" profile, Hazelcast " + "cluster will only work with localhost instances"); System.setProperty("hazelcast.local.localAddress", "127.0.0.1"); config.getNetworkConfig().setPort(serverProperties.getPort() + 5701); config.getNetworkConfig().getJoin().getTcpIpConfig().setEnabled(true); for (ServiceInstance instance : discoveryClient.getInstances(serviceId)) { String clusterMember = "127.0.0.1:" + (instance.getPort() + 5701); log.debug("Adding Hazelcast (dev) cluster member " + clusterMember); config.getNetworkConfig().getJoin().getTcpIpConfig().addMember(clusterMember); } } else { // Production configuration, one host per instance all using port 5701 config.getNetworkConfig().setPort(5701); config.getNetworkConfig().getJoin().getTcpIpConfig().setEnabled(true); for (ServiceInstance instance : discoveryClient.getInstances(serviceId)) { String clusterMember = instance.getHost() + ":5701"; log.debug("Adding Hazelcast (prod) cluster member " + clusterMember); config.getNetworkConfig().getJoin().getTcpIpConfig().addMember(clusterMember); } } } config.getMapConfigs().put("default", initializeDefaultMapConfig(jHipsterProperties)); // Full reference is available at: http://docs.hazelcast.org/docs/management-center/3.9/manual/html/Deploying_and_Starting.html config.setManagementCenterConfig(initializeDefaultManagementCenterConfig(jHipsterProperties)); config.getMapConfigs().put("com.baeldung.jhipster.uaa.domain.*", initializeDomainMapConfig(jHipsterProperties)); return Hazelcast.newHazelcastInstance(config); } private ManagementCenterConfig initializeDefaultManagementCenterConfig(JHipsterProperties jHipsterProperties) { ManagementCenterConfig managementCenterConfig = new ManagementCenterConfig(); managementCenterConfig.setEnabled(jHipsterProperties.getCache().getHazelcast().getManagementCenter().isEnabled()); managementCenterConfig.setUrl(jHipsterProperties.getCache().getHazelcast().getManagementCenter().getUrl()); managementCenterConfig.setUpdateInterval(jHipsterProperties.getCache().getHazelcast().getManagementCenter().getUpdateInterval()); return managementCenterConfig; } private MapConfig initializeDefaultMapConfig(JHipsterProperties jHipsterProperties) { MapConfig mapConfig = new MapConfig(); /* Number of backups. If 1 is set as the backup-count for example, then all entries of the map will be copied to another JVM for fail-safety. Valid numbers are 0 (no backup), 1, 2, 3. */ mapConfig.setBackupCount(jHipsterProperties.getCache().getHazelcast().getBackupCount()); /* Valid values are: NONE (no eviction), LRU (Least Recently Used), LFU (Least Frequently Used). NONE is the default. */ mapConfig.setEvictionPolicy(EvictionPolicy.LRU); /* Maximum size of the map. When max size is reached, map is evicted based on the policy defined. Any integer between 0 and Integer.MAX_VALUE. 0 means Integer.MAX_VALUE. Default is 0. */ mapConfig.setMaxSizeConfig(new MaxSizeConfig(0, MaxSizeConfig.MaxSizePolicy.USED_HEAP_SIZE)); return mapConfig; } private MapConfig initializeDomainMapConfig(JHipsterProperties jHipsterProperties) { MapConfig mapConfig = new MapConfig(); mapConfig.setTimeToLiveSeconds(jHipsterProperties.getCache().getHazelcast().getTimeToLiveSeconds()); return mapConfig; } }
java
MIT
4463e58ffb73fe599bac2479abd84598c6e70a1a
2026-01-04T14:45:57.069771Z
false
eugenp/tutorials
https://github.com/eugenp/tutorials/blob/4463e58ffb73fe599bac2479abd84598c6e70a1a/jhipster-modules/jhipster-uaa/uaa/src/main/java/com/baeldung/jhipster/uaa/config/UaaConfiguration.java
jhipster-modules/jhipster-uaa/uaa/src/main/java/com/baeldung/jhipster/uaa/config/UaaConfiguration.java
package com.baeldung.jhipster.uaa.config; import com.baeldung.jhipster.uaa.security.AuthoritiesConstants; import io.github.jhipster.config.JHipsterProperties; import org.springframework.beans.BeansException; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.beans.factory.annotation.Qualifier; import org.springframework.context.ApplicationContext; import org.springframework.context.ApplicationContextAware; import org.springframework.context.annotation.Bean; import org.springframework.context.annotation.Configuration; import org.springframework.core.io.ClassPathResource; import org.springframework.security.authentication.AuthenticationManager; import org.springframework.security.config.annotation.web.builders.HttpSecurity; import org.springframework.security.config.http.SessionCreationPolicy; import org.springframework.security.crypto.password.PasswordEncoder; import org.springframework.security.oauth2.config.annotation.configurers.ClientDetailsServiceConfigurer; import org.springframework.security.oauth2.config.annotation.web.configuration.AuthorizationServerConfigurerAdapter; import org.springframework.security.oauth2.config.annotation.web.configuration.EnableAuthorizationServer; import org.springframework.security.oauth2.config.annotation.web.configuration.EnableResourceServer; import org.springframework.security.oauth2.config.annotation.web.configuration.ResourceServerConfigurerAdapter; import org.springframework.security.oauth2.config.annotation.web.configurers.AuthorizationServerEndpointsConfigurer; import org.springframework.security.oauth2.config.annotation.web.configurers.AuthorizationServerSecurityConfigurer; import org.springframework.security.oauth2.config.annotation.web.configurers.ResourceServerSecurityConfigurer; import org.springframework.security.oauth2.provider.token.TokenEnhancer; import org.springframework.security.oauth2.provider.token.TokenEnhancerChain; import org.springframework.security.oauth2.provider.token.TokenStore; import org.springframework.security.oauth2.provider.token.store.JwtAccessTokenConverter; import org.springframework.security.oauth2.provider.token.store.JwtTokenStore; import org.springframework.security.oauth2.provider.token.store.KeyStoreKeyFactory; import org.springframework.security.web.authentication.UsernamePasswordAuthenticationFilter; import org.springframework.web.filter.CorsFilter; import javax.servlet.http.HttpServletResponse; import java.security.KeyPair; import java.util.ArrayList; import java.util.Collection; @Configuration @EnableAuthorizationServer public class UaaConfiguration extends AuthorizationServerConfigurerAdapter implements ApplicationContextAware { /** * Access tokens will not expire any earlier than this. */ private static final int MIN_ACCESS_TOKEN_VALIDITY_SECS = 60; private ApplicationContext applicationContext; @Override public void setApplicationContext(ApplicationContext applicationContext) throws BeansException { this.applicationContext = applicationContext; } @EnableResourceServer public static class ResourceServerConfiguration extends ResourceServerConfigurerAdapter { private final TokenStore tokenStore; private final JHipsterProperties jHipsterProperties; private final CorsFilter corsFilter; public ResourceServerConfiguration(TokenStore tokenStore, JHipsterProperties jHipsterProperties, CorsFilter corsFilter) { this.tokenStore = tokenStore; this.jHipsterProperties = jHipsterProperties; this.corsFilter = corsFilter; } @Override public void configure(HttpSecurity http) throws Exception { http .exceptionHandling() .authenticationEntryPoint((request, response, authException) -> response.sendError(HttpServletResponse.SC_UNAUTHORIZED)) .and() .csrf() .disable() .addFilterBefore(corsFilter, UsernamePasswordAuthenticationFilter.class) .headers() .frameOptions() .disable() .and() .sessionManagement() .sessionCreationPolicy(SessionCreationPolicy.STATELESS) .and() .authorizeRequests() .antMatchers("/api/register").permitAll() .antMatchers("/api/activate").permitAll() .antMatchers("/api/authenticate").permitAll() .antMatchers("/api/account/reset-password/init").permitAll() .antMatchers("/api/account/reset-password/finish").permitAll() .antMatchers("/api/**").authenticated() .antMatchers("/management/health").permitAll() .antMatchers("/management/**").hasAuthority(AuthoritiesConstants.ADMIN) .antMatchers("/v2/api-docs/**").permitAll() .antMatchers("/swagger-resources/configuration/ui").permitAll() .antMatchers("/swagger-ui/index.html").hasAuthority(AuthoritiesConstants.ADMIN); } @Override public void configure(ResourceServerSecurityConfigurer resources) throws Exception { resources.resourceId("jhipster-uaa").tokenStore(tokenStore); } } private final JHipsterProperties jHipsterProperties; private final UaaProperties uaaProperties; private final PasswordEncoder passwordEncoder; public UaaConfiguration(JHipsterProperties jHipsterProperties, UaaProperties uaaProperties, PasswordEncoder passwordEncoder) { this.jHipsterProperties = jHipsterProperties; this.uaaProperties = uaaProperties; this.passwordEncoder = passwordEncoder; } @Override public void configure(ClientDetailsServiceConfigurer clients) throws Exception { int accessTokenValidity = uaaProperties.getWebClientConfiguration().getAccessTokenValidityInSeconds(); accessTokenValidity = Math.max(accessTokenValidity, MIN_ACCESS_TOKEN_VALIDITY_SECS); int refreshTokenValidity = uaaProperties.getWebClientConfiguration().getRefreshTokenValidityInSecondsForRememberMe(); refreshTokenValidity = Math.max(refreshTokenValidity, accessTokenValidity); /* For a better client design, this should be done by a ClientDetailsService (similar to UserDetailsService). */ clients.inMemory() .withClient(uaaProperties.getWebClientConfiguration().getClientId()) .secret(passwordEncoder.encode(uaaProperties.getWebClientConfiguration().getSecret())) .scopes("openid") .autoApprove(true) .authorizedGrantTypes("implicit","refresh_token", "password", "authorization_code") .accessTokenValiditySeconds(accessTokenValidity) .refreshTokenValiditySeconds(refreshTokenValidity) .and() .withClient(jHipsterProperties.getSecurity().getClientAuthorization().getClientId()) .secret(passwordEncoder.encode(jHipsterProperties.getSecurity().getClientAuthorization().getClientSecret())) .scopes("web-app") .authorities("ROLE_ADMIN") .autoApprove(true) .authorizedGrantTypes("client_credentials") .accessTokenValiditySeconds((int) jHipsterProperties.getSecurity().getAuthentication().getJwt().getTokenValidityInSeconds()) .refreshTokenValiditySeconds((int) jHipsterProperties.getSecurity().getAuthentication().getJwt().getTokenValidityInSecondsForRememberMe()); } @Override public void configure(AuthorizationServerEndpointsConfigurer endpoints) throws Exception { //pick up all TokenEnhancers incl. those defined in the application //this avoids changes to this class if an application wants to add its own to the chain Collection<TokenEnhancer> tokenEnhancers = applicationContext.getBeansOfType(TokenEnhancer.class).values(); TokenEnhancerChain tokenEnhancerChain = new TokenEnhancerChain(); tokenEnhancerChain.setTokenEnhancers(new ArrayList<>(tokenEnhancers)); endpoints .authenticationManager(authenticationManager) .tokenStore(tokenStore()) .tokenEnhancer(tokenEnhancerChain) .reuseRefreshTokens(false); //don't reuse or we will run into session inactivity timeouts } @Autowired @Qualifier("authenticationManagerBean") private AuthenticationManager authenticationManager; /** * Apply the token converter (and enhancer) for token store. * @return the JwtTokenStore managing the tokens. */ @Bean public JwtTokenStore tokenStore() { return new JwtTokenStore(jwtAccessTokenConverter()); } /** * This bean generates an token enhancer, which manages the exchange between JWT acces tokens and Authentication * in both directions. * * @return an access token converter configured with the authorization server's public/private keys */ @Bean public JwtAccessTokenConverter jwtAccessTokenConverter() { JwtAccessTokenConverter converter = new JwtAccessTokenConverter(); KeyPair keyPair = new KeyStoreKeyFactory( new ClassPathResource(uaaProperties.getKeyStore().getName()), uaaProperties.getKeyStore().getPassword().toCharArray()) .getKeyPair(uaaProperties.getKeyStore().getAlias()); converter.setKeyPair(keyPair); return converter; } @Override public void configure(AuthorizationServerSecurityConfigurer oauthServer) throws Exception { oauthServer.tokenKeyAccess("permitAll()").checkTokenAccess( "isAuthenticated()"); } }
java
MIT
4463e58ffb73fe599bac2479abd84598c6e70a1a
2026-01-04T14:45:57.069771Z
false
eugenp/tutorials
https://github.com/eugenp/tutorials/blob/4463e58ffb73fe599bac2479abd84598c6e70a1a/jhipster-modules/jhipster-uaa/uaa/src/main/java/com/baeldung/jhipster/uaa/config/package-info.java
jhipster-modules/jhipster-uaa/uaa/src/main/java/com/baeldung/jhipster/uaa/config/package-info.java
/** * Spring Framework configuration files. */ package com.baeldung.jhipster.uaa.config;
java
MIT
4463e58ffb73fe599bac2479abd84598c6e70a1a
2026-01-04T14:45:57.069771Z
false
eugenp/tutorials
https://github.com/eugenp/tutorials/blob/4463e58ffb73fe599bac2479abd84598c6e70a1a/jhipster-modules/jhipster-uaa/uaa/src/main/java/com/baeldung/jhipster/uaa/config/DateTimeFormatConfiguration.java
jhipster-modules/jhipster-uaa/uaa/src/main/java/com/baeldung/jhipster/uaa/config/DateTimeFormatConfiguration.java
package com.baeldung.jhipster.uaa.config; import org.springframework.context.annotation.Configuration; import org.springframework.format.FormatterRegistry; import org.springframework.format.datetime.standard.DateTimeFormatterRegistrar; import org.springframework.web.servlet.config.annotation.WebMvcConfigurer; /** * Configure the converters to use the ISO format for dates by default. */ @Configuration public class DateTimeFormatConfiguration implements WebMvcConfigurer { @Override public void addFormatters(FormatterRegistry registry) { DateTimeFormatterRegistrar registrar = new DateTimeFormatterRegistrar(); registrar.setUseIsoFormat(true); registrar.registerFormatters(registry); } }
java
MIT
4463e58ffb73fe599bac2479abd84598c6e70a1a
2026-01-04T14:45:57.069771Z
false
eugenp/tutorials
https://github.com/eugenp/tutorials/blob/4463e58ffb73fe599bac2479abd84598c6e70a1a/jhipster-modules/jhipster-uaa/uaa/src/main/java/com/baeldung/jhipster/uaa/config/AsyncConfiguration.java
jhipster-modules/jhipster-uaa/uaa/src/main/java/com/baeldung/jhipster/uaa/config/AsyncConfiguration.java
package com.baeldung.jhipster.uaa.config; import io.github.jhipster.async.ExceptionHandlingAsyncTaskExecutor; import io.github.jhipster.config.JHipsterProperties; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import org.springframework.aop.interceptor.AsyncUncaughtExceptionHandler; import org.springframework.aop.interceptor.SimpleAsyncUncaughtExceptionHandler; import org.springframework.context.annotation.Bean; import org.springframework.context.annotation.Configuration; import org.springframework.scheduling.annotation.*; import org.springframework.scheduling.concurrent.ThreadPoolTaskExecutor; import org.springframework.scheduling.annotation.SchedulingConfigurer; import org.springframework.scheduling.config.ScheduledTaskRegistrar; import java.util.concurrent.Executor; import java.util.concurrent.Executors; @Configuration @EnableAsync @EnableScheduling public class AsyncConfiguration implements AsyncConfigurer, SchedulingConfigurer { private final Logger log = LoggerFactory.getLogger(AsyncConfiguration.class); private final JHipsterProperties jHipsterProperties; public AsyncConfiguration(JHipsterProperties jHipsterProperties) { this.jHipsterProperties = jHipsterProperties; } @Override @Bean(name = "taskExecutor") public Executor getAsyncExecutor() { log.debug("Creating Async Task Executor"); ThreadPoolTaskExecutor executor = new ThreadPoolTaskExecutor(); executor.setCorePoolSize(jHipsterProperties.getAsync().getCorePoolSize()); executor.setMaxPoolSize(jHipsterProperties.getAsync().getMaxPoolSize()); executor.setQueueCapacity(jHipsterProperties.getAsync().getQueueCapacity()); executor.setThreadNamePrefix("uaa-Executor-"); return new ExceptionHandlingAsyncTaskExecutor(executor); } @Override public AsyncUncaughtExceptionHandler getAsyncUncaughtExceptionHandler() { return new SimpleAsyncUncaughtExceptionHandler(); } @Override public void configureTasks(ScheduledTaskRegistrar taskRegistrar) { taskRegistrar.setScheduler(scheduledTaskExecutor()); } @Bean public Executor scheduledTaskExecutor() { return Executors.newScheduledThreadPool(jHipsterProperties.getAsync().getCorePoolSize()); } }
java
MIT
4463e58ffb73fe599bac2479abd84598c6e70a1a
2026-01-04T14:45:57.069771Z
false
eugenp/tutorials
https://github.com/eugenp/tutorials/blob/4463e58ffb73fe599bac2479abd84598c6e70a1a/jhipster-modules/jhipster-uaa/uaa/src/main/java/com/baeldung/jhipster/uaa/config/WebConfigurer.java
jhipster-modules/jhipster-uaa/uaa/src/main/java/com/baeldung/jhipster/uaa/config/WebConfigurer.java
package com.baeldung.jhipster.uaa.config; import com.codahale.metrics.MetricRegistry; import com.codahale.metrics.servlet.InstrumentedFilter; import com.codahale.metrics.servlets.MetricsServlet; import io.github.jhipster.config.JHipsterConstants; import io.github.jhipster.config.JHipsterProperties; import io.github.jhipster.config.h2.H2ConfigurationHelper; import io.undertow.UndertowOptions; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.boot.web.embedded.undertow.UndertowServletWebServerFactory; import org.springframework.boot.web.server.*; import org.springframework.boot.web.servlet.ServletContextInitializer; import org.springframework.boot.web.servlet.server.ConfigurableServletWebServerFactory; import org.springframework.context.annotation.Bean; import org.springframework.context.annotation.Configuration; import org.springframework.core.env.Environment; import org.springframework.http.MediaType; import org.springframework.web.cors.CorsConfiguration; import org.springframework.web.cors.UrlBasedCorsConfigurationSource; import org.springframework.web.filter.CorsFilter; import javax.servlet.*; import java.nio.charset.StandardCharsets; import java.util.*; /** * Configuration of web application with Servlet 3.0 APIs. */ @Configuration public class WebConfigurer implements ServletContextInitializer, WebServerFactoryCustomizer<WebServerFactory> { private final Logger log = LoggerFactory.getLogger(WebConfigurer.class); private final Environment env; private final JHipsterProperties jHipsterProperties; private MetricRegistry metricRegistry; public WebConfigurer(Environment env, JHipsterProperties jHipsterProperties) { this.env = env; this.jHipsterProperties = jHipsterProperties; } @Override public void onStartup(ServletContext servletContext) throws ServletException { if (env.getActiveProfiles().length != 0) { log.info("Web application configuration, using profiles: {}", (Object[]) env.getActiveProfiles()); } EnumSet<DispatcherType> disps = EnumSet.of(DispatcherType.REQUEST, DispatcherType.FORWARD, DispatcherType.ASYNC); initMetrics(servletContext, disps); if (env.acceptsProfiles(JHipsterConstants.SPRING_PROFILE_DEVELOPMENT)) { initH2Console(servletContext); } log.info("Web application fully configured"); } /** * Customize the Servlet engine: Mime types, the document root, the cache. */ @Override public void customize(WebServerFactory server) { setMimeMappings(server); /* * Enable HTTP/2 for Undertow - https://twitter.com/ankinson/status/829256167700492288 * HTTP/2 requires HTTPS, so HTTP requests will fallback to HTTP/1.1. * See the JHipsterProperties class and your application-*.yml configuration files * for more information. */ if (jHipsterProperties.getHttp().getVersion().equals(JHipsterProperties.Http.Version.V_2_0) && server instanceof UndertowServletWebServerFactory) { ((UndertowServletWebServerFactory) server) .addBuilderCustomizers(builder -> builder.setServerOption(UndertowOptions.ENABLE_HTTP2, true)); } } private void setMimeMappings(WebServerFactory server) { if (server instanceof ConfigurableServletWebServerFactory) { MimeMappings mappings = new MimeMappings(MimeMappings.DEFAULT); // IE issue, see https://github.com/jhipster/generator-jhipster/pull/711 mappings.add("html", MediaType.TEXT_HTML_VALUE + ";charset=" + StandardCharsets.UTF_8.name().toLowerCase()); // CloudFoundry issue, see https://github.com/cloudfoundry/gorouter/issues/64 mappings.add("json", MediaType.TEXT_HTML_VALUE + ";charset=" + StandardCharsets.UTF_8.name().toLowerCase()); ConfigurableServletWebServerFactory servletWebServer = (ConfigurableServletWebServerFactory) server; servletWebServer.setMimeMappings(mappings); } } /** * Initializes Metrics. */ private void initMetrics(ServletContext servletContext, EnumSet<DispatcherType> disps) { log.debug("Initializing Metrics registries"); servletContext.setAttribute(InstrumentedFilter.REGISTRY_ATTRIBUTE, metricRegistry); servletContext.setAttribute(MetricsServlet.METRICS_REGISTRY, metricRegistry); log.debug("Registering Metrics Filter"); FilterRegistration.Dynamic metricsFilter = servletContext.addFilter("webappMetricsFilter", new InstrumentedFilter()); metricsFilter.addMappingForUrlPatterns(disps, true, "/*"); metricsFilter.setAsyncSupported(true); log.debug("Registering Metrics Servlet"); ServletRegistration.Dynamic metricsAdminServlet = servletContext.addServlet("metricsServlet", new MetricsServlet()); metricsAdminServlet.addMapping("/management/metrics/*"); metricsAdminServlet.setAsyncSupported(true); metricsAdminServlet.setLoadOnStartup(2); } @Bean public CorsFilter corsFilter() { UrlBasedCorsConfigurationSource source = new UrlBasedCorsConfigurationSource(); CorsConfiguration config = jHipsterProperties.getCors(); if (config.getAllowedOrigins() != null && !config.getAllowedOrigins().isEmpty()) { log.debug("Registering CORS filter"); source.registerCorsConfiguration("/api/**", config); source.registerCorsConfiguration("/management/**", config); source.registerCorsConfiguration("/v2/api-docs", config); } return new CorsFilter(source); } /** * Initializes H2 console. */ private void initH2Console(ServletContext servletContext) { log.debug("Initialize H2 console"); H2ConfigurationHelper.initH2Console(servletContext); } @Autowired(required = false) public void setMetricRegistry(MetricRegistry metricRegistry) { this.metricRegistry = metricRegistry; } }
java
MIT
4463e58ffb73fe599bac2479abd84598c6e70a1a
2026-01-04T14:45:57.069771Z
false
eugenp/tutorials
https://github.com/eugenp/tutorials/blob/4463e58ffb73fe599bac2479abd84598c6e70a1a/jhipster-modules/jhipster-uaa/uaa/src/main/java/com/baeldung/jhipster/uaa/config/JacksonConfiguration.java
jhipster-modules/jhipster-uaa/uaa/src/main/java/com/baeldung/jhipster/uaa/config/JacksonConfiguration.java
package com.baeldung.jhipster.uaa.config; import com.fasterxml.jackson.datatype.hibernate5.Hibernate5Module; import com.fasterxml.jackson.datatype.jdk8.Jdk8Module; import com.fasterxml.jackson.datatype.jsr310.JavaTimeModule; import com.fasterxml.jackson.module.afterburner.AfterburnerModule; import org.springframework.context.annotation.Bean; import org.springframework.context.annotation.Configuration; import org.zalando.problem.ProblemModule; import org.zalando.problem.violations.ConstraintViolationProblemModule; @Configuration public class JacksonConfiguration { /** * Support for Java date and time API. * @return the corresponding Jackson module. */ @Bean public JavaTimeModule javaTimeModule() { return new JavaTimeModule(); } @Bean public Jdk8Module jdk8TimeModule() { return new Jdk8Module(); } /* * Support for Hibernate types in Jackson. */ @Bean public Hibernate5Module hibernate5Module() { return new Hibernate5Module(); } /* * Jackson Afterburner module to speed up serialization/deserialization. */ @Bean public AfterburnerModule afterburnerModule() { return new AfterburnerModule(); } /* * Module for serialization/deserialization of RFC7807 Problem. */ @Bean ProblemModule problemModule() { return new ProblemModule(); } /* * Module for serialization/deserialization of ConstraintViolationProblem. */ @Bean ConstraintViolationProblemModule constraintViolationProblemModule() { return new ConstraintViolationProblemModule(); } }
java
MIT
4463e58ffb73fe599bac2479abd84598c6e70a1a
2026-01-04T14:45:57.069771Z
false
eugenp/tutorials
https://github.com/eugenp/tutorials/blob/4463e58ffb73fe599bac2479abd84598c6e70a1a/jhipster-modules/jhipster-uaa/uaa/src/main/java/com/baeldung/jhipster/uaa/config/LoggingConfiguration.java
jhipster-modules/jhipster-uaa/uaa/src/main/java/com/baeldung/jhipster/uaa/config/LoggingConfiguration.java
package com.baeldung.jhipster.uaa.config; import java.net.InetSocketAddress; import java.util.Iterator; import io.github.jhipster.config.JHipsterProperties; import ch.qos.logback.classic.AsyncAppender; import ch.qos.logback.classic.Level; import ch.qos.logback.classic.LoggerContext; import ch.qos.logback.classic.boolex.OnMarkerEvaluator; import ch.qos.logback.classic.spi.ILoggingEvent; import ch.qos.logback.classic.spi.LoggerContextListener; import ch.qos.logback.core.Appender; import ch.qos.logback.core.filter.EvaluatorFilter; import ch.qos.logback.core.spi.ContextAwareBase; import ch.qos.logback.core.spi.FilterReply; import net.logstash.logback.appender.LogstashTcpSocketAppender; import net.logstash.logback.encoder.LogstashEncoder; import net.logstash.logback.stacktrace.ShortenedThrowableConverter; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import org.springframework.beans.factory.annotation.Value; import org.springframework.cloud.context.config.annotation.RefreshScope; import org.springframework.context.annotation.Configuration; @Configuration @RefreshScope public class LoggingConfiguration { private static final String LOGSTASH_APPENDER_NAME = "LOGSTASH"; private static final String ASYNC_LOGSTASH_APPENDER_NAME = "ASYNC_LOGSTASH"; private final Logger log = LoggerFactory.getLogger(LoggingConfiguration.class); private LoggerContext context = (LoggerContext) LoggerFactory.getILoggerFactory(); private final String appName; private final String serverPort; private final String version; private final JHipsterProperties jHipsterProperties; public LoggingConfiguration(@Value("${spring.application.name}") String appName, @Value("${server.port}") String serverPort, @Value("${info.project.version:}") String version, JHipsterProperties jHipsterProperties) { this.appName = appName; this.serverPort = serverPort; this.version = version; this.jHipsterProperties = jHipsterProperties; if (jHipsterProperties.getLogging().getLogstash().isEnabled()) { addLogstashAppender(context); addContextListener(context); } if (jHipsterProperties.getMetrics().getLogs().isEnabled()) { setMetricsMarkerLogbackFilter(context); } } private void addContextListener(LoggerContext context) { LogbackLoggerContextListener loggerContextListener = new LogbackLoggerContextListener(); loggerContextListener.setContext(context); context.addListener(loggerContextListener); } private void addLogstashAppender(LoggerContext context) { log.info("Initializing Logstash logging"); LogstashTcpSocketAppender logstashAppender = new LogstashTcpSocketAppender(); logstashAppender.setName(LOGSTASH_APPENDER_NAME); logstashAppender.setContext(context); String optionalFields = ""; String customFields = "{\"app_name\":\"" + appName + "\",\"app_port\":\"" + serverPort + "\"," + optionalFields + "\"version\":\"" + version + "\"}"; // More documentation is available at: https://github.com/logstash/logstash-logback-encoder LogstashEncoder logstashEncoder = new LogstashEncoder(); // Set the Logstash appender config from JHipster properties logstashEncoder.setCustomFields(customFields); // Set the Logstash appender config from JHipster properties logstashAppender.addDestinations(new InetSocketAddress(jHipsterProperties.getLogging().getLogstash().getHost(), jHipsterProperties.getLogging().getLogstash().getPort())); ShortenedThrowableConverter throwableConverter = new ShortenedThrowableConverter(); throwableConverter.setRootCauseFirst(true); logstashEncoder.setThrowableConverter(throwableConverter); logstashEncoder.setCustomFields(customFields); logstashAppender.setEncoder(logstashEncoder); logstashAppender.start(); // Wrap the appender in an Async appender for performance AsyncAppender asyncLogstashAppender = new AsyncAppender(); asyncLogstashAppender.setContext(context); asyncLogstashAppender.setName(ASYNC_LOGSTASH_APPENDER_NAME); asyncLogstashAppender.setQueueSize(jHipsterProperties.getLogging().getLogstash().getQueueSize()); asyncLogstashAppender.addAppender(logstashAppender); asyncLogstashAppender.start(); context.getLogger("ROOT").addAppender(asyncLogstashAppender); } // Configure a log filter to remove "metrics" logs from all appenders except the "LOGSTASH" appender private void setMetricsMarkerLogbackFilter(LoggerContext context) { log.info("Filtering metrics logs from all appenders except the {} appender", LOGSTASH_APPENDER_NAME); OnMarkerEvaluator onMarkerMetricsEvaluator = new OnMarkerEvaluator(); onMarkerMetricsEvaluator.setContext(context); onMarkerMetricsEvaluator.addMarker("metrics"); onMarkerMetricsEvaluator.start(); EvaluatorFilter<ILoggingEvent> metricsFilter = new EvaluatorFilter<>(); metricsFilter.setContext(context); metricsFilter.setEvaluator(onMarkerMetricsEvaluator); metricsFilter.setOnMatch(FilterReply.DENY); metricsFilter.start(); for (ch.qos.logback.classic.Logger logger : context.getLoggerList()) { for (Iterator<Appender<ILoggingEvent>> it = logger.iteratorForAppenders(); it.hasNext();) { Appender<ILoggingEvent> appender = it.next(); if (!appender.getName().equals(ASYNC_LOGSTASH_APPENDER_NAME)) { log.debug("Filter metrics logs from the {} appender", appender.getName()); appender.setContext(context); appender.addFilter(metricsFilter); appender.start(); } } } } /** * Logback configuration is achieved by configuration file and API. * When configuration file change is detected, the configuration is reset. * This listener ensures that the programmatic configuration is also re-applied after reset. */ class LogbackLoggerContextListener extends ContextAwareBase implements LoggerContextListener { @Override public boolean isResetResistant() { return true; } @Override public void onStart(LoggerContext context) { addLogstashAppender(context); } @Override public void onReset(LoggerContext context) { addLogstashAppender(context); } @Override public void onStop(LoggerContext context) { // Nothing to do. } @Override public void onLevelChange(ch.qos.logback.classic.Logger logger, Level level) { // Nothing to do. } } }
java
MIT
4463e58ffb73fe599bac2479abd84598c6e70a1a
2026-01-04T14:45:57.069771Z
false
eugenp/tutorials
https://github.com/eugenp/tutorials/blob/4463e58ffb73fe599bac2479abd84598c6e70a1a/jhipster-modules/jhipster-uaa/uaa/src/main/java/com/baeldung/jhipster/uaa/config/MetricsConfiguration.java
jhipster-modules/jhipster-uaa/uaa/src/main/java/com/baeldung/jhipster/uaa/config/MetricsConfiguration.java
package com.baeldung.jhipster.uaa.config; import io.github.jhipster.config.JHipsterProperties; import com.codahale.metrics.JmxReporter; import com.codahale.metrics.JvmAttributeGaugeSet; import com.codahale.metrics.MetricRegistry; import com.codahale.metrics.Slf4jReporter; import com.codahale.metrics.health.HealthCheckRegistry; import com.codahale.metrics.jvm.*; import com.ryantenney.metrics.spring.config.annotation.EnableMetrics; import com.ryantenney.metrics.spring.config.annotation.MetricsConfigurerAdapter; import com.zaxxer.hikari.HikariDataSource; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import org.slf4j.Marker; import org.slf4j.MarkerFactory; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.context.annotation.*; import javax.annotation.PostConstruct; import java.lang.management.ManagementFactory; import java.util.concurrent.TimeUnit; @Configuration @EnableMetrics(proxyTargetClass = true) public class MetricsConfiguration extends MetricsConfigurerAdapter { private static final String PROP_METRIC_REG_JVM_MEMORY = "jvm.memory"; private static final String PROP_METRIC_REG_JVM_GARBAGE = "jvm.garbage"; private static final String PROP_METRIC_REG_JVM_THREADS = "jvm.threads"; private static final String PROP_METRIC_REG_JVM_FILES = "jvm.files"; private static final String PROP_METRIC_REG_JVM_BUFFERS = "jvm.buffers"; private static final String PROP_METRIC_REG_JVM_ATTRIBUTE_SET = "jvm.attributes"; private final Logger log = LoggerFactory.getLogger(MetricsConfiguration.class); private MetricRegistry metricRegistry = new MetricRegistry(); private HealthCheckRegistry healthCheckRegistry = new HealthCheckRegistry(); private final JHipsterProperties jHipsterProperties; private HikariDataSource hikariDataSource; public MetricsConfiguration(JHipsterProperties jHipsterProperties) { this.jHipsterProperties = jHipsterProperties; } @Autowired(required = false) public void setHikariDataSource(HikariDataSource hikariDataSource) { this.hikariDataSource = hikariDataSource; } @Override @Bean public MetricRegistry getMetricRegistry() { return metricRegistry; } @Override @Bean public HealthCheckRegistry getHealthCheckRegistry() { return healthCheckRegistry; } @PostConstruct public void init() { log.debug("Registering JVM gauges"); metricRegistry.register(PROP_METRIC_REG_JVM_MEMORY, new MemoryUsageGaugeSet()); metricRegistry.register(PROP_METRIC_REG_JVM_GARBAGE, new GarbageCollectorMetricSet()); metricRegistry.register(PROP_METRIC_REG_JVM_THREADS, new ThreadStatesGaugeSet()); metricRegistry.register(PROP_METRIC_REG_JVM_FILES, new FileDescriptorRatioGauge()); metricRegistry.register(PROP_METRIC_REG_JVM_BUFFERS, new BufferPoolMetricSet(ManagementFactory.getPlatformMBeanServer())); metricRegistry.register(PROP_METRIC_REG_JVM_ATTRIBUTE_SET, new JvmAttributeGaugeSet()); if (hikariDataSource != null) { log.debug("Monitoring the datasource"); // remove the factory created by HikariDataSourceMetricsPostProcessor until JHipster migrate to Micrometer hikariDataSource.setMetricsTrackerFactory(null); hikariDataSource.setMetricRegistry(metricRegistry); } if (jHipsterProperties.getMetrics().getJmx().isEnabled()) { log.debug("Initializing Metrics JMX reporting"); JmxReporter jmxReporter = JmxReporter.forRegistry(metricRegistry).build(); jmxReporter.start(); } if (jHipsterProperties.getMetrics().getLogs().isEnabled()) { log.info("Initializing Metrics Log reporting"); Marker metricsMarker = MarkerFactory.getMarker("metrics"); final Slf4jReporter reporter = Slf4jReporter.forRegistry(metricRegistry) .outputTo(LoggerFactory.getLogger("metrics")) .markWith(metricsMarker) .convertRatesTo(TimeUnit.SECONDS) .convertDurationsTo(TimeUnit.MILLISECONDS) .build(); reporter.start(jHipsterProperties.getMetrics().getLogs().getReportFrequency(), TimeUnit.SECONDS); } } }
java
MIT
4463e58ffb73fe599bac2479abd84598c6e70a1a
2026-01-04T14:45:57.069771Z
false
eugenp/tutorials
https://github.com/eugenp/tutorials/blob/4463e58ffb73fe599bac2479abd84598c6e70a1a/jhipster-modules/jhipster-uaa/uaa/src/main/java/com/baeldung/jhipster/uaa/config/LiquibaseConfiguration.java
jhipster-modules/jhipster-uaa/uaa/src/main/java/com/baeldung/jhipster/uaa/config/LiquibaseConfiguration.java
package com.baeldung.jhipster.uaa.config; import javax.sql.DataSource; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import org.springframework.beans.factory.annotation.Qualifier; import org.springframework.boot.autoconfigure.liquibase.LiquibaseProperties; import org.springframework.cache.CacheManager; import org.springframework.context.annotation.Bean; import org.springframework.context.annotation.Configuration; import org.springframework.core.env.Environment; import org.springframework.core.task.TaskExecutor; import io.github.jhipster.config.JHipsterConstants; import io.github.jhipster.config.liquibase.AsyncSpringLiquibase; import liquibase.integration.spring.SpringLiquibase; @Configuration public class LiquibaseConfiguration { private final Logger log = LoggerFactory.getLogger(LiquibaseConfiguration.class); private final Environment env; private final CacheManager cacheManager; public LiquibaseConfiguration(Environment env, CacheManager cacheManager) { this.env = env; this.cacheManager = cacheManager; } @Bean public SpringLiquibase liquibase(@Qualifier("taskExecutor") TaskExecutor taskExecutor, DataSource dataSource, LiquibaseProperties liquibaseProperties) { // Use liquibase.integration.spring.SpringLiquibase if you don't want Liquibase to start asynchronously SpringLiquibase liquibase = new AsyncSpringLiquibase(taskExecutor, env); liquibase.setDataSource(dataSource); liquibase.setChangeLog("classpath:config/liquibase/master.xml"); liquibase.setContexts(liquibaseProperties.getContexts()); liquibase.setDefaultSchema(liquibaseProperties.getDefaultSchema()); liquibase.setDropFirst(liquibaseProperties.isDropFirst()); liquibase.setChangeLogParameters(liquibaseProperties.getParameters()); if (env.acceptsProfiles(JHipsterConstants.SPRING_PROFILE_NO_LIQUIBASE)) { liquibase.setShouldRun(false); } else { liquibase.setShouldRun(liquibaseProperties.isEnabled()); log.debug("Configuring Liquibase"); } return liquibase; } }
java
MIT
4463e58ffb73fe599bac2479abd84598c6e70a1a
2026-01-04T14:45:57.069771Z
false
eugenp/tutorials
https://github.com/eugenp/tutorials/blob/4463e58ffb73fe599bac2479abd84598c6e70a1a/jhipster-modules/jhipster-uaa/uaa/src/main/java/com/baeldung/jhipster/uaa/config/UaaWebSecurityConfiguration.java
jhipster-modules/jhipster-uaa/uaa/src/main/java/com/baeldung/jhipster/uaa/config/UaaWebSecurityConfiguration.java
package com.baeldung.jhipster.uaa.config; import org.springframework.beans.factory.BeanInitializationException; import org.springframework.context.annotation.Bean; import org.springframework.context.annotation.Configuration; import org.springframework.http.HttpMethod; import org.springframework.security.authentication.AuthenticationManager; import org.springframework.security.config.annotation.authentication.builders.AuthenticationManagerBuilder; import org.springframework.security.config.annotation.method.configuration.EnableGlobalMethodSecurity; import org.springframework.security.config.annotation.web.builders.WebSecurity; import org.springframework.security.config.annotation.web.configuration.WebSecurityConfigurerAdapter; import org.springframework.security.core.userdetails.UserDetailsService; import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder; import org.springframework.security.crypto.password.PasswordEncoder; import org.springframework.security.data.repository.query.SecurityEvaluationContextExtension; import javax.annotation.PostConstruct; @Configuration @EnableGlobalMethodSecurity(prePostEnabled = true, securedEnabled = true) public class UaaWebSecurityConfiguration extends WebSecurityConfigurerAdapter { private final UserDetailsService userDetailsService; private final AuthenticationManagerBuilder authenticationManagerBuilder; public UaaWebSecurityConfiguration(UserDetailsService userDetailsService, AuthenticationManagerBuilder authenticationManagerBuilder) { this.userDetailsService = userDetailsService; this.authenticationManagerBuilder = authenticationManagerBuilder; } @PostConstruct public void init() throws Exception { try { authenticationManagerBuilder .userDetailsService(userDetailsService) .passwordEncoder(passwordEncoder()); } catch (Exception e) { throw new BeanInitializationException("Security configuration failed", e); } } @Bean public PasswordEncoder passwordEncoder() { return new BCryptPasswordEncoder(); } @Override @Bean public AuthenticationManager authenticationManagerBean() throws Exception { return super.authenticationManagerBean(); } @Override public void configure(WebSecurity web) throws Exception { web.ignoring() .antMatchers(HttpMethod.OPTIONS, "/**") .antMatchers("/app/**/*.{js,html}") .antMatchers("/bower_components/**") .antMatchers("/i18n/**") .antMatchers("/content/**") .antMatchers("/swagger-ui/index.html") .antMatchers("/test/**") .antMatchers("/h2-console/**"); } @Bean public SecurityEvaluationContextExtension securityEvaluationContextExtension() { return new SecurityEvaluationContextExtension(); } }
java
MIT
4463e58ffb73fe599bac2479abd84598c6e70a1a
2026-01-04T14:45:57.069771Z
false
eugenp/tutorials
https://github.com/eugenp/tutorials/blob/4463e58ffb73fe599bac2479abd84598c6e70a1a/jhipster-modules/jhipster-uaa/uaa/src/main/java/com/baeldung/jhipster/uaa/config/Constants.java
jhipster-modules/jhipster-uaa/uaa/src/main/java/com/baeldung/jhipster/uaa/config/Constants.java
package com.baeldung.jhipster.uaa.config; /** * Application constants. */ public final class Constants { // Regex for acceptable logins public static final String LOGIN_REGEX = "^[_.@A-Za-z0-9-]*$"; public static final String SYSTEM_ACCOUNT = "system"; public static final String ANONYMOUS_USER = "anonymoususer"; public static final String DEFAULT_LANGUAGE = "en"; private Constants() { } }
java
MIT
4463e58ffb73fe599bac2479abd84598c6e70a1a
2026-01-04T14:45:57.069771Z
false
eugenp/tutorials
https://github.com/eugenp/tutorials/blob/4463e58ffb73fe599bac2479abd84598c6e70a1a/jhipster-modules/jhipster-uaa/uaa/src/main/java/com/baeldung/jhipster/uaa/config/LoggingAspectConfiguration.java
jhipster-modules/jhipster-uaa/uaa/src/main/java/com/baeldung/jhipster/uaa/config/LoggingAspectConfiguration.java
package com.baeldung.jhipster.uaa.config; import com.baeldung.jhipster.uaa.aop.logging.LoggingAspect; import io.github.jhipster.config.JHipsterConstants; import org.springframework.context.annotation.*; import org.springframework.core.env.Environment; @Configuration @EnableAspectJAutoProxy public class LoggingAspectConfiguration { @Bean @Profile(JHipsterConstants.SPRING_PROFILE_DEVELOPMENT) public LoggingAspect loggingAspect(Environment env) { return new LoggingAspect(env); } }
java
MIT
4463e58ffb73fe599bac2479abd84598c6e70a1a
2026-01-04T14:45:57.069771Z
false
eugenp/tutorials
https://github.com/eugenp/tutorials/blob/4463e58ffb73fe599bac2479abd84598c6e70a1a/jhipster-modules/jhipster-uaa/uaa/src/main/java/com/baeldung/jhipster/uaa/config/LocaleConfiguration.java
jhipster-modules/jhipster-uaa/uaa/src/main/java/com/baeldung/jhipster/uaa/config/LocaleConfiguration.java
package com.baeldung.jhipster.uaa.config; import io.github.jhipster.config.locale.AngularCookieLocaleResolver; import org.springframework.context.annotation.Bean; import org.springframework.context.annotation.Configuration; import org.springframework.web.servlet.LocaleResolver; import org.springframework.web.servlet.config.annotation.*; import org.springframework.web.servlet.i18n.LocaleChangeInterceptor; @Configuration public class LocaleConfiguration implements WebMvcConfigurer { @Bean(name = "localeResolver") public LocaleResolver localeResolver() { AngularCookieLocaleResolver cookieLocaleResolver = new AngularCookieLocaleResolver(); cookieLocaleResolver.setCookieName("NG_TRANSLATE_LANG_KEY"); return cookieLocaleResolver; } @Override public void addInterceptors(InterceptorRegistry registry) { LocaleChangeInterceptor localeChangeInterceptor = new LocaleChangeInterceptor(); localeChangeInterceptor.setParamName("language"); registry.addInterceptor(localeChangeInterceptor); } }
java
MIT
4463e58ffb73fe599bac2479abd84598c6e70a1a
2026-01-04T14:45:57.069771Z
false
eugenp/tutorials
https://github.com/eugenp/tutorials/blob/4463e58ffb73fe599bac2479abd84598c6e70a1a/jhipster-modules/jhipster-uaa/uaa/src/main/java/com/baeldung/jhipster/uaa/config/audit/AuditEventConverter.java
jhipster-modules/jhipster-uaa/uaa/src/main/java/com/baeldung/jhipster/uaa/config/audit/AuditEventConverter.java
package com.baeldung.jhipster.uaa.config.audit; import com.baeldung.jhipster.uaa.domain.PersistentAuditEvent; import org.springframework.boot.actuate.audit.AuditEvent; import org.springframework.security.web.authentication.WebAuthenticationDetails; import org.springframework.stereotype.Component; import java.util.*; @Component public class AuditEventConverter { /** * Convert a list of PersistentAuditEvent to a list of AuditEvent * * @param persistentAuditEvents the list to convert * @return the converted list. */ public List<AuditEvent> convertToAuditEvent(Iterable<PersistentAuditEvent> persistentAuditEvents) { if (persistentAuditEvents == null) { return Collections.emptyList(); } List<AuditEvent> auditEvents = new ArrayList<>(); for (PersistentAuditEvent persistentAuditEvent : persistentAuditEvents) { auditEvents.add(convertToAuditEvent(persistentAuditEvent)); } return auditEvents; } /** * Convert a PersistentAuditEvent to an AuditEvent * * @param persistentAuditEvent the event to convert * @return the converted list. */ public AuditEvent convertToAuditEvent(PersistentAuditEvent persistentAuditEvent) { if (persistentAuditEvent == null) { return null; } return new AuditEvent(persistentAuditEvent.getAuditEventDate(), persistentAuditEvent.getPrincipal(), persistentAuditEvent.getAuditEventType(), convertDataToObjects(persistentAuditEvent.getData())); } /** * Internal conversion. This is needed to support the current SpringBoot actuator AuditEventRepository interface * * @param data the data to convert * @return a map of String, Object */ public Map<String, Object> convertDataToObjects(Map<String, String> data) { Map<String, Object> results = new HashMap<>(); if (data != null) { for (Map.Entry<String, String> entry : data.entrySet()) { results.put(entry.getKey(), entry.getValue()); } } return results; } /** * Internal conversion. This method will allow to save additional data. * By default, it will save the object as string * * @param data the data to convert * @return a map of String, String */ public Map<String, String> convertDataToStrings(Map<String, Object> data) { Map<String, String> results = new HashMap<>(); if (data != null) { for (Map.Entry<String, Object> entry : data.entrySet()) { // Extract the data that will be saved. if (entry.getValue() instanceof WebAuthenticationDetails) { WebAuthenticationDetails authenticationDetails = (WebAuthenticationDetails) entry.getValue(); results.put("remoteAddress", authenticationDetails.getRemoteAddress()); results.put("sessionId", authenticationDetails.getSessionId()); } else { results.put(entry.getKey(), Objects.toString(entry.getValue())); } } } return results; } }
java
MIT
4463e58ffb73fe599bac2479abd84598c6e70a1a
2026-01-04T14:45:57.069771Z
false
eugenp/tutorials
https://github.com/eugenp/tutorials/blob/4463e58ffb73fe599bac2479abd84598c6e70a1a/jhipster-modules/jhipster-uaa/uaa/src/main/java/com/baeldung/jhipster/uaa/config/audit/package-info.java
jhipster-modules/jhipster-uaa/uaa/src/main/java/com/baeldung/jhipster/uaa/config/audit/package-info.java
/** * Audit specific code. */ package com.baeldung.jhipster.uaa.config.audit;
java
MIT
4463e58ffb73fe599bac2479abd84598c6e70a1a
2026-01-04T14:45:57.069771Z
false
eugenp/tutorials
https://github.com/eugenp/tutorials/blob/4463e58ffb73fe599bac2479abd84598c6e70a1a/jhipster-modules/jhipster-uaa/uaa/src/main/java/com/baeldung/jhipster/uaa/web/rest/AccountResource.java
jhipster-modules/jhipster-uaa/uaa/src/main/java/com/baeldung/jhipster/uaa/web/rest/AccountResource.java
package com.baeldung.jhipster.uaa.web.rest; import com.codahale.metrics.annotation.Timed; import com.baeldung.jhipster.uaa.domain.User; import com.baeldung.jhipster.uaa.repository.UserRepository; import com.baeldung.jhipster.uaa.security.SecurityUtils; import com.baeldung.jhipster.uaa.service.MailService; import com.baeldung.jhipster.uaa.service.UserService; import com.baeldung.jhipster.uaa.service.dto.PasswordChangeDTO; import com.baeldung.jhipster.uaa.service.dto.UserDTO; import com.baeldung.jhipster.uaa.web.rest.errors.*; import com.baeldung.jhipster.uaa.web.rest.vm.KeyAndPasswordVM; import com.baeldung.jhipster.uaa.web.rest.vm.ManagedUserVM; import org.apache.commons.lang3.StringUtils; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import org.springframework.http.HttpStatus; import org.springframework.web.bind.annotation.*; import javax.servlet.http.HttpServletRequest; import javax.validation.Valid; import java.util.*; /** * REST controller for managing the current user's account. */ @RestController @RequestMapping("/api") public class AccountResource { private final Logger log = LoggerFactory.getLogger(AccountResource.class); private final UserRepository userRepository; private final UserService userService; private final MailService mailService; public AccountResource(UserRepository userRepository, UserService userService, MailService mailService) { this.userRepository = userRepository; this.userService = userService; this.mailService = mailService; } /** * POST /register : register the user. * * @param managedUserVM the managed user View Model * @throws InvalidPasswordException 400 (Bad Request) if the password is incorrect * @throws EmailAlreadyUsedException 400 (Bad Request) if the email is already used * @throws LoginAlreadyUsedException 400 (Bad Request) if the login is already used */ @PostMapping("/register") @Timed @ResponseStatus(HttpStatus.CREATED) public void registerAccount(@Valid @RequestBody ManagedUserVM managedUserVM) { if (!checkPasswordLength(managedUserVM.getPassword())) { throw new InvalidPasswordException(); } User user = userService.registerUser(managedUserVM, managedUserVM.getPassword()); mailService.sendActivationEmail(user); } /** * GET /activate : activate the registered user. * * @param key the activation key * @throws RuntimeException 500 (Internal Server Error) if the user couldn't be activated */ @GetMapping("/activate") @Timed public void activateAccount(@RequestParam(value = "key") String key) { Optional<User> user = userService.activateRegistration(key); if (!user.isPresent()) { throw new InternalServerErrorException("No user was found for this activation key"); } } /** * GET /authenticate : check if the user is authenticated, and return its login. * * @param request the HTTP request * @return the login if the user is authenticated */ @GetMapping("/authenticate") @Timed public String isAuthenticated(HttpServletRequest request) { log.debug("REST request to check if the current user is authenticated"); return request.getRemoteUser(); } /** * GET /account : get the current user. * * @return the current user * @throws RuntimeException 500 (Internal Server Error) if the user couldn't be returned */ @GetMapping("/account") @Timed public UserDTO getAccount() { return userService.getUserWithAuthorities() .map(UserDTO::new) .orElseThrow(() -> new InternalServerErrorException("User could not be found")); } /** * POST /account : update the current user information. * * @param userDTO the current user information * @throws EmailAlreadyUsedException 400 (Bad Request) if the email is already used * @throws RuntimeException 500 (Internal Server Error) if the user login wasn't found */ @PostMapping("/account") @Timed public void saveAccount(@Valid @RequestBody UserDTO userDTO) { final String userLogin = SecurityUtils.getCurrentUserLogin().orElseThrow(() -> new InternalServerErrorException("Current user login not found")); Optional<User> existingUser = userRepository.findOneByEmailIgnoreCase(userDTO.getEmail()); if (existingUser.isPresent() && (!existingUser.get().getLogin().equalsIgnoreCase(userLogin))) { throw new EmailAlreadyUsedException(); } Optional<User> user = userRepository.findOneByLogin(userLogin); if (!user.isPresent()) { throw new InternalServerErrorException("User could not be found"); } userService.updateUser(userDTO.getFirstName(), userDTO.getLastName(), userDTO.getEmail(), userDTO.getLangKey(), userDTO.getImageUrl()); } /** * POST /account/change-password : changes the current user's password * * @param passwordChangeDto current and new password * @throws InvalidPasswordException 400 (Bad Request) if the new password is incorrect */ @PostMapping(path = "/account/change-password") @Timed public void changePassword(@RequestBody PasswordChangeDTO passwordChangeDto) { if (!checkPasswordLength(passwordChangeDto.getNewPassword())) { throw new InvalidPasswordException(); } userService.changePassword(passwordChangeDto.getCurrentPassword(), passwordChangeDto.getNewPassword()); } /** * POST /account/reset-password/init : Send an email to reset the password of the user * * @param mail the mail of the user * @throws EmailNotFoundException 400 (Bad Request) if the email address is not registered */ @PostMapping(path = "/account/reset-password/init") @Timed public void requestPasswordReset(@RequestBody String mail) { mailService.sendPasswordResetMail( userService.requestPasswordReset(mail) .orElseThrow(EmailNotFoundException::new) ); } /** * POST /account/reset-password/finish : Finish to reset the password of the user * * @param keyAndPassword the generated key and the new password * @throws InvalidPasswordException 400 (Bad Request) if the password is incorrect * @throws RuntimeException 500 (Internal Server Error) if the password could not be reset */ @PostMapping(path = "/account/reset-password/finish") @Timed public void finishPasswordReset(@RequestBody KeyAndPasswordVM keyAndPassword) { if (!checkPasswordLength(keyAndPassword.getNewPassword())) { throw new InvalidPasswordException(); } Optional<User> user = userService.completePasswordReset(keyAndPassword.getNewPassword(), keyAndPassword.getKey()); if (!user.isPresent()) { throw new InternalServerErrorException("No user was found for this reset key"); } } private static boolean checkPasswordLength(String password) { return !StringUtils.isEmpty(password) && password.length() >= ManagedUserVM.PASSWORD_MIN_LENGTH && password.length() <= ManagedUserVM.PASSWORD_MAX_LENGTH; } }
java
MIT
4463e58ffb73fe599bac2479abd84598c6e70a1a
2026-01-04T14:45:57.069771Z
false
eugenp/tutorials
https://github.com/eugenp/tutorials/blob/4463e58ffb73fe599bac2479abd84598c6e70a1a/jhipster-modules/jhipster-uaa/uaa/src/main/java/com/baeldung/jhipster/uaa/web/rest/package-info.java
jhipster-modules/jhipster-uaa/uaa/src/main/java/com/baeldung/jhipster/uaa/web/rest/package-info.java
/** * Spring MVC REST controllers. */ package com.baeldung.jhipster.uaa.web.rest;
java
MIT
4463e58ffb73fe599bac2479abd84598c6e70a1a
2026-01-04T14:45:57.069771Z
false
eugenp/tutorials
https://github.com/eugenp/tutorials/blob/4463e58ffb73fe599bac2479abd84598c6e70a1a/jhipster-modules/jhipster-uaa/uaa/src/main/java/com/baeldung/jhipster/uaa/web/rest/LogsResource.java
jhipster-modules/jhipster-uaa/uaa/src/main/java/com/baeldung/jhipster/uaa/web/rest/LogsResource.java
package com.baeldung.jhipster.uaa.web.rest; import com.baeldung.jhipster.uaa.web.rest.vm.LoggerVM; import ch.qos.logback.classic.Level; import ch.qos.logback.classic.LoggerContext; import com.codahale.metrics.annotation.Timed; import org.slf4j.LoggerFactory; import org.springframework.http.HttpStatus; import org.springframework.web.bind.annotation.*; import java.util.List; import java.util.stream.Collectors; /** * Controller for view and managing Log Level at runtime. */ @RestController @RequestMapping("/management") public class LogsResource { @GetMapping("/logs") @Timed public List<LoggerVM> getList() { LoggerContext context = (LoggerContext) LoggerFactory.getILoggerFactory(); return context.getLoggerList() .stream() .map(LoggerVM::new) .collect(Collectors.toList()); } @PutMapping("/logs") @ResponseStatus(HttpStatus.NO_CONTENT) @Timed public void changeLevel(@RequestBody LoggerVM jsonLogger) { LoggerContext context = (LoggerContext) LoggerFactory.getILoggerFactory(); context.getLogger(jsonLogger.getName()).setLevel(Level.valueOf(jsonLogger.getLevel())); } }
java
MIT
4463e58ffb73fe599bac2479abd84598c6e70a1a
2026-01-04T14:45:57.069771Z
false
eugenp/tutorials
https://github.com/eugenp/tutorials/blob/4463e58ffb73fe599bac2479abd84598c6e70a1a/jhipster-modules/jhipster-uaa/uaa/src/main/java/com/baeldung/jhipster/uaa/web/rest/UserResource.java
jhipster-modules/jhipster-uaa/uaa/src/main/java/com/baeldung/jhipster/uaa/web/rest/UserResource.java
package com.baeldung.jhipster.uaa.web.rest; import com.baeldung.jhipster.uaa.config.Constants; import com.baeldung.jhipster.uaa.domain.User; import com.baeldung.jhipster.uaa.repository.UserRepository; import com.baeldung.jhipster.uaa.security.AuthoritiesConstants; import com.baeldung.jhipster.uaa.service.MailService; import com.baeldung.jhipster.uaa.service.UserService; import com.baeldung.jhipster.uaa.service.dto.UserDTO; import com.baeldung.jhipster.uaa.web.rest.errors.BadRequestAlertException; import com.baeldung.jhipster.uaa.web.rest.errors.EmailAlreadyUsedException; import com.baeldung.jhipster.uaa.web.rest.errors.LoginAlreadyUsedException; import com.baeldung.jhipster.uaa.web.rest.util.HeaderUtil; import com.baeldung.jhipster.uaa.web.rest.util.PaginationUtil; import com.codahale.metrics.annotation.Timed; import io.github.jhipster.web.util.ResponseUtil; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import org.springframework.data.domain.Page; import org.springframework.data.domain.Pageable; import org.springframework.http.HttpHeaders; import org.springframework.http.HttpStatus; import org.springframework.http.ResponseEntity; import org.springframework.security.access.prepost.PreAuthorize; import org.springframework.web.bind.annotation.*; import javax.validation.Valid; import java.net.URI; import java.net.URISyntaxException; import java.util.*; /** * REST controller for managing users. * <p> * This class accesses the User entity, and needs to fetch its collection of authorities. * <p> * For a normal use-case, it would be better to have an eager relationship between User and Authority, * and send everything to the client side: there would be no View Model and DTO, a lot less code, and an outer-join * which would be good for performance. * <p> * We use a View Model and a DTO for 3 reasons: * <ul> * <li>We want to keep a lazy association between the user and the authorities, because people will * quite often do relationships with the user, and we don't want them to get the authorities all * the time for nothing (for performance reasons). This is the #1 goal: we should not impact our users' * application because of this use-case.</li> * <li> Not having an outer join causes n+1 requests to the database. This is not a real issue as * we have by default a second-level cache. This means on the first HTTP call we do the n+1 requests, * but then all authorities come from the cache, so in fact it's much better than doing an outer join * (which will get lots of data from the database, for each HTTP call).</li> * <li> As this manages users, for security reasons, we'd rather have a DTO layer.</li> * </ul> * <p> * Another option would be to have a specific JPA entity graph to handle this case. */ @RestController @RequestMapping("/api") public class UserResource { private final Logger log = LoggerFactory.getLogger(UserResource.class); private final UserService userService; private final UserRepository userRepository; private final MailService mailService; public UserResource(UserService userService, UserRepository userRepository, MailService mailService) { this.userService = userService; this.userRepository = userRepository; this.mailService = mailService; } /** * POST /users : Creates a new user. * <p> * Creates a new user if the login and email are not already used, and sends an * mail with an activation link. * The user needs to be activated on creation. * * @param userDTO the user to create * @return the ResponseEntity with status 201 (Created) and with body the new user, or with status 400 (Bad Request) if the login or email is already in use * @throws URISyntaxException if the Location URI syntax is incorrect * @throws BadRequestAlertException 400 (Bad Request) if the login or email is already in use */ @PostMapping("/users") @Timed @PreAuthorize("hasRole(\"" + AuthoritiesConstants.ADMIN + "\")") public ResponseEntity<User> createUser(@Valid @RequestBody UserDTO userDTO) throws URISyntaxException { log.debug("REST request to save User : {}", userDTO); if (userDTO.getId() != null) { throw new BadRequestAlertException("A new user cannot already have an ID", "userManagement", "idexists"); // Lowercase the user login before comparing with database } else if (userRepository.findOneByLogin(userDTO.getLogin().toLowerCase()).isPresent()) { throw new LoginAlreadyUsedException(); } else if (userRepository.findOneByEmailIgnoreCase(userDTO.getEmail()).isPresent()) { throw new EmailAlreadyUsedException(); } else { User newUser = userService.createUser(userDTO); mailService.sendCreationEmail(newUser); return ResponseEntity.created(new URI("/api/users/" + newUser.getLogin())) .headers(HeaderUtil.createAlert( "userManagement.created", newUser.getLogin())) .body(newUser); } } /** * PUT /users : Updates an existing User. * * @param userDTO the user to update * @return the ResponseEntity with status 200 (OK) and with body the updated user * @throws EmailAlreadyUsedException 400 (Bad Request) if the email is already in use * @throws LoginAlreadyUsedException 400 (Bad Request) if the login is already in use */ @PutMapping("/users") @Timed @PreAuthorize("hasRole(\"" + AuthoritiesConstants.ADMIN + "\")") public ResponseEntity<UserDTO> updateUser(@Valid @RequestBody UserDTO userDTO) { log.debug("REST request to update User : {}", userDTO); Optional<User> existingUser = userRepository.findOneByEmailIgnoreCase(userDTO.getEmail()); if (existingUser.isPresent() && (!existingUser.get().getId().equals(userDTO.getId()))) { throw new EmailAlreadyUsedException(); } existingUser = userRepository.findOneByLogin(userDTO.getLogin().toLowerCase()); if (existingUser.isPresent() && (!existingUser.get().getId().equals(userDTO.getId()))) { throw new LoginAlreadyUsedException(); } Optional<UserDTO> updatedUser = userService.updateUser(userDTO); return ResponseUtil.wrapOrNotFound(updatedUser, HeaderUtil.createAlert("userManagement.updated", userDTO.getLogin())); } /** * GET /users : get all users. * * @param pageable the pagination information * @return the ResponseEntity with status 200 (OK) and with body all users */ @GetMapping("/users") @Timed public ResponseEntity<List<UserDTO>> getAllUsers(Pageable pageable) { final Page<UserDTO> page = userService.getAllManagedUsers(pageable); HttpHeaders headers = PaginationUtil.generatePaginationHttpHeaders(page, "/api/users"); return new ResponseEntity<>(page.getContent(), headers, HttpStatus.OK); } /** * @return a string list of the all of the roles */ @GetMapping("/users/authorities") @Timed @PreAuthorize("hasRole(\"" + AuthoritiesConstants.ADMIN + "\")") public List<String> getAuthorities() { return userService.getAuthorities(); } /** * GET /users/:login : get the "login" user. * * @param login the login of the user to find * @return the ResponseEntity with status 200 (OK) and with body the "login" user, or with status 404 (Not Found) */ @GetMapping("/users/{login:" + Constants.LOGIN_REGEX + "}") @Timed public ResponseEntity<UserDTO> getUser(@PathVariable String login) { log.debug("REST request to get User : {}", login); return ResponseUtil.wrapOrNotFound( userService.getUserWithAuthoritiesByLogin(login) .map(UserDTO::new)); } /** * DELETE /users/:login : delete the "login" User. * * @param login the login of the user to delete * @return the ResponseEntity with status 200 (OK) */ @DeleteMapping("/users/{login:" + Constants.LOGIN_REGEX + "}") @Timed @PreAuthorize("hasRole(\"" + AuthoritiesConstants.ADMIN + "\")") public ResponseEntity<Void> deleteUser(@PathVariable String login) { log.debug("REST request to delete User: {}", login); userService.deleteUser(login); return ResponseEntity.ok().headers(HeaderUtil.createAlert( "userManagement.deleted", login)).build(); } }
java
MIT
4463e58ffb73fe599bac2479abd84598c6e70a1a
2026-01-04T14:45:57.069771Z
false
eugenp/tutorials
https://github.com/eugenp/tutorials/blob/4463e58ffb73fe599bac2479abd84598c6e70a1a/jhipster-modules/jhipster-uaa/uaa/src/main/java/com/baeldung/jhipster/uaa/web/rest/AuditResource.java
jhipster-modules/jhipster-uaa/uaa/src/main/java/com/baeldung/jhipster/uaa/web/rest/AuditResource.java
package com.baeldung.jhipster.uaa.web.rest; import com.baeldung.jhipster.uaa.service.AuditEventService; import com.baeldung.jhipster.uaa.web.rest.util.PaginationUtil; import io.github.jhipster.web.util.ResponseUtil; import org.springframework.boot.actuate.audit.AuditEvent; import org.springframework.data.domain.Page; import org.springframework.data.domain.Pageable; import org.springframework.http.HttpHeaders; import org.springframework.http.HttpStatus; import org.springframework.http.ResponseEntity; import org.springframework.web.bind.annotation.*; import java.time.LocalDate; import java.time.ZoneId; import java.util.List; /** * REST controller for getting the audit events. */ @RestController @RequestMapping("/management/audits") public class AuditResource { private final AuditEventService auditEventService; public AuditResource(AuditEventService auditEventService) { this.auditEventService = auditEventService; } /** * GET /audits : get a page of AuditEvents. * * @param pageable the pagination information * @return the ResponseEntity with status 200 (OK) and the list of AuditEvents in body */ @GetMapping public ResponseEntity<List<AuditEvent>> getAll(Pageable pageable) { Page<AuditEvent> page = auditEventService.findAll(pageable); HttpHeaders headers = PaginationUtil.generatePaginationHttpHeaders(page, "/management/audits"); return new ResponseEntity<>(page.getContent(), headers, HttpStatus.OK); } /** * GET /audits : get a page of AuditEvents between the fromDate and toDate. * * @param fromDate the start of the time period of AuditEvents to get * @param toDate the end of the time period of AuditEvents to get * @param pageable the pagination information * @return the ResponseEntity with status 200 (OK) and the list of AuditEvents in body */ @GetMapping(params = {"fromDate", "toDate"}) public ResponseEntity<List<AuditEvent>> getByDates( @RequestParam(value = "fromDate") LocalDate fromDate, @RequestParam(value = "toDate") LocalDate toDate, Pageable pageable) { Page<AuditEvent> page = auditEventService.findByDates( fromDate.atStartOfDay(ZoneId.systemDefault()).toInstant(), toDate.atStartOfDay(ZoneId.systemDefault()).plusDays(1).toInstant(), pageable); HttpHeaders headers = PaginationUtil.generatePaginationHttpHeaders(page, "/management/audits"); return new ResponseEntity<>(page.getContent(), headers, HttpStatus.OK); } /** * GET /audits/:id : get an AuditEvent by id. * * @param id the id of the entity to get * @return the ResponseEntity with status 200 (OK) and the AuditEvent in body, or status 404 (Not Found) */ @GetMapping("/{id:.+}") public ResponseEntity<AuditEvent> get(@PathVariable Long id) { return ResponseUtil.wrapOrNotFound(auditEventService.find(id)); } }
java
MIT
4463e58ffb73fe599bac2479abd84598c6e70a1a
2026-01-04T14:45:57.069771Z
false
eugenp/tutorials
https://github.com/eugenp/tutorials/blob/4463e58ffb73fe599bac2479abd84598c6e70a1a/jhipster-modules/jhipster-uaa/uaa/src/main/java/com/baeldung/jhipster/uaa/web/rest/util/HeaderUtil.java
jhipster-modules/jhipster-uaa/uaa/src/main/java/com/baeldung/jhipster/uaa/web/rest/util/HeaderUtil.java
package com.baeldung.jhipster.uaa.web.rest.util; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import org.springframework.http.HttpHeaders; /** * Utility class for HTTP headers creation. */ public final class HeaderUtil { private static final Logger log = LoggerFactory.getLogger(HeaderUtil.class); private static final String APPLICATION_NAME = "uaaApp"; private HeaderUtil() { } public static HttpHeaders createAlert(String message, String param) { HttpHeaders headers = new HttpHeaders(); headers.add("X-" + APPLICATION_NAME + "-alert", message); headers.add("X-" + APPLICATION_NAME + "-params", param); return headers; } public static HttpHeaders createEntityCreationAlert(String entityName, String param) { return createAlert(APPLICATION_NAME + "." + entityName + ".created", param); } public static HttpHeaders createEntityUpdateAlert(String entityName, String param) { return createAlert(APPLICATION_NAME + "." + entityName + ".updated", param); } public static HttpHeaders createEntityDeletionAlert(String entityName, String param) { return createAlert(APPLICATION_NAME + "." + entityName + ".deleted", param); } public static HttpHeaders createFailureAlert(String entityName, String errorKey, String defaultMessage) { log.error("Entity processing failed, {}", defaultMessage); HttpHeaders headers = new HttpHeaders(); headers.add("X-" + APPLICATION_NAME + "-error", "error." + errorKey); headers.add("X-" + APPLICATION_NAME + "-params", entityName); return headers; } }
java
MIT
4463e58ffb73fe599bac2479abd84598c6e70a1a
2026-01-04T14:45:57.069771Z
false
eugenp/tutorials
https://github.com/eugenp/tutorials/blob/4463e58ffb73fe599bac2479abd84598c6e70a1a/jhipster-modules/jhipster-uaa/uaa/src/main/java/com/baeldung/jhipster/uaa/web/rest/util/PaginationUtil.java
jhipster-modules/jhipster-uaa/uaa/src/main/java/com/baeldung/jhipster/uaa/web/rest/util/PaginationUtil.java
package com.baeldung.jhipster.uaa.web.rest.util; import org.springframework.data.domain.Page; import org.springframework.http.HttpHeaders; import org.springframework.web.util.UriComponentsBuilder; /** * Utility class for handling pagination. * * <p> * Pagination uses the same principles as the <a href="https://developer.github.com/v3/#pagination">GitHub API</a>, * and follow <a href="http://tools.ietf.org/html/rfc5988">RFC 5988 (Link header)</a>. */ public final class PaginationUtil { private PaginationUtil() { } public static <T> HttpHeaders generatePaginationHttpHeaders(Page<T> page, String baseUrl) { HttpHeaders headers = new HttpHeaders(); headers.add("X-Total-Count", Long.toString(page.getTotalElements())); String link = ""; if ((page.getNumber() + 1) < page.getTotalPages()) { link = "<" + generateUri(baseUrl, page.getNumber() + 1, page.getSize()) + ">; rel=\"next\","; } // prev link if ((page.getNumber()) > 0) { link += "<" + generateUri(baseUrl, page.getNumber() - 1, page.getSize()) + ">; rel=\"prev\","; } // last and first link int lastPage = 0; if (page.getTotalPages() > 0) { lastPage = page.getTotalPages() - 1; } link += "<" + generateUri(baseUrl, lastPage, page.getSize()) + ">; rel=\"last\","; link += "<" + generateUri(baseUrl, 0, page.getSize()) + ">; rel=\"first\""; headers.add(HttpHeaders.LINK, link); return headers; } private static String generateUri(String baseUrl, int page, int size) { return UriComponentsBuilder.fromUriString(baseUrl).queryParam("page", page).queryParam("size", size).toUriString(); } }
java
MIT
4463e58ffb73fe599bac2479abd84598c6e70a1a
2026-01-04T14:45:57.069771Z
false
eugenp/tutorials
https://github.com/eugenp/tutorials/blob/4463e58ffb73fe599bac2479abd84598c6e70a1a/jhipster-modules/jhipster-uaa/uaa/src/main/java/com/baeldung/jhipster/uaa/web/rest/errors/InvalidPasswordException.java
jhipster-modules/jhipster-uaa/uaa/src/main/java/com/baeldung/jhipster/uaa/web/rest/errors/InvalidPasswordException.java
package com.baeldung.jhipster.uaa.web.rest.errors; import org.zalando.problem.AbstractThrowableProblem; import org.zalando.problem.Status; public class InvalidPasswordException extends AbstractThrowableProblem { private static final long serialVersionUID = 1L; public InvalidPasswordException() { super(ErrorConstants.INVALID_PASSWORD_TYPE, "Incorrect password", Status.BAD_REQUEST); } }
java
MIT
4463e58ffb73fe599bac2479abd84598c6e70a1a
2026-01-04T14:45:57.069771Z
false
eugenp/tutorials
https://github.com/eugenp/tutorials/blob/4463e58ffb73fe599bac2479abd84598c6e70a1a/jhipster-modules/jhipster-uaa/uaa/src/main/java/com/baeldung/jhipster/uaa/web/rest/errors/CustomParameterizedException.java
jhipster-modules/jhipster-uaa/uaa/src/main/java/com/baeldung/jhipster/uaa/web/rest/errors/CustomParameterizedException.java
package com.baeldung.jhipster.uaa.web.rest.errors; import org.zalando.problem.AbstractThrowableProblem; import java.util.HashMap; import java.util.Map; import static org.zalando.problem.Status.BAD_REQUEST; /** * Custom, parameterized exception, which can be translated on the client side. * For example: * * <pre> * throw new CustomParameterizedException(&quot;myCustomError&quot;, &quot;hello&quot;, &quot;world&quot;); * </pre> * * Can be translated with: * * <pre> * "error.myCustomError" : "The server says {{param0}} to {{param1}}" * </pre> */ public class CustomParameterizedException extends AbstractThrowableProblem { private static final long serialVersionUID = 1L; private static final String PARAM = "param"; public CustomParameterizedException(String message, String... params) { this(message, toParamMap(params)); } public CustomParameterizedException(String message, Map<String, Object> paramMap) { super(ErrorConstants.PARAMETERIZED_TYPE, "Parameterized Exception", BAD_REQUEST, null, null, null, toProblemParameters(message, paramMap)); } public static Map<String, Object> toParamMap(String... params) { Map<String, Object> paramMap = new HashMap<>(); if (params != null && params.length > 0) { for (int i = 0; i < params.length; i++) { paramMap.put(PARAM + i, params[i]); } } return paramMap; } public static Map<String, Object> toProblemParameters(String message, Map<String, Object> paramMap) { Map<String, Object> parameters = new HashMap<>(); parameters.put("message", message); parameters.put("params", paramMap); return parameters; } }
java
MIT
4463e58ffb73fe599bac2479abd84598c6e70a1a
2026-01-04T14:45:57.069771Z
false
eugenp/tutorials
https://github.com/eugenp/tutorials/blob/4463e58ffb73fe599bac2479abd84598c6e70a1a/jhipster-modules/jhipster-uaa/uaa/src/main/java/com/baeldung/jhipster/uaa/web/rest/errors/package-info.java
jhipster-modules/jhipster-uaa/uaa/src/main/java/com/baeldung/jhipster/uaa/web/rest/errors/package-info.java
/** * Specific errors used with Zalando's "problem-spring-web" library. * * More information on https://github.com/zalando/problem-spring-web */ package com.baeldung.jhipster.uaa.web.rest.errors;
java
MIT
4463e58ffb73fe599bac2479abd84598c6e70a1a
2026-01-04T14:45:57.069771Z
false
eugenp/tutorials
https://github.com/eugenp/tutorials/blob/4463e58ffb73fe599bac2479abd84598c6e70a1a/jhipster-modules/jhipster-uaa/uaa/src/main/java/com/baeldung/jhipster/uaa/web/rest/errors/LoginAlreadyUsedException.java
jhipster-modules/jhipster-uaa/uaa/src/main/java/com/baeldung/jhipster/uaa/web/rest/errors/LoginAlreadyUsedException.java
package com.baeldung.jhipster.uaa.web.rest.errors; public class LoginAlreadyUsedException extends BadRequestAlertException { private static final long serialVersionUID = 1L; public LoginAlreadyUsedException() { super(ErrorConstants.LOGIN_ALREADY_USED_TYPE, "Login name already used!", "userManagement", "userexists"); } }
java
MIT
4463e58ffb73fe599bac2479abd84598c6e70a1a
2026-01-04T14:45:57.069771Z
false
eugenp/tutorials
https://github.com/eugenp/tutorials/blob/4463e58ffb73fe599bac2479abd84598c6e70a1a/jhipster-modules/jhipster-uaa/uaa/src/main/java/com/baeldung/jhipster/uaa/web/rest/errors/EmailNotFoundException.java
jhipster-modules/jhipster-uaa/uaa/src/main/java/com/baeldung/jhipster/uaa/web/rest/errors/EmailNotFoundException.java
package com.baeldung.jhipster.uaa.web.rest.errors; import org.zalando.problem.AbstractThrowableProblem; import org.zalando.problem.Status; public class EmailNotFoundException extends AbstractThrowableProblem { private static final long serialVersionUID = 1L; public EmailNotFoundException() { super(ErrorConstants.EMAIL_NOT_FOUND_TYPE, "Email address not registered", Status.BAD_REQUEST); } }
java
MIT
4463e58ffb73fe599bac2479abd84598c6e70a1a
2026-01-04T14:45:57.069771Z
false
eugenp/tutorials
https://github.com/eugenp/tutorials/blob/4463e58ffb73fe599bac2479abd84598c6e70a1a/jhipster-modules/jhipster-uaa/uaa/src/main/java/com/baeldung/jhipster/uaa/web/rest/errors/InternalServerErrorException.java
jhipster-modules/jhipster-uaa/uaa/src/main/java/com/baeldung/jhipster/uaa/web/rest/errors/InternalServerErrorException.java
package com.baeldung.jhipster.uaa.web.rest.errors; import org.zalando.problem.AbstractThrowableProblem; import org.zalando.problem.Status; /** * Simple exception with a message, that returns an Internal Server Error code. */ public class InternalServerErrorException extends AbstractThrowableProblem { private static final long serialVersionUID = 1L; public InternalServerErrorException(String message) { super(ErrorConstants.DEFAULT_TYPE, message, Status.INTERNAL_SERVER_ERROR); } }
java
MIT
4463e58ffb73fe599bac2479abd84598c6e70a1a
2026-01-04T14:45:57.069771Z
false
eugenp/tutorials
https://github.com/eugenp/tutorials/blob/4463e58ffb73fe599bac2479abd84598c6e70a1a/jhipster-modules/jhipster-uaa/uaa/src/main/java/com/baeldung/jhipster/uaa/web/rest/errors/ErrorConstants.java
jhipster-modules/jhipster-uaa/uaa/src/main/java/com/baeldung/jhipster/uaa/web/rest/errors/ErrorConstants.java
package com.baeldung.jhipster.uaa.web.rest.errors; import java.net.URI; public final class ErrorConstants { public static final String ERR_CONCURRENCY_FAILURE = "error.concurrencyFailure"; public static final String ERR_VALIDATION = "error.validation"; public static final String PROBLEM_BASE_URL = "https://www.jhipster.tech/problem"; public static final URI DEFAULT_TYPE = URI.create(PROBLEM_BASE_URL + "/problem-with-message"); public static final URI CONSTRAINT_VIOLATION_TYPE = URI.create(PROBLEM_BASE_URL + "/constraint-violation"); public static final URI PARAMETERIZED_TYPE = URI.create(PROBLEM_BASE_URL + "/parameterized"); public static final URI ENTITY_NOT_FOUND_TYPE = URI.create(PROBLEM_BASE_URL + "/entity-not-found"); public static final URI INVALID_PASSWORD_TYPE = URI.create(PROBLEM_BASE_URL + "/invalid-password"); public static final URI EMAIL_ALREADY_USED_TYPE = URI.create(PROBLEM_BASE_URL + "/email-already-used"); public static final URI LOGIN_ALREADY_USED_TYPE = URI.create(PROBLEM_BASE_URL + "/login-already-used"); public static final URI EMAIL_NOT_FOUND_TYPE = URI.create(PROBLEM_BASE_URL + "/email-not-found"); private ErrorConstants() { } }
java
MIT
4463e58ffb73fe599bac2479abd84598c6e70a1a
2026-01-04T14:45:57.069771Z
false
eugenp/tutorials
https://github.com/eugenp/tutorials/blob/4463e58ffb73fe599bac2479abd84598c6e70a1a/jhipster-modules/jhipster-uaa/uaa/src/main/java/com/baeldung/jhipster/uaa/web/rest/errors/FieldErrorVM.java
jhipster-modules/jhipster-uaa/uaa/src/main/java/com/baeldung/jhipster/uaa/web/rest/errors/FieldErrorVM.java
package com.baeldung.jhipster.uaa.web.rest.errors; import java.io.Serializable; public class FieldErrorVM implements Serializable { private static final long serialVersionUID = 1L; private final String objectName; private final String field; private final String message; public FieldErrorVM(String dto, String field, String message) { this.objectName = dto; this.field = field; this.message = message; } public String getObjectName() { return objectName; } public String getField() { return field; } public String getMessage() { return message; } }
java
MIT
4463e58ffb73fe599bac2479abd84598c6e70a1a
2026-01-04T14:45:57.069771Z
false
eugenp/tutorials
https://github.com/eugenp/tutorials/blob/4463e58ffb73fe599bac2479abd84598c6e70a1a/jhipster-modules/jhipster-uaa/uaa/src/main/java/com/baeldung/jhipster/uaa/web/rest/errors/EmailAlreadyUsedException.java
jhipster-modules/jhipster-uaa/uaa/src/main/java/com/baeldung/jhipster/uaa/web/rest/errors/EmailAlreadyUsedException.java
package com.baeldung.jhipster.uaa.web.rest.errors; public class EmailAlreadyUsedException extends BadRequestAlertException { private static final long serialVersionUID = 1L; public EmailAlreadyUsedException() { super(ErrorConstants.EMAIL_ALREADY_USED_TYPE, "Email is already in use!", "userManagement", "emailexists"); } }
java
MIT
4463e58ffb73fe599bac2479abd84598c6e70a1a
2026-01-04T14:45:57.069771Z
false
eugenp/tutorials
https://github.com/eugenp/tutorials/blob/4463e58ffb73fe599bac2479abd84598c6e70a1a/jhipster-modules/jhipster-uaa/uaa/src/main/java/com/baeldung/jhipster/uaa/web/rest/errors/BadRequestAlertException.java
jhipster-modules/jhipster-uaa/uaa/src/main/java/com/baeldung/jhipster/uaa/web/rest/errors/BadRequestAlertException.java
package com.baeldung.jhipster.uaa.web.rest.errors; import org.zalando.problem.AbstractThrowableProblem; import org.zalando.problem.Status; import java.net.URI; import java.util.HashMap; import java.util.Map; public class BadRequestAlertException extends AbstractThrowableProblem { private static final long serialVersionUID = 1L; private final String entityName; private final String errorKey; public BadRequestAlertException(String defaultMessage, String entityName, String errorKey) { this(ErrorConstants.DEFAULT_TYPE, defaultMessage, entityName, errorKey); } public BadRequestAlertException(URI type, String defaultMessage, String entityName, String errorKey) { super(type, defaultMessage, Status.BAD_REQUEST, null, null, null, getAlertParameters(entityName, errorKey)); this.entityName = entityName; this.errorKey = errorKey; } public String getEntityName() { return entityName; } public String getErrorKey() { return errorKey; } private static Map<String, Object> getAlertParameters(String entityName, String errorKey) { Map<String, Object> parameters = new HashMap<>(); parameters.put("message", "error." + errorKey); parameters.put("params", entityName); return parameters; } }
java
MIT
4463e58ffb73fe599bac2479abd84598c6e70a1a
2026-01-04T14:45:57.069771Z
false
eugenp/tutorials
https://github.com/eugenp/tutorials/blob/4463e58ffb73fe599bac2479abd84598c6e70a1a/jhipster-modules/jhipster-uaa/uaa/src/main/java/com/baeldung/jhipster/uaa/web/rest/errors/ExceptionTranslator.java
jhipster-modules/jhipster-uaa/uaa/src/main/java/com/baeldung/jhipster/uaa/web/rest/errors/ExceptionTranslator.java
package com.baeldung.jhipster.uaa.web.rest.errors; import com.baeldung.jhipster.uaa.web.rest.util.HeaderUtil; import org.springframework.dao.ConcurrencyFailureException; import org.springframework.http.ResponseEntity; import org.springframework.validation.BindingResult; import org.springframework.web.bind.MethodArgumentNotValidException; import org.springframework.web.bind.annotation.ControllerAdvice; import org.springframework.web.bind.annotation.ExceptionHandler; import org.springframework.web.context.request.NativeWebRequest; import org.zalando.problem.DefaultProblem; import org.zalando.problem.Problem; import org.zalando.problem.ProblemBuilder; import org.zalando.problem.Status; import org.zalando.problem.spring.web.advice.ProblemHandling; import org.zalando.problem.spring.web.advice.security.SecurityAdviceTrait; import org.zalando.problem.violations.ConstraintViolationProblem; import javax.annotation.Nonnull; import javax.annotation.Nullable; import javax.servlet.http.HttpServletRequest; import java.util.List; import java.util.NoSuchElementException; import java.util.stream.Collectors; /** * Controller advice to translate the server side exceptions to client-friendly json structures. * The error response follows RFC7807 - Problem Details for HTTP APIs (https://tools.ietf.org/html/rfc7807) */ @ControllerAdvice public class ExceptionTranslator implements ProblemHandling, SecurityAdviceTrait { /** * Post-process the Problem payload to add the message key for the front-end if needed */ @Override public ResponseEntity<Problem> process(@Nullable ResponseEntity<Problem> entity, NativeWebRequest request) { if (entity == null) { return entity; } Problem problem = entity.getBody(); if (!(problem instanceof ConstraintViolationProblem || problem instanceof DefaultProblem)) { return entity; } ProblemBuilder builder = Problem.builder() .withType(Problem.DEFAULT_TYPE.equals(problem.getType()) ? ErrorConstants.DEFAULT_TYPE : problem.getType()) .withStatus(problem.getStatus()) .withTitle(problem.getTitle()) .with("path", request.getNativeRequest(HttpServletRequest.class).getRequestURI()); if (problem instanceof ConstraintViolationProblem) { builder .with("violations", ((ConstraintViolationProblem) problem).getViolations()) .with("message", ErrorConstants.ERR_VALIDATION); } else { builder .withCause(((DefaultProblem) problem).getCause()) .withDetail(problem.getDetail()) .withInstance(problem.getInstance()); problem.getParameters().forEach(builder::with); if (!problem.getParameters().containsKey("message") && problem.getStatus() != null) { builder.with("message", "error.http." + problem.getStatus().getStatusCode()); } } return new ResponseEntity<>(builder.build(), entity.getHeaders(), entity.getStatusCode()); } @Override public ResponseEntity<Problem> handleMethodArgumentNotValid(MethodArgumentNotValidException ex, @Nonnull NativeWebRequest request) { BindingResult result = ex.getBindingResult(); List<FieldErrorVM> fieldErrors = result.getFieldErrors().stream() .map(f -> new FieldErrorVM(f.getObjectName(), f.getField(), f.getCode())) .collect(Collectors.toList()); Problem problem = Problem.builder() .withType(ErrorConstants.CONSTRAINT_VIOLATION_TYPE) .withTitle("Method argument not valid") .withStatus(defaultConstraintViolationStatus()) .with("message", ErrorConstants.ERR_VALIDATION) .with("fieldErrors", fieldErrors) .build(); return create(ex, problem, request); } @ExceptionHandler public ResponseEntity<Problem> handleNoSuchElementException(NoSuchElementException ex, NativeWebRequest request) { Problem problem = Problem.builder() .withStatus(Status.NOT_FOUND) .with("message", ErrorConstants.ENTITY_NOT_FOUND_TYPE) .build(); return create(ex, problem, request); } @ExceptionHandler public ResponseEntity<Problem> handleBadRequestAlertException(BadRequestAlertException ex, NativeWebRequest request) { return create(ex, request, HeaderUtil.createFailureAlert(ex.getEntityName(), ex.getErrorKey(), ex.getMessage())); } @ExceptionHandler public ResponseEntity<Problem> handleConcurrencyFailure(ConcurrencyFailureException ex, NativeWebRequest request) { Problem problem = Problem.builder() .withStatus(Status.CONFLICT) .with("message", ErrorConstants.ERR_CONCURRENCY_FAILURE) .build(); return create(ex, problem, request); } }
java
MIT
4463e58ffb73fe599bac2479abd84598c6e70a1a
2026-01-04T14:45:57.069771Z
false
eugenp/tutorials
https://github.com/eugenp/tutorials/blob/4463e58ffb73fe599bac2479abd84598c6e70a1a/jhipster-modules/jhipster-uaa/uaa/src/main/java/com/baeldung/jhipster/uaa/web/rest/vm/package-info.java
jhipster-modules/jhipster-uaa/uaa/src/main/java/com/baeldung/jhipster/uaa/web/rest/vm/package-info.java
/** * View Models used by Spring MVC REST controllers. */ package com.baeldung.jhipster.uaa.web.rest.vm;
java
MIT
4463e58ffb73fe599bac2479abd84598c6e70a1a
2026-01-04T14:45:57.069771Z
false
eugenp/tutorials
https://github.com/eugenp/tutorials/blob/4463e58ffb73fe599bac2479abd84598c6e70a1a/jhipster-modules/jhipster-uaa/uaa/src/main/java/com/baeldung/jhipster/uaa/web/rest/vm/LoggerVM.java
jhipster-modules/jhipster-uaa/uaa/src/main/java/com/baeldung/jhipster/uaa/web/rest/vm/LoggerVM.java
package com.baeldung.jhipster.uaa.web.rest.vm; import ch.qos.logback.classic.Logger; /** * View Model object for storing a Logback logger. */ public class LoggerVM { private String name; private String level; public LoggerVM(Logger logger) { this.name = logger.getName(); this.level = logger.getEffectiveLevel().toString(); } public LoggerVM() { // Empty public constructor used by Jackson. } public String getName() { return name; } public void setName(String name) { this.name = name; } public String getLevel() { return level; } public void setLevel(String level) { this.level = level; } @Override public String toString() { return "LoggerVM{" + "name='" + name + '\'' + ", level='" + level + '\'' + '}'; } }
java
MIT
4463e58ffb73fe599bac2479abd84598c6e70a1a
2026-01-04T14:45:57.069771Z
false
eugenp/tutorials
https://github.com/eugenp/tutorials/blob/4463e58ffb73fe599bac2479abd84598c6e70a1a/jhipster-modules/jhipster-uaa/uaa/src/main/java/com/baeldung/jhipster/uaa/web/rest/vm/KeyAndPasswordVM.java
jhipster-modules/jhipster-uaa/uaa/src/main/java/com/baeldung/jhipster/uaa/web/rest/vm/KeyAndPasswordVM.java
package com.baeldung.jhipster.uaa.web.rest.vm; /** * View Model object for storing the user's key and password. */ public class KeyAndPasswordVM { private String key; private String newPassword; public String getKey() { return key; } public void setKey(String key) { this.key = key; } public String getNewPassword() { return newPassword; } public void setNewPassword(String newPassword) { this.newPassword = newPassword; } }
java
MIT
4463e58ffb73fe599bac2479abd84598c6e70a1a
2026-01-04T14:45:57.069771Z
false
eugenp/tutorials
https://github.com/eugenp/tutorials/blob/4463e58ffb73fe599bac2479abd84598c6e70a1a/jhipster-modules/jhipster-uaa/uaa/src/main/java/com/baeldung/jhipster/uaa/web/rest/vm/ManagedUserVM.java
jhipster-modules/jhipster-uaa/uaa/src/main/java/com/baeldung/jhipster/uaa/web/rest/vm/ManagedUserVM.java
package com.baeldung.jhipster.uaa.web.rest.vm; import com.baeldung.jhipster.uaa.service.dto.UserDTO; import javax.validation.constraints.Size; /** * View Model extending the UserDTO, which is meant to be used in the user management UI. */ public class ManagedUserVM extends UserDTO { public static final int PASSWORD_MIN_LENGTH = 4; public static final int PASSWORD_MAX_LENGTH = 100; @Size(min = PASSWORD_MIN_LENGTH, max = PASSWORD_MAX_LENGTH) private String password; public ManagedUserVM() { // Empty constructor needed for Jackson. } public String getPassword() { return password; } public void setPassword(String password) { this.password = password; } @Override public String toString() { return "ManagedUserVM{" + "} " + super.toString(); } }
java
MIT
4463e58ffb73fe599bac2479abd84598c6e70a1a
2026-01-04T14:45:57.069771Z
false
eugenp/tutorials
https://github.com/eugenp/tutorials/blob/4463e58ffb73fe599bac2479abd84598c6e70a1a/jhipster-modules/jhipster-uaa/gateway/src/test/java/com/baeldung/jhipster/gateway/gateway/responserewriting/SwaggerBasePathRewritingFilterUnitTest.java
jhipster-modules/jhipster-uaa/gateway/src/test/java/com/baeldung/jhipster/gateway/gateway/responserewriting/SwaggerBasePathRewritingFilterUnitTest.java
package com.baeldung.jhipster.gateway.gateway.responserewriting; import com.netflix.zuul.context.RequestContext; import org.apache.commons.io.IOUtils; import org.junit.Test; import org.springframework.mock.web.MockHttpServletRequest; import org.springframework.mock.web.MockHttpServletResponse; import java.io.ByteArrayInputStream; import java.io.InputStream; import java.nio.charset.StandardCharsets; import java.util.zip.GZIPInputStream; import static com.baeldung.jhipster.gateway.gateway.responserewriting.SwaggerBasePathRewritingFilter.gzipData; import static org.junit.Assert.*; import static springfox.documentation.swagger2.web.Swagger2Controller.DEFAULT_URL; /** * Tests SwaggerBasePathRewritingFilter class. */ public class SwaggerBasePathRewritingFilterUnitTest { private SwaggerBasePathRewritingFilter filter = new SwaggerBasePathRewritingFilter(); @Test public void shouldFilter_on_default_swagger_url() { MockHttpServletRequest request = new MockHttpServletRequest("GET", DEFAULT_URL); RequestContext.getCurrentContext().setRequest(request); assertTrue(filter.shouldFilter()); } /** * Zuul DebugFilter can be triggered by "deug" parameter. */ @Test public void shouldFilter_on_default_swagger_url_with_param() { MockHttpServletRequest request = new MockHttpServletRequest("GET", DEFAULT_URL); request.setParameter("debug", "true"); RequestContext.getCurrentContext().setRequest(request); assertTrue(filter.shouldFilter()); } @Test public void shouldNotFilter_on_wrong_url() { MockHttpServletRequest request = new MockHttpServletRequest("GET", "/management/info"); RequestContext.getCurrentContext().setRequest(request); assertFalse(filter.shouldFilter()); } @Test public void run_on_valid_response() throws Exception { MockHttpServletRequest request = new MockHttpServletRequest("GET", "/service1" + DEFAULT_URL); RequestContext context = RequestContext.getCurrentContext(); context.setRequest(request); MockHttpServletResponse response = new MockHttpServletResponse(); context.setResponseGZipped(false); context.setResponse(response); InputStream in = IOUtils.toInputStream("{\"basePath\":\"/\"}", StandardCharsets.UTF_8); context.setResponseDataStream(in); filter.run(); assertEquals("UTF-8", response.getCharacterEncoding()); assertEquals("{\"basePath\":\"/service1\"}", context.getResponseBody()); } @Test public void run_on_valid_response_gzip() throws Exception { MockHttpServletRequest request = new MockHttpServletRequest("GET", "/service1" + DEFAULT_URL); RequestContext context = RequestContext.getCurrentContext(); context.setRequest(request); MockHttpServletResponse response = new MockHttpServletResponse(); context.setResponseGZipped(true); context.setResponse(response); context.setResponseDataStream(new ByteArrayInputStream(gzipData("{\"basePath\":\"/\"}"))); filter.run(); assertEquals("UTF-8", response.getCharacterEncoding()); InputStream responseDataStream = new GZIPInputStream(context.getResponseDataStream()); String responseBody = IOUtils.toString(responseDataStream, StandardCharsets.UTF_8); assertEquals("{\"basePath\":\"/service1\"}", responseBody); } }
java
MIT
4463e58ffb73fe599bac2479abd84598c6e70a1a
2026-01-04T14:45:57.069771Z
false
eugenp/tutorials
https://github.com/eugenp/tutorials/blob/4463e58ffb73fe599bac2479abd84598c6e70a1a/jhipster-modules/jhipster-uaa/gateway/src/test/java/com/baeldung/jhipster/gateway/security/OAuth2TokenMockUtil.java
jhipster-modules/jhipster-uaa/gateway/src/test/java/com/baeldung/jhipster/gateway/security/OAuth2TokenMockUtil.java
package com.baeldung.jhipster.gateway.security; import org.springframework.boot.test.mock.mockito.MockBean; import org.springframework.mock.web.MockHttpServletRequest; import org.springframework.security.authentication.UsernamePasswordAuthenticationToken; import org.springframework.security.core.Authentication; import org.springframework.security.core.GrantedAuthority; import org.springframework.security.core.authority.SimpleGrantedAuthority; import org.springframework.security.core.userdetails.User; import org.springframework.security.oauth2.common.DefaultOAuth2AccessToken; import org.springframework.security.oauth2.provider.OAuth2Authentication; import org.springframework.security.oauth2.provider.OAuth2Request; import org.springframework.security.oauth2.provider.token.ResourceServerTokenServices; import org.springframework.stereotype.Component; import org.springframework.test.web.servlet.request.RequestPostProcessor; import java.util.Collections; import java.util.List; import java.util.Set; import java.util.UUID; import java.util.stream.Collectors; import static org.mockito.BDDMockito.given; /** * A bean providing simple mocking of OAuth2 access tokens for security integration tests. */ @Component public class OAuth2TokenMockUtil { @MockBean private ResourceServerTokenServices tokenServices; private OAuth2Authentication createAuthentication(String username, Set<String> scopes, Set<String> roles) { List<GrantedAuthority> authorities = roles.stream() .map(SimpleGrantedAuthority::new) .collect(Collectors.toList()); User principal = new User(username, "test", true, true, true, true, authorities); Authentication authentication = new UsernamePasswordAuthenticationToken(principal, principal.getPassword(), principal.getAuthorities()); // Create the authorization request and OAuth2Authentication object OAuth2Request authRequest = new OAuth2Request(null, "testClient", null, true, scopes, null, null, null, null); return new OAuth2Authentication(authRequest, authentication); } public RequestPostProcessor oauth2Authentication(String username, Set<String> scopes, Set<String> roles) { String uuid = String.valueOf(UUID.randomUUID()); given(tokenServices.loadAuthentication(uuid)) .willReturn(createAuthentication(username, scopes, roles)); given(tokenServices.readAccessToken(uuid)).willReturn(new DefaultOAuth2AccessToken(uuid)); return new OAuth2PostProcessor(uuid); } public RequestPostProcessor oauth2Authentication(String username, Set<String> scopes) { return oauth2Authentication(username, scopes, Collections.emptySet()); } public RequestPostProcessor oauth2Authentication(String username) { return oauth2Authentication(username, Collections.emptySet()); } public static class OAuth2PostProcessor implements RequestPostProcessor { private String token; public OAuth2PostProcessor(String token) { this.token = token; } @Override public MockHttpServletRequest postProcessRequest(MockHttpServletRequest mockHttpServletRequest) { mockHttpServletRequest.addHeader("Authorization", "Bearer " + token); return mockHttpServletRequest; } } }
java
MIT
4463e58ffb73fe599bac2479abd84598c6e70a1a
2026-01-04T14:45:57.069771Z
false
eugenp/tutorials
https://github.com/eugenp/tutorials/blob/4463e58ffb73fe599bac2479abd84598c6e70a1a/jhipster-modules/jhipster-uaa/gateway/src/test/java/com/baeldung/jhipster/gateway/security/oauth2/OAuth2CookieHelperUnitTest.java
jhipster-modules/jhipster-uaa/gateway/src/test/java/com/baeldung/jhipster/gateway/security/oauth2/OAuth2CookieHelperUnitTest.java
package com.baeldung.jhipster.gateway.security.oauth2; import com.baeldung.jhipster.gateway.config.oauth2.OAuth2Properties; import org.junit.Assert; import org.junit.Before; import org.junit.Test; import org.springframework.mock.web.MockHttpServletRequest; import org.springframework.test.util.ReflectionTestUtils; /** * Tests helper functions around OAuth2 Cookies. * * @see OAuth2CookieHelper */ public class OAuth2CookieHelperUnitTest { public static final String GET_COOKIE_DOMAIN_METHOD = "getCookieDomain"; private OAuth2Properties oAuth2Properties; private OAuth2CookieHelper cookieHelper; @Before public void setUp() throws NoSuchMethodException { oAuth2Properties = new OAuth2Properties(); cookieHelper = new OAuth2CookieHelper(oAuth2Properties); } @Test public void testLocalhostDomain() { MockHttpServletRequest request = new MockHttpServletRequest(); request.setServerName("localhost"); String name = ReflectionTestUtils.invokeMethod(cookieHelper, GET_COOKIE_DOMAIN_METHOD, request); Assert.assertNull(name); } @Test public void testComDomain() { MockHttpServletRequest request = new MockHttpServletRequest(); request.setServerName("test.com"); String name = ReflectionTestUtils.invokeMethod(cookieHelper, GET_COOKIE_DOMAIN_METHOD, request); Assert.assertNull(name); //already top-level domain } @Test public void testWwwDomainCom() { MockHttpServletRequest request = new MockHttpServletRequest(); request.setServerName("www.test.com"); String name = ReflectionTestUtils.invokeMethod(cookieHelper, GET_COOKIE_DOMAIN_METHOD, request); Assert.assertNull(name); } @Test public void testComSubDomain() { MockHttpServletRequest request = new MockHttpServletRequest(); request.setServerName("abc.test.com"); String name = ReflectionTestUtils.invokeMethod(cookieHelper, GET_COOKIE_DOMAIN_METHOD, request); Assert.assertEquals(".test.com", name); } @Test public void testWwwSubDomainCom() { MockHttpServletRequest request = new MockHttpServletRequest(); request.setServerName("www.abc.test.com"); String name = ReflectionTestUtils.invokeMethod(cookieHelper, GET_COOKIE_DOMAIN_METHOD, request); Assert.assertEquals(".test.com", name); } @Test public void testCoUkDomain() { MockHttpServletRequest request = new MockHttpServletRequest(); request.setServerName("test.co.uk"); String name = ReflectionTestUtils.invokeMethod(cookieHelper, GET_COOKIE_DOMAIN_METHOD, request); Assert.assertNull(name); //already top-level domain } @Test public void testCoUkSubDomain() { MockHttpServletRequest request = new MockHttpServletRequest(); request.setServerName("abc.test.co.uk"); String name = ReflectionTestUtils.invokeMethod(cookieHelper, GET_COOKIE_DOMAIN_METHOD, request); Assert.assertEquals(".test.co.uk", name); } @Test public void testNestedDomain() { MockHttpServletRequest request = new MockHttpServletRequest(); request.setServerName("abc.xyu.test.co.uk"); String name = ReflectionTestUtils.invokeMethod(cookieHelper, GET_COOKIE_DOMAIN_METHOD, request); Assert.assertEquals(".test.co.uk", name); } @Test public void testIpAddress() { MockHttpServletRequest request = new MockHttpServletRequest(); request.setServerName("127.0.0.1"); String name = ReflectionTestUtils.invokeMethod(cookieHelper, GET_COOKIE_DOMAIN_METHOD, request); Assert.assertNull(name); } }
java
MIT
4463e58ffb73fe599bac2479abd84598c6e70a1a
2026-01-04T14:45:57.069771Z
false
eugenp/tutorials
https://github.com/eugenp/tutorials/blob/4463e58ffb73fe599bac2479abd84598c6e70a1a/jhipster-modules/jhipster-uaa/gateway/src/test/java/com/baeldung/jhipster/gateway/security/oauth2/CookieCollectionUnitTest.java
jhipster-modules/jhipster-uaa/gateway/src/test/java/com/baeldung/jhipster/gateway/security/oauth2/CookieCollectionUnitTest.java
package com.baeldung.jhipster.gateway.security.oauth2; import org.junit.After; import org.junit.Assert; import org.junit.Before; import org.junit.Test; import javax.servlet.http.Cookie; import java.util.Arrays; import java.util.Collections; import java.util.Iterator; import java.util.List; /** * Test the CookieCollection. * * @see CookieCollection */ public class CookieCollectionUnitTest { public static final String COOKIE_NAME = "chocolate"; public static final String COOKIE_VALUE = "yummy"; public static final String BROWNIE_NAME = "brownie"; private Cookie cookie; private Cookie cupsCookie; private Cookie brownieCookie; @Before public void setUp() throws Exception { cookie = new Cookie(COOKIE_NAME, COOKIE_VALUE); cupsCookie = new Cookie("cups", "delicious"); brownieCookie = new Cookie(BROWNIE_NAME, "mmh"); } @After public void tearDown() throws Exception { } @Test public void size() throws Exception { CookieCollection cookies = new CookieCollection(); Assert.assertEquals(0, cookies.size()); cookies.add(cookie); Assert.assertEquals(1, cookies.size()); } @Test public void isEmpty() throws Exception { CookieCollection cookies = new CookieCollection(); Assert.assertTrue(cookies.isEmpty()); cookies.add(cookie); Assert.assertFalse(cookies.isEmpty()); } @Test public void contains() throws Exception { CookieCollection cookies = new CookieCollection(cookie); Assert.assertTrue(cookies.contains(cookie)); Assert.assertTrue(cookies.contains(COOKIE_NAME)); Assert.assertFalse(cookies.contains("yuck")); } @Test public void iterator() throws Exception { CookieCollection cookies = new CookieCollection(cookie); Iterator<Cookie> it = cookies.iterator(); Assert.assertTrue(it.hasNext()); Assert.assertEquals(cookie, it.next()); Assert.assertFalse(it.hasNext()); } @Test public void toArray() throws Exception { CookieCollection cookies = new CookieCollection(cookie); Cookie[] array = cookies.toArray(); Assert.assertEquals(cookies.size(), array.length); Assert.assertEquals(cookie, array[0]); } @Test public void toArray1() throws Exception { CookieCollection cookies = new CookieCollection(cookie); Cookie[] array = new Cookie[cookies.size()]; cookies.toArray(array); Assert.assertEquals(cookies.size(), array.length); Assert.assertEquals(cookie, array[0]); } @Test public void add() throws Exception { CookieCollection cookies = new CookieCollection(cookie); Cookie newCookie = new Cookie(BROWNIE_NAME, "mmh"); cookies.add(newCookie); Assert.assertEquals(2, cookies.size()); Assert.assertTrue(cookies.contains(newCookie)); Assert.assertTrue(cookies.contains(BROWNIE_NAME)); } @Test public void addAgain() { CookieCollection cookies = new CookieCollection(cookie, brownieCookie, cupsCookie); Cookie white = new Cookie(COOKIE_NAME, "white"); boolean modified = cookies.add(white); Assert.assertTrue(modified); Assert.assertEquals(white, cookies.get(COOKIE_NAME)); Assert.assertTrue(cookies.contains(white)); Assert.assertFalse(cookies.contains(cookie)); Assert.assertTrue(cookies.contains(COOKIE_NAME)); } @Test public void get() { CookieCollection cookies = new CookieCollection(cookie, brownieCookie, cupsCookie); Cookie c = cookies.get(COOKIE_NAME); Assert.assertNotNull(c); Assert.assertEquals(cookie, c); } @Test public void remove() throws Exception { CookieCollection cookies = new CookieCollection(cookie, brownieCookie, cupsCookie); cookies.remove(cookie); Assert.assertEquals(2, cookies.size()); Assert.assertFalse(cookies.contains(cookie)); Assert.assertFalse(cookies.contains(COOKIE_NAME)); Assert.assertTrue(cookies.contains(brownieCookie)); Assert.assertTrue(cookies.contains(BROWNIE_NAME)); } @Test public void containsAll() throws Exception { List<Cookie> content = Arrays.asList(cookie, brownieCookie); CookieCollection cookies = new CookieCollection(content); Assert.assertTrue(cookies.containsAll(content)); Assert.assertTrue(cookies.containsAll(Collections.singletonList(cookie))); Assert.assertFalse(cookies.containsAll(Arrays.asList(cookie, brownieCookie, cupsCookie))); Assert.assertTrue(cookies.containsAll(Arrays.asList(COOKIE_NAME, BROWNIE_NAME))); } @Test @SuppressWarnings("unchecked") public void addAll() throws Exception { CookieCollection cookies = new CookieCollection(); List<Cookie> content = Arrays.asList(cookie, brownieCookie, cupsCookie); boolean modified = cookies.addAll(content); Assert.assertTrue(modified); Assert.assertEquals(3, cookies.size()); Assert.assertTrue(cookies.containsAll(content)); Assert.assertFalse(cookies.addAll(Collections.EMPTY_LIST)); } @Test public void removeAll() throws Exception { CookieCollection cookies = new CookieCollection(cookie, brownieCookie, cupsCookie); boolean modified = cookies.removeAll(Arrays.asList(brownieCookie, cupsCookie)); Assert.assertTrue(modified); Assert.assertEquals(1, cookies.size()); Assert.assertFalse(cookies.contains(brownieCookie)); Assert.assertFalse(cookies.contains(cupsCookie)); Assert.assertFalse(cookies.removeAll(Collections.EMPTY_LIST)); } @Test public void removeAllByName() throws Exception { CookieCollection cookies = new CookieCollection(cookie, brownieCookie, cupsCookie); boolean modified = cookies.removeAll(Arrays.asList(COOKIE_NAME, BROWNIE_NAME)); Assert.assertTrue(modified); Assert.assertEquals(1, cookies.size()); Assert.assertFalse(cookies.contains(brownieCookie)); Assert.assertFalse(cookies.contains(cookie)); Assert.assertFalse(cookies.removeAll(Collections.EMPTY_LIST)); } @Test public void retainAll() throws Exception { CookieCollection cookies = new CookieCollection(cookie, brownieCookie, cupsCookie); List<Cookie> content = Arrays.asList(cookie, brownieCookie); boolean modified = cookies.retainAll(content); Assert.assertTrue(modified); Assert.assertEquals(2, cookies.size()); Assert.assertTrue(cookies.containsAll(content)); Assert.assertFalse(cookies.contains(cupsCookie)); Assert.assertFalse(cookies.retainAll(content)); } @Test public void clear() throws Exception { CookieCollection cookies = new CookieCollection(cookie); cookies.clear(); Assert.assertTrue(cookies.isEmpty()); } }
java
MIT
4463e58ffb73fe599bac2479abd84598c6e70a1a
2026-01-04T14:45:57.069771Z
false
eugenp/tutorials
https://github.com/eugenp/tutorials/blob/4463e58ffb73fe599bac2479abd84598c6e70a1a/jhipster-modules/jhipster-uaa/gateway/src/test/java/com/baeldung/jhipster/gateway/security/oauth2/CookieTokenExtractorUnitTest.java
jhipster-modules/jhipster-uaa/gateway/src/test/java/com/baeldung/jhipster/gateway/security/oauth2/CookieTokenExtractorUnitTest.java
package com.baeldung.jhipster.gateway.security.oauth2; import org.junit.Assert; import org.junit.Before; import org.junit.Test; import org.springframework.http.HttpMethod; import org.springframework.mock.web.MockHttpServletRequest; import org.springframework.security.core.Authentication; import org.springframework.security.oauth2.common.OAuth2AccessToken; /** * Test whether the CookieTokenExtractor can properly extract access tokens from * Cookies and Headers. */ public class CookieTokenExtractorUnitTest { private CookieTokenExtractor cookieTokenExtractor; @Before public void init() { cookieTokenExtractor = new CookieTokenExtractor(); } @Test public void testExtractTokenCookie() { MockHttpServletRequest request = OAuth2AuthenticationServiceUnitTest.createMockHttpServletRequest(); Authentication authentication = cookieTokenExtractor.extract(request); Assert.assertEquals(OAuth2AuthenticationServiceUnitTest.ACCESS_TOKEN_VALUE, authentication.getPrincipal().toString()); } @Test public void testExtractTokenHeader() { MockHttpServletRequest request = new MockHttpServletRequest(HttpMethod.GET.name(), "http://www.test.com"); request.addHeader("Authorization", OAuth2AccessToken.BEARER_TYPE + " " + OAuth2AuthenticationServiceUnitTest.ACCESS_TOKEN_VALUE); Authentication authentication = cookieTokenExtractor.extract(request); Assert.assertEquals(OAuth2AuthenticationServiceUnitTest.ACCESS_TOKEN_VALUE, authentication.getPrincipal().toString()); } @Test public void testExtractTokenParam() { MockHttpServletRequest request = new MockHttpServletRequest(HttpMethod.GET.name(), "http://www.test.com"); request.addParameter(OAuth2AccessToken.ACCESS_TOKEN, OAuth2AuthenticationServiceUnitTest.ACCESS_TOKEN_VALUE); Authentication authentication = cookieTokenExtractor.extract(request); Assert.assertEquals(OAuth2AuthenticationServiceUnitTest.ACCESS_TOKEN_VALUE, authentication.getPrincipal().toString()); } }
java
MIT
4463e58ffb73fe599bac2479abd84598c6e70a1a
2026-01-04T14:45:57.069771Z
false
eugenp/tutorials
https://github.com/eugenp/tutorials/blob/4463e58ffb73fe599bac2479abd84598c6e70a1a/jhipster-modules/jhipster-uaa/gateway/src/test/java/com/baeldung/jhipster/gateway/security/oauth2/OAuth2AuthenticationServiceUnitTest.java
jhipster-modules/jhipster-uaa/gateway/src/test/java/com/baeldung/jhipster/gateway/security/oauth2/OAuth2AuthenticationServiceUnitTest.java
package com.baeldung.jhipster.gateway.security.oauth2; import com.baeldung.jhipster.gateway.config.oauth2.OAuth2Properties; import com.baeldung.jhipster.gateway.web.filter.RefreshTokenFilter; import com.baeldung.jhipster.gateway.web.rest.errors.InvalidPasswordException; import io.github.jhipster.config.JHipsterProperties; import org.junit.Assert; import org.junit.Before; import org.junit.Rule; import org.junit.Test; import org.junit.rules.ExpectedException; import org.junit.runner.RunWith; import org.mockito.Mock; import org.mockito.junit.MockitoJUnitRunner; import org.springframework.http.*; import org.springframework.mock.web.MockHttpServletRequest; import org.springframework.mock.web.MockHttpServletResponse; import org.springframework.security.oauth2.common.DefaultOAuth2AccessToken; import org.springframework.security.oauth2.common.DefaultOAuth2RefreshToken; import org.springframework.security.oauth2.common.OAuth2AccessToken; import org.springframework.security.oauth2.common.exceptions.InvalidTokenException; import org.springframework.security.oauth2.provider.token.TokenStore; import org.springframework.util.LinkedMultiValueMap; import org.springframework.util.MultiValueMap; import org.springframework.web.client.HttpClientErrorException; import org.springframework.web.client.RestTemplate; import javax.servlet.http.Cookie; import javax.servlet.http.HttpServletRequest; import java.util.Date; import java.util.HashMap; import java.util.Map; import static org.mockito.Mockito.when; /** * Test password and refresh token grants. * * @see OAuth2AuthenticationService */ @RunWith(MockitoJUnitRunner.class) public class OAuth2AuthenticationServiceUnitTest { public static final String CLIENT_AUTHORIZATION = "Basic d2ViX2FwcDpjaGFuZ2VpdA=="; public static final String ACCESS_TOKEN_VALUE = "eyJhbGciOiJSUzI1NiIsInR5cCI6IkpXVCJ9.eyJleHAiOjE0OTQyNzI4NDQsInVzZXJfbmFtZSI6InVzZXIiLCJhdXRob3JpdGllcyI6WyJST0xFX1VTRVIiXSwianRpIjoiNzc1ZTJkYWUtYWYzZi00YTdhLWExOTktNzNiZTU1MmIxZDVkIiwiY2xpZW50X2lkIjoid2ViX2FwcCIsInNjb3BlIjpbIm9wZW5pZCJdfQ.gEK0YcX2IpkpxnkxXXHQ4I0xzTjcy7edqb89ukYE0LPe7xUcZVwkkCJF_nBxsGJh2jtA6NzNLfY5zuL6nP7uoAq3fmvsyrcyR2qPk8JuuNzGtSkICx3kPDRjAT4ST8SZdeh7XCbPVbySJ7ZmPlRWHyedzLA1wXN0NUf8yZYS4ELdUwVBYIXSjkNoKqfWm88cwuNr0g0teypjPtjDqCnXFt1pibwdfIXn479Y1neNAdvSpHcI4Ost-c7APCNxW2gqX-0BItZQearxRgKDdBQ7CGPAIky7dA0gPuKUpp_VCoqowKCXqkE9yKtRQGIISewtj2UkDRZePmzmYrUBXRzfYw"; public static final String REFRESH_TOKEN_VALUE = "eyJhbGciOiJSUzI1NiIsInR5cCI6IkpXVCJ9.eyJ1c2VyX25hbWUiOiJ1c2VyIiwic2NvcGUiOlsib3BlbmlkIl0sImF0aSI6Ijc3NWUyZGFlLWFmM2YtNGE3YS1hMTk5LTczYmU1NTJiMWQ1ZCIsImV4cCI6MTQ5Njg2NDc0MywiYXV0aG9yaXRpZXMiOlsiUk9MRV9VU0VSIl0sImp0aSI6IjhmYjI2YTllLTdjYzQtNDFlMi1hNzBjLTk4MDc0N2U2YWFiOSIsImNsaWVudF9pZCI6IndlYl9hcHAifQ.q1-Df9_AFO6TJNiLKV2YwTjRbnd7qcXv52skXYnog5siHYRoR6cPtm6TNQ04iDAoIHljTSTNnD6DS3bHk41mV55gsSVxGReL8VCb_R8ZmhVL4-5yr90sfms0wFp6lgD2bPmZ-TXiS2Oe9wcbNWagy5RsEplZ-sbXu3tjmDao4FN35ojPsXmUs84XnNQH3Y_-PY9GjZG0JEfLQIvE0J5BkXS18Z015GKyA6GBIoLhAGBQQYyG9m10ld_a9fD5SmCyCF72Jad_pfP1u8Z_WyvO-wrlBvm2x-zBthreVrXU5mOb9795wJEP-xaw3dXYGjht_grcW4vKUFtj61JgZk98CQ"; public static final String EXPIRED_SESSION_TOKEN_VALUE = "eyJhbGciOiJSUzI1NiIsInR5cCI6IkpXVCJ9.eyJ1c2VyX25hbWUiOiJ1c2VyIiwic2NvcGUiOlsib3BlbmlkIl0sImF0aSI6IjE0NTkwYzdkLTQ5M2YtNDU0NS05MzlmLTg1ODM4ZjRmNzNmNSIsImV4cCI6MTQ5NTU3Mjg5MywiaWF0IjoxNDk1MzIwODkzLCJhdXRob3JpdGllcyI6WyJST0xFX1VTRVIiXSwianRpIjoiNzVhYTIxNzEtMzFmNi00MWJmLWExZGUtYWU0YTg1ZjZiMjEyIiwiY2xpZW50X2lkIjoid2ViX2FwcCJ9.gAH-yly7WAslQUeGhyHmjYXwQN3dluvoT84iOJ2mVWYGVlnDRsoxN3_d1ozqtiso9UM7dWpAr80o3gK7AyK-cO1GGBXa3lg0ETsbucFoqHLivgGZA2qVOsFlDq8E7DZENAbOWmywmhFUOogCfZ-BqsuFSi8waMLL-1qlhehBPuK1KzGxIZbjSVUFFFYTxoWPKi2NNTBzYSwwCV0ixj-gHyFC6Gl5ByA4EvYygGUZF2pACxs4tIRkmT90pXWCjWeKS9k9MlxZ7C4UHqyTRW-IYzqAm8OHdwsnXeu0GkFYc08gxoUuPcjMby8ziYLG5uWj0Ua0msmiSjoafzs-5xfH-Q"; public static final String NEW_ACCESS_TOKEN_VALUE = "eyJhbGciOiJSUzI1NiIsInR5cCI6IkpXVCJ9.eyJleHAiOjE0OTQyNzY2NDEsInVzZXJfbmFtZSI6InVzZXIiLCJhdXRob3JpdGllcyI6WyJST0xFX1VTRVIiXSwianRpIjoiYzIyY2YzMDgtZTIyYi00YzNjLWI5MjctOTYwYzA2YmY1ZmU0IiwiY2xpZW50X2lkIjoid2ViX2FwcCIsInNjb3BlIjpbIm9wZW5pZCJdfQ.IAhE39GCqWRUuXdWy-raOcE9NYXRhGiqkeJH649501LeqNPH5HtRUNWmudVRgwT52Bj7HcbJapMLGetKIMEASqC1-WARfcZ_PR0r7Kfg3OlFALWOH_oVT5kvi2H-QCoSAF9mRYK6abCh_tPk5KryVB5c7YxTMIXDT2nTsSexD8eNQOMBWRCg0RaLHZ9bKfeyVgncQJsu7-vTo1xJyh-keYpdNZ0TA2SjYJgezmB7gwW1Kmc7_83htr8VycG7XA_PuD9--yRNlrN0LtNHEBqNypZsOe6NvpKiNlodFYHlsU1CaumzcF9U7dpVanjIUKJ5VRWVUlSFY6JJ755W29VCTw"; public static final String NEW_REFRESH_TOKEN_VALUE = "eyJhbGciOiJSUzI1NiIsInR5cCI6IkpXVCJ9.eyJ1c2VyX25hbWUiOiJ1c2VyIiwic2NvcGUiOlsib3BlbmlkIl0sImF0aSI6ImMyMmNmMzA4LWUyMmItNGMzYy1iOTI3LTk2MGMwNmJmNWZlNCIsImV4cCI6MTQ5Njg2ODU4MSwiYXV0aG9yaXRpZXMiOlsiUk9MRV9VU0VSIl0sImp0aSI6ImU4YmZhZWJlLWYzMDItNGNjZS1hZGY1LWQ4MzE5OWM1MjBlOSIsImNsaWVudF9pZCI6IndlYl9hcHAifQ.OemWBUfc-2rl4t4VVqolYxul3L527PbSbX2Xvo7oyy3Vy5nmmblqp4hVGdTEjivrlldGVQX03ERbrA-oFkpmfWbBzLvnKS6AUq1MGjut6dXZJeiEqNYmiAABn6jSgK26S0k6b2ADgmf7mxJO8EBypb5sT1DMAbY5cbOe7r4ZG7zMTVSvlvjHTXp_FM8Y9i6nehLD4XDYY57cb_ZA89vAXNzvTAjoopDliExgR0bApG6nvvDEhEYgTS65lccEQocoev6bISJ3RvNYNPJxWcNPftKDp4HrEt2E2WP28K5IivRtQgDQNlQeormf1tp6AG-Oj__NXyAPM7yhAKXNy2zWdQ"; @Mock private RestTemplate restTemplate; @Mock private TokenStore tokenStore; private OAuth2TokenEndpointClient authorizationClient; private OAuth2AuthenticationService authenticationService; private RefreshTokenFilter refreshTokenFilter; @Rule public ExpectedException expectedException = ExpectedException.none(); private OAuth2Properties oAuth2Properties; private JHipsterProperties jHipsterProperties; @Before public void init() { oAuth2Properties = new OAuth2Properties(); jHipsterProperties = new JHipsterProperties(); jHipsterProperties.getSecurity().getClientAuthorization().setAccessTokenUri("http://uaa/oauth/token"); OAuth2CookieHelper cookieHelper = new OAuth2CookieHelper(oAuth2Properties); OAuth2AccessToken accessToken = createAccessToken(ACCESS_TOKEN_VALUE, REFRESH_TOKEN_VALUE); mockInvalidPassword(); mockPasswordGrant(accessToken); mockRefreshGrant(); authorizationClient = new UaaTokenEndpointClient(restTemplate, jHipsterProperties, oAuth2Properties); authenticationService = new OAuth2AuthenticationService(authorizationClient, cookieHelper); when(tokenStore.readAccessToken(ACCESS_TOKEN_VALUE)).thenReturn(accessToken); refreshTokenFilter = new RefreshTokenFilter(authenticationService, tokenStore); } public static OAuth2AccessToken createAccessToken(String accessTokenValue, String refreshTokenValue) { DefaultOAuth2AccessToken accessToken = new DefaultOAuth2AccessToken(accessTokenValue); accessToken.setExpiration(new Date()); //token expires now DefaultOAuth2RefreshToken refreshToken = new DefaultOAuth2RefreshToken(refreshTokenValue); accessToken.setRefreshToken(refreshToken); return accessToken; } public static MockHttpServletRequest createMockHttpServletRequest() { MockHttpServletRequest request = new MockHttpServletRequest(HttpMethod.GET.name(), "http://www.test.com"); Cookie accessTokenCookie = new Cookie(OAuth2CookieHelper.ACCESS_TOKEN_COOKIE, ACCESS_TOKEN_VALUE); Cookie refreshTokenCookie = new Cookie(OAuth2CookieHelper.REFRESH_TOKEN_COOKIE, REFRESH_TOKEN_VALUE); request.setCookies(accessTokenCookie, refreshTokenCookie); return request; } private void mockInvalidPassword() { HttpHeaders reqHeaders = new HttpHeaders(); reqHeaders.setContentType(MediaType.APPLICATION_FORM_URLENCODED); reqHeaders.add("Authorization", CLIENT_AUTHORIZATION); //take over Authorization header from client request to UAA request MultiValueMap<String, String> formParams = new LinkedMultiValueMap<>(); formParams.set("username", "user"); formParams.set("password", "user2"); formParams.add("grant_type", "password"); HttpEntity<MultiValueMap<String, String>> entity = new HttpEntity<>(formParams, reqHeaders); when(restTemplate.postForEntity("http://uaa/oauth/token", entity, OAuth2AccessToken.class)) .thenThrow(new HttpClientErrorException(HttpStatus.BAD_REQUEST)); } private void mockPasswordGrant(OAuth2AccessToken accessToken) { HttpHeaders reqHeaders = new HttpHeaders(); reqHeaders.setContentType(MediaType.APPLICATION_FORM_URLENCODED); reqHeaders.add("Authorization", CLIENT_AUTHORIZATION); //take over Authorization header from client request to UAA request MultiValueMap<String, String> formParams = new LinkedMultiValueMap<>(); formParams.set("username", "user"); formParams.set("password", "user"); formParams.add("grant_type", "password"); HttpEntity<MultiValueMap<String, String>> entity = new HttpEntity<>(formParams, reqHeaders); when(restTemplate.postForEntity("http://uaa/oauth/token", entity, OAuth2AccessToken.class)) .thenReturn(new ResponseEntity<OAuth2AccessToken>(accessToken, HttpStatus.OK)); } private void mockRefreshGrant() { MultiValueMap<String, String> params = new LinkedMultiValueMap<>(); params.add("grant_type", "refresh_token"); params.add("refresh_token", REFRESH_TOKEN_VALUE); //we must authenticate with the UAA server via HTTP basic authentication using the browser's client_id with no client secret HttpHeaders headers = new HttpHeaders(); headers.add("Authorization", CLIENT_AUTHORIZATION); HttpEntity<MultiValueMap<String, String>> entity = new HttpEntity<>(params, headers); OAuth2AccessToken newAccessToken = createAccessToken(NEW_ACCESS_TOKEN_VALUE, NEW_REFRESH_TOKEN_VALUE); when(restTemplate.postForEntity("http://uaa/oauth/token", entity, OAuth2AccessToken.class)) .thenReturn(new ResponseEntity<OAuth2AccessToken>(newAccessToken, HttpStatus.OK)); } @Test public void testAuthenticationCookies() { MockHttpServletRequest request = new MockHttpServletRequest(); request.setServerName("www.test.com"); request.addHeader("Authorization", CLIENT_AUTHORIZATION); Map<String, String> params = new HashMap<>(); params.put("username", "user"); params.put("password", "user"); params.put("rememberMe", "true"); MockHttpServletResponse response = new MockHttpServletResponse(); authenticationService.authenticate(request, response, params); //check that cookies are set correctly Cookie accessTokenCookie = response.getCookie(OAuth2CookieHelper.ACCESS_TOKEN_COOKIE); Assert.assertEquals(ACCESS_TOKEN_VALUE, accessTokenCookie.getValue()); Cookie refreshTokenCookie = response.getCookie(OAuth2CookieHelper.REFRESH_TOKEN_COOKIE); Assert.assertEquals(REFRESH_TOKEN_VALUE, OAuth2CookieHelper.getRefreshTokenValue(refreshTokenCookie)); Assert.assertTrue(OAuth2CookieHelper.isRememberMe(refreshTokenCookie)); } @Test public void testAuthenticationNoRememberMe() { MockHttpServletRequest request = new MockHttpServletRequest(); request.setServerName("www.test.com"); Map<String, String> params = new HashMap<>(); params.put("username", "user"); params.put("password", "user"); params.put("rememberMe", "false"); MockHttpServletResponse response = new MockHttpServletResponse(); authenticationService.authenticate(request, response, params); //check that cookies are set correctly Cookie accessTokenCookie = response.getCookie(OAuth2CookieHelper.ACCESS_TOKEN_COOKIE); Assert.assertEquals(ACCESS_TOKEN_VALUE, accessTokenCookie.getValue()); Cookie refreshTokenCookie = response.getCookie(OAuth2CookieHelper.SESSION_TOKEN_COOKIE); Assert.assertEquals(REFRESH_TOKEN_VALUE, OAuth2CookieHelper.getRefreshTokenValue(refreshTokenCookie)); Assert.assertFalse(OAuth2CookieHelper.isRememberMe(refreshTokenCookie)); } @Test public void testInvalidPassword() { MockHttpServletRequest request = new MockHttpServletRequest(); request.setServerName("www.test.com"); Map<String, String> params = new HashMap<>(); params.put("username", "user"); params.put("password", "user2"); params.put("rememberMe", "false"); MockHttpServletResponse response = new MockHttpServletResponse(); expectedException.expect(InvalidPasswordException.class); authenticationService.authenticate(request, response, params); } @Test public void testRefreshGrant() { MockHttpServletRequest request = createMockHttpServletRequest(); MockHttpServletResponse response = new MockHttpServletResponse(); HttpServletRequest newRequest = refreshTokenFilter.refreshTokensIfExpiring(request, response); Cookie newAccessTokenCookie = response.getCookie(OAuth2CookieHelper.ACCESS_TOKEN_COOKIE); Assert.assertEquals(NEW_ACCESS_TOKEN_VALUE, newAccessTokenCookie.getValue()); Cookie newRefreshTokenCookie = response.getCookie(OAuth2CookieHelper.REFRESH_TOKEN_COOKIE); Assert.assertEquals(NEW_REFRESH_TOKEN_VALUE, newRefreshTokenCookie.getValue()); Cookie requestAccessTokenCookie = OAuth2CookieHelper.getAccessTokenCookie(newRequest); Assert.assertEquals(NEW_ACCESS_TOKEN_VALUE, requestAccessTokenCookie.getValue()); } @Test public void testSessionExpired() { MockHttpServletRequest request = new MockHttpServletRequest(HttpMethod.GET.name(), "http://www.test.com"); Cookie accessTokenCookie = new Cookie(OAuth2CookieHelper.ACCESS_TOKEN_COOKIE, ACCESS_TOKEN_VALUE); Cookie refreshTokenCookie = new Cookie(OAuth2CookieHelper.SESSION_TOKEN_COOKIE, EXPIRED_SESSION_TOKEN_VALUE); request.setCookies(accessTokenCookie, refreshTokenCookie); MockHttpServletResponse response = new MockHttpServletResponse(); HttpServletRequest newRequest = refreshTokenFilter.refreshTokensIfExpiring(request, response); //cookies in response are deleted Cookie newAccessTokenCookie = response.getCookie(OAuth2CookieHelper.ACCESS_TOKEN_COOKIE); Assert.assertEquals(0, newAccessTokenCookie.getMaxAge()); Cookie newRefreshTokenCookie = response.getCookie(OAuth2CookieHelper.REFRESH_TOKEN_COOKIE); Assert.assertEquals(0, newRefreshTokenCookie.getMaxAge()); //request no longer contains cookies Cookie requestAccessTokenCookie = OAuth2CookieHelper.getAccessTokenCookie(newRequest); Assert.assertNull(requestAccessTokenCookie); Cookie requestRefreshTokenCookie = OAuth2CookieHelper.getRefreshTokenCookie(newRequest); Assert.assertNull(requestRefreshTokenCookie); } /** * If no refresh token is found and the access token has expired, then expect an exception. */ @Test public void testRefreshGrantNoRefreshToken() { MockHttpServletRequest request = new MockHttpServletRequest(HttpMethod.GET.name(), "http://www.test.com"); Cookie accessTokenCookie = new Cookie(OAuth2CookieHelper.ACCESS_TOKEN_COOKIE, ACCESS_TOKEN_VALUE); request.setCookies(accessTokenCookie); MockHttpServletResponse response = new MockHttpServletResponse(); expectedException.expect(InvalidTokenException.class); refreshTokenFilter.refreshTokensIfExpiring(request, response); } @Test public void testLogout() { MockHttpServletRequest request = new MockHttpServletRequest(); Cookie accessTokenCookie = new Cookie(OAuth2CookieHelper.ACCESS_TOKEN_COOKIE, ACCESS_TOKEN_VALUE); Cookie refreshTokenCookie = new Cookie(OAuth2CookieHelper.REFRESH_TOKEN_COOKIE, REFRESH_TOKEN_VALUE); request.setCookies(accessTokenCookie, refreshTokenCookie); MockHttpServletResponse response = new MockHttpServletResponse(); authenticationService.logout(request, response); Cookie newAccessTokenCookie = response.getCookie(OAuth2CookieHelper.ACCESS_TOKEN_COOKIE); Assert.assertEquals(0, newAccessTokenCookie.getMaxAge()); Cookie newRefreshTokenCookie = response.getCookie(OAuth2CookieHelper.REFRESH_TOKEN_COOKIE); Assert.assertEquals(0, newRefreshTokenCookie.getMaxAge()); } @Test public void testStripTokens() { MockHttpServletRequest request = createMockHttpServletRequest(); HttpServletRequest newRequest = authenticationService.stripTokens(request); CookieCollection cookies = new CookieCollection(newRequest.getCookies()); Assert.assertFalse(cookies.contains(OAuth2CookieHelper.ACCESS_TOKEN_COOKIE)); Assert.assertFalse(cookies.contains(OAuth2CookieHelper.REFRESH_TOKEN_COOKIE)); } }
java
MIT
4463e58ffb73fe599bac2479abd84598c6e70a1a
2026-01-04T14:45:57.069771Z
false
eugenp/tutorials
https://github.com/eugenp/tutorials/blob/4463e58ffb73fe599bac2479abd84598c6e70a1a/jhipster-modules/jhipster-uaa/gateway/src/test/java/com/baeldung/jhipster/gateway/config/WebConfigurerUnitTest.java
jhipster-modules/jhipster-uaa/gateway/src/test/java/com/baeldung/jhipster/gateway/config/WebConfigurerUnitTest.java
package com.baeldung.jhipster.gateway.config; import com.codahale.metrics.MetricRegistry; import com.codahale.metrics.servlet.InstrumentedFilter; import com.codahale.metrics.servlets.MetricsServlet; import io.github.jhipster.config.JHipsterConstants; import io.github.jhipster.config.JHipsterProperties; import io.github.jhipster.web.filter.CachingHttpHeadersFilter; import io.undertow.Undertow; import io.undertow.Undertow.Builder; import io.undertow.UndertowOptions; import org.apache.commons.io.FilenameUtils; import org.h2.server.web.WebServlet; import org.junit.Before; import org.junit.Test; import org.springframework.boot.web.embedded.undertow.UndertowServletWebServerFactory; import org.springframework.http.HttpHeaders; import org.springframework.mock.env.MockEnvironment; import org.springframework.mock.web.MockServletContext; import org.springframework.test.util.ReflectionTestUtils; import org.springframework.test.web.servlet.MockMvc; import org.springframework.test.web.servlet.setup.MockMvcBuilders; import org.xnio.OptionMap; import javax.servlet.*; import java.util.*; import static org.assertj.core.api.Assertions.assertThat; import static org.mockito.ArgumentMatchers.any; import static org.mockito.ArgumentMatchers.anyString; import static org.mockito.Mockito.*; import static org.springframework.test.web.servlet.request.MockMvcRequestBuilders.get; import static org.springframework.test.web.servlet.request.MockMvcRequestBuilders.options; import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.header; import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.status; /** * Unit tests for the WebConfigurer class. * * @see WebConfigurer */ public class WebConfigurerUnitTest { private WebConfigurer webConfigurer; private MockServletContext servletContext; private MockEnvironment env; private JHipsterProperties props; private MetricRegistry metricRegistry; @Before public void setup() { servletContext = spy(new MockServletContext()); doReturn(mock(FilterRegistration.Dynamic.class)) .when(servletContext).addFilter(anyString(), any(Filter.class)); doReturn(mock(ServletRegistration.Dynamic.class)) .when(servletContext).addServlet(anyString(), any(Servlet.class)); env = new MockEnvironment(); props = new JHipsterProperties(); webConfigurer = new WebConfigurer(env, props); metricRegistry = new MetricRegistry(); webConfigurer.setMetricRegistry(metricRegistry); } @Test public void testStartUpProdServletContext() throws ServletException { env.setActiveProfiles(JHipsterConstants.SPRING_PROFILE_PRODUCTION); webConfigurer.onStartup(servletContext); assertThat(servletContext.getAttribute(InstrumentedFilter.REGISTRY_ATTRIBUTE)).isEqualTo(metricRegistry); assertThat(servletContext.getAttribute(MetricsServlet.METRICS_REGISTRY)).isEqualTo(metricRegistry); verify(servletContext).addFilter(eq("webappMetricsFilter"), any(InstrumentedFilter.class)); verify(servletContext).addServlet(eq("metricsServlet"), any(MetricsServlet.class)); verify(servletContext).addFilter(eq("cachingHttpHeadersFilter"), any(CachingHttpHeadersFilter.class)); verify(servletContext, never()).addServlet(eq("H2Console"), any(WebServlet.class)); } @Test public void testStartUpDevServletContext() throws ServletException { env.setActiveProfiles(JHipsterConstants.SPRING_PROFILE_DEVELOPMENT); webConfigurer.onStartup(servletContext); assertThat(servletContext.getAttribute(InstrumentedFilter.REGISTRY_ATTRIBUTE)).isEqualTo(metricRegistry); assertThat(servletContext.getAttribute(MetricsServlet.METRICS_REGISTRY)).isEqualTo(metricRegistry); verify(servletContext).addFilter(eq("webappMetricsFilter"), any(InstrumentedFilter.class)); verify(servletContext).addServlet(eq("metricsServlet"), any(MetricsServlet.class)); verify(servletContext, never()).addFilter(eq("cachingHttpHeadersFilter"), any(CachingHttpHeadersFilter.class)); verify(servletContext).addServlet(eq("H2Console"), any(WebServlet.class)); } @Test public void testCustomizeServletContainer() { env.setActiveProfiles(JHipsterConstants.SPRING_PROFILE_PRODUCTION); UndertowServletWebServerFactory container = new UndertowServletWebServerFactory(); webConfigurer.customize(container); assertThat(container.getMimeMappings().get("abs")).isEqualTo("audio/x-mpeg"); assertThat(container.getMimeMappings().get("html")).isEqualTo("text/html;charset=utf-8"); assertThat(container.getMimeMappings().get("json")).isEqualTo("text/html;charset=utf-8"); if (container.getDocumentRoot() != null) { assertThat(container.getDocumentRoot().getPath()).isEqualTo(FilenameUtils.separatorsToSystem("target/www")); } Builder builder = Undertow.builder(); container.getBuilderCustomizers().forEach(c -> c.customize(builder)); OptionMap.Builder serverOptions = (OptionMap.Builder) ReflectionTestUtils.getField(builder, "serverOptions"); assertThat(serverOptions.getMap().get(UndertowOptions.ENABLE_HTTP2)).isNull(); } @Test public void testUndertowHttp2Enabled() { props.getHttp().setVersion(JHipsterProperties.Http.Version.V_2_0); UndertowServletWebServerFactory container = new UndertowServletWebServerFactory(); webConfigurer.customize(container); Builder builder = Undertow.builder(); container.getBuilderCustomizers().forEach(c -> c.customize(builder)); OptionMap.Builder serverOptions = (OptionMap.Builder) ReflectionTestUtils.getField(builder, "serverOptions"); assertThat(serverOptions.getMap().get(UndertowOptions.ENABLE_HTTP2)).isTrue(); } @Test public void testCorsFilterOnApiPath() throws Exception { props.getCors().setAllowedOrigins(Collections.singletonList("*")); props.getCors().setAllowedMethods(Arrays.asList("GET", "POST", "PUT", "DELETE")); props.getCors().setAllowedHeaders(Collections.singletonList("*")); props.getCors().setMaxAge(1800L); props.getCors().setAllowCredentials(true); MockMvc mockMvc = MockMvcBuilders.standaloneSetup(new WebConfigurerTestController()) .addFilters(webConfigurer.corsFilter()) .build(); mockMvc.perform( options("/api/test-cors") .header(HttpHeaders.ORIGIN, "other.domain.com") .header(HttpHeaders.ACCESS_CONTROL_REQUEST_METHOD, "POST")) .andExpect(status().isOk()) .andExpect(header().string(HttpHeaders.ACCESS_CONTROL_ALLOW_ORIGIN, "other.domain.com")) .andExpect(header().string(HttpHeaders.VARY, "Origin")) .andExpect(header().string(HttpHeaders.ACCESS_CONTROL_ALLOW_METHODS, "GET,POST,PUT,DELETE")) .andExpect(header().string(HttpHeaders.ACCESS_CONTROL_ALLOW_CREDENTIALS, "true")) .andExpect(header().string(HttpHeaders.ACCESS_CONTROL_MAX_AGE, "1800")); mockMvc.perform( get("/api/test-cors") .header(HttpHeaders.ORIGIN, "other.domain.com")) .andExpect(status().isOk()) .andExpect(header().string(HttpHeaders.ACCESS_CONTROL_ALLOW_ORIGIN, "other.domain.com")); } @Test public void testCorsFilterOnOtherPath() throws Exception { props.getCors().setAllowedOrigins(Collections.singletonList("*")); props.getCors().setAllowedMethods(Arrays.asList("GET", "POST", "PUT", "DELETE")); props.getCors().setAllowedHeaders(Collections.singletonList("*")); props.getCors().setMaxAge(1800L); props.getCors().setAllowCredentials(true); MockMvc mockMvc = MockMvcBuilders.standaloneSetup(new WebConfigurerTestController()) .addFilters(webConfigurer.corsFilter()) .build(); mockMvc.perform( get("/test/test-cors") .header(HttpHeaders.ORIGIN, "other.domain.com")) .andExpect(status().isOk()) .andExpect(header().doesNotExist(HttpHeaders.ACCESS_CONTROL_ALLOW_ORIGIN)); } @Test public void testCorsFilterDeactivated() throws Exception { props.getCors().setAllowedOrigins(null); MockMvc mockMvc = MockMvcBuilders.standaloneSetup(new WebConfigurerTestController()) .addFilters(webConfigurer.corsFilter()) .build(); mockMvc.perform( get("/api/test-cors") .header(HttpHeaders.ORIGIN, "other.domain.com")) .andExpect(status().isOk()) .andExpect(header().doesNotExist(HttpHeaders.ACCESS_CONTROL_ALLOW_ORIGIN)); } @Test public void testCorsFilterDeactivated2() throws Exception { props.getCors().setAllowedOrigins(new ArrayList<>()); MockMvc mockMvc = MockMvcBuilders.standaloneSetup(new WebConfigurerTestController()) .addFilters(webConfigurer.corsFilter()) .build(); mockMvc.perform( get("/api/test-cors") .header(HttpHeaders.ORIGIN, "other.domain.com")) .andExpect(status().isOk()) .andExpect(header().doesNotExist(HttpHeaders.ACCESS_CONTROL_ALLOW_ORIGIN)); } }
java
MIT
4463e58ffb73fe599bac2479abd84598c6e70a1a
2026-01-04T14:45:57.069771Z
false
eugenp/tutorials
https://github.com/eugenp/tutorials/blob/4463e58ffb73fe599bac2479abd84598c6e70a1a/jhipster-modules/jhipster-uaa/gateway/src/test/java/com/baeldung/jhipster/gateway/config/SecurityBeanOverrideConfiguration.java
jhipster-modules/jhipster-uaa/gateway/src/test/java/com/baeldung/jhipster/gateway/config/SecurityBeanOverrideConfiguration.java
package com.baeldung.jhipster.gateway.config; import org.springframework.cloud.client.loadbalancer.RestTemplateCustomizer; import org.springframework.context.annotation.Bean; import org.springframework.context.annotation.Configuration; import org.springframework.context.annotation.Primary; import org.springframework.security.oauth2.provider.token.TokenStore; import org.springframework.security.oauth2.provider.token.store.JwtAccessTokenConverter; import org.springframework.web.client.RestTemplate; /** * Overrides UAA specific beans, so they do not interfere the testing * This configuration must be included in @SpringBootTest in order to take effect. */ @Configuration public class SecurityBeanOverrideConfiguration { @Bean @Primary public TokenStore tokenStore() { return null; } @Bean @Primary public JwtAccessTokenConverter jwtAccessTokenConverter() { return null; } @Bean @Primary public RestTemplate loadBalancedRestTemplate(RestTemplateCustomizer customizer) { return null; } }
java
MIT
4463e58ffb73fe599bac2479abd84598c6e70a1a
2026-01-04T14:45:57.069771Z
false
eugenp/tutorials
https://github.com/eugenp/tutorials/blob/4463e58ffb73fe599bac2479abd84598c6e70a1a/jhipster-modules/jhipster-uaa/gateway/src/test/java/com/baeldung/jhipster/gateway/config/WebConfigurerTestController.java
jhipster-modules/jhipster-uaa/gateway/src/test/java/com/baeldung/jhipster/gateway/config/WebConfigurerTestController.java
package com.baeldung.jhipster.gateway.config; import org.springframework.web.bind.annotation.GetMapping; import org.springframework.web.bind.annotation.RestController; @RestController public class WebConfigurerTestController { @GetMapping("/api/test-cors") public void testCorsOnApiPath() { } @GetMapping("/test/test-cors") public void testCorsOnOtherPath() { } }
java
MIT
4463e58ffb73fe599bac2479abd84598c6e70a1a
2026-01-04T14:45:57.069771Z
false
eugenp/tutorials
https://github.com/eugenp/tutorials/blob/4463e58ffb73fe599bac2479abd84598c6e70a1a/jhipster-modules/jhipster-uaa/gateway/src/test/java/com/baeldung/jhipster/gateway/web/rest/TestUtil.java
jhipster-modules/jhipster-uaa/gateway/src/test/java/com/baeldung/jhipster/gateway/web/rest/TestUtil.java
package com.baeldung.jhipster.gateway.web.rest; import com.fasterxml.jackson.annotation.JsonInclude; import com.fasterxml.jackson.databind.ObjectMapper; import com.fasterxml.jackson.datatype.jsr310.JavaTimeModule; import org.hamcrest.Description; import org.hamcrest.TypeSafeDiagnosingMatcher; import org.springframework.format.datetime.standard.DateTimeFormatterRegistrar; import org.springframework.format.support.DefaultFormattingConversionService; import org.springframework.format.support.FormattingConversionService; import org.springframework.http.MediaType; import java.io.IOException; import java.nio.charset.StandardCharsets; import java.time.ZonedDateTime; import java.time.format.DateTimeParseException; import static org.assertj.core.api.Assertions.assertThat; /** * Utility class for testing REST controllers. */ public class TestUtil { /** MediaType for JSON UTF8 */ public static final MediaType APPLICATION_JSON_UTF8 = new MediaType( MediaType.APPLICATION_JSON.getType(), MediaType.APPLICATION_JSON.getSubtype(), StandardCharsets.UTF_8); /** * Convert an object to JSON byte array. * * @param object * the object to convert * @return the JSON byte array * @throws IOException */ public static byte[] convertObjectToJsonBytes(Object object) throws IOException { ObjectMapper mapper = new ObjectMapper(); mapper.setSerializationInclusion(JsonInclude.Include.NON_EMPTY); JavaTimeModule module = new JavaTimeModule(); mapper.registerModule(module); return mapper.writeValueAsBytes(object); } /** * Create a byte array with a specific size filled with specified data. * * @param size the size of the byte array * @param data the data to put in the byte array * @return the JSON byte array */ public static byte[] createByteArray(int size, String data) { byte[] byteArray = new byte[size]; for (int i = 0; i < size; i++) { byteArray[i] = Byte.parseByte(data, 2); } return byteArray; } /** * A matcher that tests that the examined string represents the same instant as the reference datetime. */ public static class ZonedDateTimeMatcher extends TypeSafeDiagnosingMatcher<String> { private final ZonedDateTime date; public ZonedDateTimeMatcher(ZonedDateTime date) { this.date = date; } @Override protected boolean matchesSafely(String item, Description mismatchDescription) { try { if (!date.isEqual(ZonedDateTime.parse(item))) { mismatchDescription.appendText("was ").appendValue(item); return false; } return true; } catch (DateTimeParseException e) { mismatchDescription.appendText("was ").appendValue(item) .appendText(", which could not be parsed as a ZonedDateTime"); return false; } } @Override public void describeTo(Description description) { description.appendText("a String representing the same Instant as ").appendValue(date); } } /** * Creates a matcher that matches when the examined string reprensents the same instant as the reference datetime * @param date the reference datetime against which the examined string is checked */ public static ZonedDateTimeMatcher sameInstant(ZonedDateTime date) { return new ZonedDateTimeMatcher(date); } /** * Verifies the equals/hashcode contract on the domain object. */ public static <T> void equalsVerifier(Class<T> clazz) throws Exception { T domainObject1 = clazz.getConstructor().newInstance(); assertThat(domainObject1.toString()).isNotNull(); assertThat(domainObject1).isEqualTo(domainObject1); assertThat(domainObject1.hashCode()).isEqualTo(domainObject1.hashCode()); // Test with an instance of another class Object testOtherObject = new Object(); assertThat(domainObject1).isNotEqualTo(testOtherObject); assertThat(domainObject1).isNotEqualTo(null); // Test with an instance of the same class T domainObject2 = clazz.getConstructor().newInstance(); assertThat(domainObject1).isNotEqualTo(domainObject2); // HashCodes are equals because the objects are not persisted yet assertThat(domainObject1.hashCode()).isEqualTo(domainObject2.hashCode()); } /** * Create a FormattingConversionService which use ISO date format, instead of the localized one. * @return the FormattingConversionService */ public static FormattingConversionService createFormattingConversionService() { DefaultFormattingConversionService dfcs = new DefaultFormattingConversionService (); DateTimeFormatterRegistrar registrar = new DateTimeFormatterRegistrar(); registrar.setUseIsoFormat(true); registrar.registerFormatters(dfcs); return dfcs; } }
java
MIT
4463e58ffb73fe599bac2479abd84598c6e70a1a
2026-01-04T14:45:57.069771Z
false
eugenp/tutorials
https://github.com/eugenp/tutorials/blob/4463e58ffb73fe599bac2479abd84598c6e70a1a/jhipster-modules/jhipster-uaa/gateway/src/test/java/com/baeldung/jhipster/gateway/web/rest/LogsResourceIntTest.java
jhipster-modules/jhipster-uaa/gateway/src/test/java/com/baeldung/jhipster/gateway/web/rest/LogsResourceIntTest.java
package com.baeldung.jhipster.gateway.web.rest; import com.baeldung.jhipster.gateway.GatewayApp; import com.baeldung.jhipster.gateway.config.SecurityBeanOverrideConfiguration; import com.baeldung.jhipster.gateway.web.rest.vm.LoggerVM; import ch.qos.logback.classic.AsyncAppender; import ch.qos.logback.classic.LoggerContext; import org.junit.Before; import org.junit.Test; import org.junit.runner.RunWith; import org.slf4j.LoggerFactory; import org.springframework.boot.test.context.SpringBootTest; import org.springframework.http.MediaType; import org.springframework.test.context.junit4.SpringRunner; import org.springframework.test.web.servlet.MockMvc; import org.springframework.test.web.servlet.setup.MockMvcBuilders; import static org.assertj.core.api.Assertions.assertThat; import static org.springframework.test.web.servlet.request.MockMvcRequestBuilders.get; import static org.springframework.test.web.servlet.request.MockMvcRequestBuilders.put; import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.content; import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.status; /** * Test class for the LogsResource REST controller. * * @see LogsResource */ @RunWith(SpringRunner.class) @SpringBootTest(classes = {SecurityBeanOverrideConfiguration.class, GatewayApp.class}) public class LogsResourceIntTest { private MockMvc restLogsMockMvc; @Before public void setup() { LogsResource logsResource = new LogsResource(); this.restLogsMockMvc = MockMvcBuilders .standaloneSetup(logsResource) .build(); } @Test public void getAllLogs() throws Exception { restLogsMockMvc.perform(get("/management/logs")) .andExpect(status().isOk()) .andExpect(content().contentType(MediaType.APPLICATION_JSON_UTF8_VALUE)); } @Test public void changeLogs() throws Exception { LoggerVM logger = new LoggerVM(); logger.setLevel("INFO"); logger.setName("some.test.logger"); restLogsMockMvc.perform(put("/management/logs") .contentType(TestUtil.APPLICATION_JSON_UTF8) .content(TestUtil.convertObjectToJsonBytes(logger))) .andExpect(status().isNoContent()); } @Test public void testLogstashAppender() { LoggerContext context = (LoggerContext) LoggerFactory.getILoggerFactory(); assertThat(context.getLogger("ROOT").getAppender("ASYNC_LOGSTASH")).isInstanceOf(AsyncAppender.class); } }
java
MIT
4463e58ffb73fe599bac2479abd84598c6e70a1a
2026-01-04T14:45:57.069771Z
false
eugenp/tutorials
https://github.com/eugenp/tutorials/blob/4463e58ffb73fe599bac2479abd84598c6e70a1a/jhipster-modules/jhipster-uaa/gateway/src/test/java/com/baeldung/jhipster/gateway/web/rest/util/PaginationUtilUnitTest.java
jhipster-modules/jhipster-uaa/gateway/src/test/java/com/baeldung/jhipster/gateway/web/rest/util/PaginationUtilUnitTest.java
package com.baeldung.jhipster.gateway.web.rest.util; import static org.junit.Assert.assertEquals; import static org.junit.Assert.assertNotNull; import static org.junit.Assert.assertTrue; import java.util.ArrayList; import java.util.List; import org.junit.Test; import org.springframework.data.domain.Page; import org.springframework.data.domain.PageImpl; import org.springframework.data.domain.PageRequest; import org.springframework.http.HttpHeaders; /** * Tests based on parsing algorithm in app/components/util/pagination-util.service.js * * @see PaginationUtil */ public class PaginationUtilUnitTest { @Test public void generatePaginationHttpHeadersTest() { String baseUrl = "/api/_search/example"; List<String> content = new ArrayList<>(); Page<String> page = new PageImpl<>(content, PageRequest.of(6, 50), 400L); HttpHeaders headers = PaginationUtil.generatePaginationHttpHeaders(page, baseUrl); List<String> strHeaders = headers.get(HttpHeaders.LINK); assertNotNull(strHeaders); assertTrue(strHeaders.size() == 1); String headerData = strHeaders.get(0); assertTrue(headerData.split(",").length == 4); String expectedData = "</api/_search/example?page=7&size=50>; rel=\"next\"," + "</api/_search/example?page=5&size=50>; rel=\"prev\"," + "</api/_search/example?page=7&size=50>; rel=\"last\"," + "</api/_search/example?page=0&size=50>; rel=\"first\""; assertEquals(expectedData, headerData); List<String> xTotalCountHeaders = headers.get("X-Total-Count"); assertTrue(xTotalCountHeaders.size() == 1); assertTrue(Long.valueOf(xTotalCountHeaders.get(0)).equals(400L)); } }
java
MIT
4463e58ffb73fe599bac2479abd84598c6e70a1a
2026-01-04T14:45:57.069771Z
false
eugenp/tutorials
https://github.com/eugenp/tutorials/blob/4463e58ffb73fe599bac2479abd84598c6e70a1a/jhipster-modules/jhipster-uaa/gateway/src/test/java/com/baeldung/jhipster/gateway/web/rest/errors/ExceptionTranslatorTestController.java
jhipster-modules/jhipster-uaa/gateway/src/test/java/com/baeldung/jhipster/gateway/web/rest/errors/ExceptionTranslatorTestController.java
package com.baeldung.jhipster.gateway.web.rest.errors; import org.springframework.dao.ConcurrencyFailureException; import org.springframework.http.HttpStatus; import org.springframework.security.access.AccessDeniedException; import org.springframework.security.authentication.BadCredentialsException; import org.springframework.web.bind.annotation.*; import javax.validation.Valid; import javax.validation.constraints.NotNull; import java.util.HashMap; import java.util.Map; @RestController public class ExceptionTranslatorTestController { @GetMapping("/test/concurrency-failure") public void concurrencyFailure() { throw new ConcurrencyFailureException("test concurrency failure"); } @PostMapping("/test/method-argument") public void methodArgument(@Valid @RequestBody TestDTO testDTO) { } @GetMapping("/test/parameterized-error") public void parameterizedError() { throw new CustomParameterizedException("test parameterized error", "param0_value", "param1_value"); } @GetMapping("/test/parameterized-error2") public void parameterizedError2() { Map<String, Object> params = new HashMap<>(); params.put("foo", "foo_value"); params.put("bar", "bar_value"); throw new CustomParameterizedException("test parameterized error", params); } @GetMapping("/test/missing-servlet-request-part") public void missingServletRequestPartException(@RequestPart String part) { } @GetMapping("/test/missing-servlet-request-parameter") public void missingServletRequestParameterException(@RequestParam String param) { } @GetMapping("/test/access-denied") public void accessdenied() { throw new AccessDeniedException("test access denied!"); } @GetMapping("/test/unauthorized") public void unauthorized() { throw new BadCredentialsException("test authentication failed!"); } @GetMapping("/test/response-status") public void exceptionWithReponseStatus() { throw new TestResponseStatusException(); } @GetMapping("/test/internal-server-error") public void internalServerError() { throw new RuntimeException(); } public static class TestDTO { @NotNull private String test; public String getTest() { return test; } public void setTest(String test) { this.test = test; } } @ResponseStatus(value = HttpStatus.BAD_REQUEST, reason = "test response status") @SuppressWarnings("serial") public static class TestResponseStatusException extends RuntimeException { } }
java
MIT
4463e58ffb73fe599bac2479abd84598c6e70a1a
2026-01-04T14:45:57.069771Z
false
eugenp/tutorials
https://github.com/eugenp/tutorials/blob/4463e58ffb73fe599bac2479abd84598c6e70a1a/jhipster-modules/jhipster-uaa/gateway/src/test/java/com/baeldung/jhipster/gateway/web/rest/errors/ExceptionTranslatorIntTest.java
jhipster-modules/jhipster-uaa/gateway/src/test/java/com/baeldung/jhipster/gateway/web/rest/errors/ExceptionTranslatorIntTest.java
package com.baeldung.jhipster.gateway.web.rest.errors; import com.baeldung.jhipster.gateway.GatewayApp; import com.baeldung.jhipster.gateway.config.SecurityBeanOverrideConfiguration; import org.junit.Before; import org.junit.Test; import org.junit.runner.RunWith; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.boot.test.context.SpringBootTest; import org.springframework.http.MediaType; import org.springframework.http.converter.json.MappingJackson2HttpMessageConverter; import org.springframework.test.context.junit4.SpringRunner; import org.springframework.test.web.servlet.MockMvc; import org.springframework.test.web.servlet.setup.MockMvcBuilders; import static org.springframework.test.web.servlet.request.MockMvcRequestBuilders.get; import static org.springframework.test.web.servlet.request.MockMvcRequestBuilders.post; import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.content; import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.jsonPath; import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.status; /** * Test class for the ExceptionTranslator controller advice. * * @see ExceptionTranslator */ @RunWith(SpringRunner.class) @SpringBootTest(classes = {SecurityBeanOverrideConfiguration.class, GatewayApp.class}) public class ExceptionTranslatorIntTest { @Autowired private ExceptionTranslatorTestController controller; @Autowired private ExceptionTranslator exceptionTranslator; @Autowired private MappingJackson2HttpMessageConverter jacksonMessageConverter; private MockMvc mockMvc; @Before public void setup() { mockMvc = MockMvcBuilders.standaloneSetup(controller) .setControllerAdvice(exceptionTranslator) .setMessageConverters(jacksonMessageConverter) .build(); } @Test public void testConcurrencyFailure() throws Exception { mockMvc.perform(get("/test/concurrency-failure")) .andExpect(status().isConflict()) .andExpect(content().contentType(MediaType.APPLICATION_PROBLEM_JSON)) .andExpect(jsonPath("$.message").value(ErrorConstants.ERR_CONCURRENCY_FAILURE)); } @Test public void testMethodArgumentNotValid() throws Exception { mockMvc.perform(post("/test/method-argument").content("{}").contentType(MediaType.APPLICATION_JSON)) .andExpect(status().isBadRequest()) .andExpect(content().contentType(MediaType.APPLICATION_PROBLEM_JSON)) .andExpect(jsonPath("$.message").value(ErrorConstants.ERR_VALIDATION)) .andExpect(jsonPath("$.fieldErrors.[0].objectName").value("testDTO")) .andExpect(jsonPath("$.fieldErrors.[0].field").value("test")) .andExpect(jsonPath("$.fieldErrors.[0].message").value("NotNull")); } @Test public void testParameterizedError() throws Exception { mockMvc.perform(get("/test/parameterized-error")) .andExpect(status().isBadRequest()) .andExpect(content().contentType(MediaType.APPLICATION_PROBLEM_JSON)) .andExpect(jsonPath("$.message").value("test parameterized error")) .andExpect(jsonPath("$.params.param0").value("param0_value")) .andExpect(jsonPath("$.params.param1").value("param1_value")); } @Test public void testParameterizedError2() throws Exception { mockMvc.perform(get("/test/parameterized-error2")) .andExpect(status().isBadRequest()) .andExpect(content().contentType(MediaType.APPLICATION_PROBLEM_JSON)) .andExpect(jsonPath("$.message").value("test parameterized error")) .andExpect(jsonPath("$.params.foo").value("foo_value")) .andExpect(jsonPath("$.params.bar").value("bar_value")); } @Test public void testMissingServletRequestPartException() throws Exception { mockMvc.perform(get("/test/missing-servlet-request-part")) .andExpect(status().isBadRequest()) .andExpect(content().contentType(MediaType.APPLICATION_PROBLEM_JSON)) .andExpect(jsonPath("$.message").value("error.http.400")); } @Test public void testMissingServletRequestParameterException() throws Exception { mockMvc.perform(get("/test/missing-servlet-request-parameter")) .andExpect(status().isBadRequest()) .andExpect(content().contentType(MediaType.APPLICATION_PROBLEM_JSON)) .andExpect(jsonPath("$.message").value("error.http.400")); } @Test public void testAccessDenied() throws Exception { mockMvc.perform(get("/test/access-denied")) .andExpect(status().isForbidden()) .andExpect(content().contentType(MediaType.APPLICATION_PROBLEM_JSON)) .andExpect(jsonPath("$.message").value("error.http.403")) .andExpect(jsonPath("$.detail").value("test access denied!")); } @Test public void testUnauthorized() throws Exception { mockMvc.perform(get("/test/unauthorized")) .andExpect(status().isUnauthorized()) .andExpect(content().contentType(MediaType.APPLICATION_PROBLEM_JSON)) .andExpect(jsonPath("$.message").value("error.http.401")) .andExpect(jsonPath("$.path").value("/test/unauthorized")) .andExpect(jsonPath("$.detail").value("test authentication failed!")); } @Test public void testMethodNotSupported() throws Exception { mockMvc.perform(post("/test/access-denied")) .andExpect(status().isMethodNotAllowed()) .andExpect(content().contentType(MediaType.APPLICATION_PROBLEM_JSON)) .andExpect(jsonPath("$.message").value("error.http.405")) .andExpect(jsonPath("$.detail").value("Request method 'POST' not supported")); } @Test public void testExceptionWithResponseStatus() throws Exception { mockMvc.perform(get("/test/response-status")) .andExpect(status().isBadRequest()) .andExpect(content().contentType(MediaType.APPLICATION_PROBLEM_JSON)) .andExpect(jsonPath("$.message").value("error.http.400")) .andExpect(jsonPath("$.title").value("test response status")); } @Test public void testInternalServerError() throws Exception { mockMvc.perform(get("/test/internal-server-error")) .andExpect(status().isInternalServerError()) .andExpect(content().contentType(MediaType.APPLICATION_PROBLEM_JSON)) .andExpect(jsonPath("$.message").value("error.http.500")) .andExpect(jsonPath("$.title").value("Internal Server Error")); } }
java
MIT
4463e58ffb73fe599bac2479abd84598c6e70a1a
2026-01-04T14:45:57.069771Z
false
eugenp/tutorials
https://github.com/eugenp/tutorials/blob/4463e58ffb73fe599bac2479abd84598c6e70a1a/jhipster-modules/jhipster-uaa/gateway/src/main/java/com/baeldung/jhipster/gateway/GatewayApp.java
jhipster-modules/jhipster-uaa/gateway/src/main/java/com/baeldung/jhipster/gateway/GatewayApp.java
package com.baeldung.jhipster.gateway; import com.baeldung.jhipster.gateway.config.ApplicationProperties; import com.baeldung.jhipster.gateway.config.DefaultProfileUtil; import io.github.jhipster.config.JHipsterConstants; import org.apache.commons.lang3.StringUtils; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import org.springframework.boot.SpringApplication; import org.springframework.boot.autoconfigure.SpringBootApplication; import org.springframework.boot.autoconfigure.liquibase.LiquibaseProperties; import org.springframework.boot.context.properties.EnableConfigurationProperties; import org.springframework.cloud.client.discovery.EnableDiscoveryClient; import org.springframework.cloud.netflix.zuul.EnableZuulProxy; import org.springframework.core.env.Environment; import javax.annotation.PostConstruct; import java.net.InetAddress; import java.net.UnknownHostException; import java.util.Arrays; import java.util.Collection; @SpringBootApplication @EnableConfigurationProperties({LiquibaseProperties.class, ApplicationProperties.class}) @EnableDiscoveryClient @EnableZuulProxy public class GatewayApp { private static final Logger log = LoggerFactory.getLogger(GatewayApp.class); private final Environment env; public GatewayApp(Environment env) { this.env = env; } /** * Initializes gateway. * <p> * Spring profiles can be configured with a program argument --spring.profiles.active=your-active-profile * <p> * You can find more information on how profiles work with JHipster on <a href="https://www.jhipster.tech/profiles/">https://www.jhipster.tech/profiles/</a>. */ @PostConstruct public void initApplication() { Collection<String> activeProfiles = Arrays.asList(env.getActiveProfiles()); if (activeProfiles.contains(JHipsterConstants.SPRING_PROFILE_DEVELOPMENT) && activeProfiles.contains(JHipsterConstants.SPRING_PROFILE_PRODUCTION)) { log.error("You have misconfigured your application! It should not run " + "with both the 'dev' and 'prod' profiles at the same time."); } if (activeProfiles.contains(JHipsterConstants.SPRING_PROFILE_DEVELOPMENT) && activeProfiles.contains(JHipsterConstants.SPRING_PROFILE_CLOUD)) { log.error("You have misconfigured your application! It should not " + "run with both the 'dev' and 'cloud' profiles at the same time."); } } /** * Main method, used to run the application. * * @param args the command line arguments */ public static void main(String[] args) { SpringApplication app = new SpringApplication(GatewayApp.class); DefaultProfileUtil.addDefaultProfile(app); Environment env = app.run(args).getEnvironment(); logApplicationStartup(env); } private static void logApplicationStartup(Environment env) { String protocol = "http"; if (env.getProperty("server.ssl.key-store") != null) { protocol = "https"; } String serverPort = env.getProperty("server.port"); String contextPath = env.getProperty("server.servlet.context-path"); if (StringUtils.isBlank(contextPath)) { contextPath = "/"; } String hostAddress = "localhost"; try { hostAddress = InetAddress.getLocalHost().getHostAddress(); } catch (UnknownHostException e) { log.warn("The host name could not be determined, using `localhost` as fallback"); } log.info("\n----------------------------------------------------------\n\t" + "Application '{}' is running! Access URLs:\n\t" + "Local: \t\t{}://localhost:{}{}\n\t" + "External: \t{}://{}:{}{}\n\t" + "Profile(s): \t{}\n----------------------------------------------------------", env.getProperty("spring.application.name"), protocol, serverPort, contextPath, protocol, hostAddress, serverPort, contextPath, env.getActiveProfiles()); String configServerStatus = env.getProperty("configserver.status"); if (configServerStatus == null) { configServerStatus = "Not found or not setup for this application"; } log.info("\n----------------------------------------------------------\n\t" + "Config Server: \t{}\n----------------------------------------------------------", configServerStatus); } }
java
MIT
4463e58ffb73fe599bac2479abd84598c6e70a1a
2026-01-04T14:45:57.069771Z
false
eugenp/tutorials
https://github.com/eugenp/tutorials/blob/4463e58ffb73fe599bac2479abd84598c6e70a1a/jhipster-modules/jhipster-uaa/gateway/src/main/java/com/baeldung/jhipster/gateway/ApplicationWebXml.java
jhipster-modules/jhipster-uaa/gateway/src/main/java/com/baeldung/jhipster/gateway/ApplicationWebXml.java
package com.baeldung.jhipster.gateway; import com.baeldung.jhipster.gateway.config.DefaultProfileUtil; import org.springframework.boot.builder.SpringApplicationBuilder; import org.springframework.boot.web.servlet.support.SpringBootServletInitializer; /** * This is a helper Java class that provides an alternative to creating a web.xml. * This will be invoked only when the application is deployed to a Servlet container like Tomcat, JBoss etc. */ public class ApplicationWebXml extends SpringBootServletInitializer { @Override protected SpringApplicationBuilder configure(SpringApplicationBuilder application) { /** * set a default to use when no profile is configured. */ DefaultProfileUtil.addDefaultProfile(application.application()); return application.sources(GatewayApp.class); } }
java
MIT
4463e58ffb73fe599bac2479abd84598c6e70a1a
2026-01-04T14:45:57.069771Z
false
eugenp/tutorials
https://github.com/eugenp/tutorials/blob/4463e58ffb73fe599bac2479abd84598c6e70a1a/jhipster-modules/jhipster-uaa/gateway/src/main/java/com/baeldung/jhipster/gateway/service/package-info.java
jhipster-modules/jhipster-uaa/gateway/src/main/java/com/baeldung/jhipster/gateway/service/package-info.java
/** * Service layer beans. */ package com.baeldung.jhipster.gateway.service;
java
MIT
4463e58ffb73fe599bac2479abd84598c6e70a1a
2026-01-04T14:45:57.069771Z
false
eugenp/tutorials
https://github.com/eugenp/tutorials/blob/4463e58ffb73fe599bac2479abd84598c6e70a1a/jhipster-modules/jhipster-uaa/gateway/src/main/java/com/baeldung/jhipster/gateway/aop/logging/LoggingAspect.java
jhipster-modules/jhipster-uaa/gateway/src/main/java/com/baeldung/jhipster/gateway/aop/logging/LoggingAspect.java
package com.baeldung.jhipster.gateway.aop.logging; import io.github.jhipster.config.JHipsterConstants; import org.aspectj.lang.JoinPoint; import org.aspectj.lang.ProceedingJoinPoint; import org.aspectj.lang.annotation.AfterThrowing; import org.aspectj.lang.annotation.Around; import org.aspectj.lang.annotation.Aspect; import org.aspectj.lang.annotation.Pointcut; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import org.springframework.core.env.Environment; import java.util.Arrays; /** * Aspect for logging execution of service and repository Spring components. * * By default, it only runs with the "dev" profile. */ @Aspect public class LoggingAspect { private final Logger log = LoggerFactory.getLogger(this.getClass()); private final Environment env; public LoggingAspect(Environment env) { this.env = env; } /** * Pointcut that matches all repositories, services and Web REST endpoints. */ @Pointcut("within(@org.springframework.stereotype.Repository *)" + " || within(@org.springframework.stereotype.Service *)" + " || within(@org.springframework.web.bind.annotation.RestController *)") public void springBeanPointcut() { // Method is empty as this is just a Pointcut, the implementations are in the advices. } /** * Pointcut that matches all Spring beans in the application's main packages. */ @Pointcut("within(com.baeldung.jhipster.gateway.repository..*)"+ " || within(com.baeldung.jhipster.gateway.service..*)"+ " || within(com.baeldung.jhipster.gateway.web.rest..*)") public void applicationPackagePointcut() { // Method is empty as this is just a Pointcut, the implementations are in the advices. } /** * Advice that logs methods throwing exceptions. * * @param joinPoint join point for advice * @param e exception */ @AfterThrowing(pointcut = "applicationPackagePointcut() && springBeanPointcut()", throwing = "e") public void logAfterThrowing(JoinPoint joinPoint, Throwable e) { if (env.acceptsProfiles(JHipsterConstants.SPRING_PROFILE_DEVELOPMENT)) { log.error("Exception in {}.{}() with cause = \'{}\' and exception = \'{}\'", joinPoint.getSignature().getDeclaringTypeName(), joinPoint.getSignature().getName(), e.getCause() != null? e.getCause() : "NULL", e.getMessage(), e); } else { log.error("Exception in {}.{}() with cause = {}", joinPoint.getSignature().getDeclaringTypeName(), joinPoint.getSignature().getName(), e.getCause() != null? e.getCause() : "NULL"); } } /** * Advice that logs when a method is entered and exited. * * @param joinPoint join point for advice * @return result * @throws Throwable throws IllegalArgumentException */ @Around("applicationPackagePointcut() && springBeanPointcut()") public Object logAround(ProceedingJoinPoint joinPoint) throws Throwable { if (log.isDebugEnabled()) { log.debug("Enter: {}.{}() with argument[s] = {}", joinPoint.getSignature().getDeclaringTypeName(), joinPoint.getSignature().getName(), Arrays.toString(joinPoint.getArgs())); } try { Object result = joinPoint.proceed(); if (log.isDebugEnabled()) { log.debug("Exit: {}.{}() with result = {}", joinPoint.getSignature().getDeclaringTypeName(), joinPoint.getSignature().getName(), result); } return result; } catch (IllegalArgumentException e) { log.error("Illegal argument: {} in {}.{}()", Arrays.toString(joinPoint.getArgs()), joinPoint.getSignature().getDeclaringTypeName(), joinPoint.getSignature().getName()); throw e; } } }
java
MIT
4463e58ffb73fe599bac2479abd84598c6e70a1a
2026-01-04T14:45:57.069771Z
false
eugenp/tutorials
https://github.com/eugenp/tutorials/blob/4463e58ffb73fe599bac2479abd84598c6e70a1a/jhipster-modules/jhipster-uaa/gateway/src/main/java/com/baeldung/jhipster/gateway/domain/package-info.java
jhipster-modules/jhipster-uaa/gateway/src/main/java/com/baeldung/jhipster/gateway/domain/package-info.java
/** * JPA domain objects. */ package com.baeldung.jhipster.gateway.domain;
java
MIT
4463e58ffb73fe599bac2479abd84598c6e70a1a
2026-01-04T14:45:57.069771Z
false
eugenp/tutorials
https://github.com/eugenp/tutorials/blob/4463e58ffb73fe599bac2479abd84598c6e70a1a/jhipster-modules/jhipster-uaa/gateway/src/main/java/com/baeldung/jhipster/gateway/domain/PersistentAuditEvent.java
jhipster-modules/jhipster-uaa/gateway/src/main/java/com/baeldung/jhipster/gateway/domain/PersistentAuditEvent.java
package com.baeldung.jhipster.gateway.domain; import javax.persistence.*; import javax.validation.constraints.NotNull; import java.io.Serializable; import java.time.Instant; import java.util.HashMap; import java.util.Map; /** * Persist AuditEvent managed by the Spring Boot actuator. * * @see org.springframework.boot.actuate.audit.AuditEvent */ @Entity @Table(name = "jhi_persistent_audit_event") public class PersistentAuditEvent implements Serializable { private static final long serialVersionUID = 1L; @Id @GeneratedValue(strategy = GenerationType.IDENTITY) @Column(name = "event_id") private Long id; @NotNull @Column(nullable = false) private String principal; @Column(name = "event_date") private Instant auditEventDate; @Column(name = "event_type") private String auditEventType; @ElementCollection @MapKeyColumn(name = "name") @Column(name = "value") @CollectionTable(name = "jhi_persistent_audit_evt_data", joinColumns=@JoinColumn(name="event_id")) private Map<String, String> data = new HashMap<>(); public Long getId() { return id; } public void setId(Long id) { this.id = id; } public String getPrincipal() { return principal; } public void setPrincipal(String principal) { this.principal = principal; } public Instant getAuditEventDate() { return auditEventDate; } public void setAuditEventDate(Instant auditEventDate) { this.auditEventDate = auditEventDate; } public String getAuditEventType() { return auditEventType; } public void setAuditEventType(String auditEventType) { this.auditEventType = auditEventType; } public Map<String, String> getData() { return data; } public void setData(Map<String, String> data) { this.data = data; } }
java
MIT
4463e58ffb73fe599bac2479abd84598c6e70a1a
2026-01-04T14:45:57.069771Z
false
eugenp/tutorials
https://github.com/eugenp/tutorials/blob/4463e58ffb73fe599bac2479abd84598c6e70a1a/jhipster-modules/jhipster-uaa/gateway/src/main/java/com/baeldung/jhipster/gateway/domain/AbstractAuditingEntity.java
jhipster-modules/jhipster-uaa/gateway/src/main/java/com/baeldung/jhipster/gateway/domain/AbstractAuditingEntity.java
package com.baeldung.jhipster.gateway.domain; import com.fasterxml.jackson.annotation.JsonIgnore; import org.hibernate.envers.Audited; import org.springframework.data.annotation.CreatedBy; import org.springframework.data.annotation.CreatedDate; import org.springframework.data.annotation.LastModifiedBy; import org.springframework.data.annotation.LastModifiedDate; import org.springframework.data.jpa.domain.support.AuditingEntityListener; import java.io.Serializable; import java.time.Instant; import javax.persistence.Column; import javax.persistence.EntityListeners; import javax.persistence.MappedSuperclass; /** * Base abstract class for entities which will hold definitions for created, last modified by and created, * last modified by date. */ @MappedSuperclass @Audited @EntityListeners(AuditingEntityListener.class) public abstract class AbstractAuditingEntity implements Serializable { private static final long serialVersionUID = 1L; @CreatedBy @Column(name = "created_by", nullable = false, length = 50, updatable = false) @JsonIgnore private String createdBy; @CreatedDate @Column(name = "created_date", nullable = false, updatable = false) @JsonIgnore private Instant createdDate = Instant.now(); @LastModifiedBy @Column(name = "last_modified_by", length = 50) @JsonIgnore private String lastModifiedBy; @LastModifiedDate @Column(name = "last_modified_date") @JsonIgnore private Instant lastModifiedDate = Instant.now(); public String getCreatedBy() { return createdBy; } public void setCreatedBy(String createdBy) { this.createdBy = createdBy; } public Instant getCreatedDate() { return createdDate; } public void setCreatedDate(Instant createdDate) { this.createdDate = createdDate; } public String getLastModifiedBy() { return lastModifiedBy; } public void setLastModifiedBy(String lastModifiedBy) { this.lastModifiedBy = lastModifiedBy; } public Instant getLastModifiedDate() { return lastModifiedDate; } public void setLastModifiedDate(Instant lastModifiedDate) { this.lastModifiedDate = lastModifiedDate; } }
java
MIT
4463e58ffb73fe599bac2479abd84598c6e70a1a
2026-01-04T14:45:57.069771Z
false
eugenp/tutorials
https://github.com/eugenp/tutorials/blob/4463e58ffb73fe599bac2479abd84598c6e70a1a/jhipster-modules/jhipster-uaa/gateway/src/main/java/com/baeldung/jhipster/gateway/gateway/responserewriting/SwaggerBasePathRewritingFilter.java
jhipster-modules/jhipster-uaa/gateway/src/main/java/com/baeldung/jhipster/gateway/gateway/responserewriting/SwaggerBasePathRewritingFilter.java
package com.baeldung.jhipster.gateway.gateway.responserewriting; import com.fasterxml.jackson.databind.ObjectMapper; import com.netflix.zuul.context.RequestContext; import org.apache.commons.io.IOUtils; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import org.springframework.cloud.netflix.zuul.filters.ZuulProperties; import org.springframework.cloud.netflix.zuul.filters.post.SendResponseFilter; import springfox.documentation.swagger2.web.Swagger2Controller; import java.io.*; import java.nio.charset.StandardCharsets; import java.util.LinkedHashMap; import java.util.zip.GZIPInputStream; import java.util.zip.GZIPOutputStream; /** * Zuul filter to rewrite micro-services Swagger URL Base Path. */ public class SwaggerBasePathRewritingFilter extends SendResponseFilter { private final Logger log = LoggerFactory.getLogger(SwaggerBasePathRewritingFilter.class); private ObjectMapper mapper = new ObjectMapper(); public SwaggerBasePathRewritingFilter() { super(new ZuulProperties()); } @Override public String filterType() { return "post"; } @Override public int filterOrder() { return 100; } /** * Filter requests to micro-services Swagger docs. */ @Override public boolean shouldFilter() { return RequestContext.getCurrentContext().getRequest().getRequestURI().endsWith(Swagger2Controller.DEFAULT_URL); } @Override public Object run() { RequestContext context = RequestContext.getCurrentContext(); context.getResponse().setCharacterEncoding("UTF-8"); String rewrittenResponse = rewriteBasePath(context); if (context.getResponseGZipped()) { try { context.setResponseDataStream(new ByteArrayInputStream(gzipData(rewrittenResponse))); } catch (IOException e) { log.error("Swagger-docs filter error", e); } } else { context.setResponseBody(rewrittenResponse); } return null; } @SuppressWarnings("unchecked") private String rewriteBasePath(RequestContext context) { InputStream responseDataStream = context.getResponseDataStream(); String requestUri = RequestContext.getCurrentContext().getRequest().getRequestURI(); try { if (context.getResponseGZipped()) { responseDataStream = new GZIPInputStream(context.getResponseDataStream()); } String response = IOUtils.toString(responseDataStream, StandardCharsets.UTF_8); if (response != null) { LinkedHashMap<String, Object> map = this.mapper.readValue(response, LinkedHashMap.class); String basePath = requestUri.replace(Swagger2Controller.DEFAULT_URL, ""); map.put("basePath", basePath); log.debug("Swagger-docs: rewritten Base URL with correct micro-service route: {}", basePath); return mapper.writeValueAsString(map); } } catch (IOException e) { log.error("Swagger-docs filter error", e); } return null; } public static byte[] gzipData(String content) throws IOException { ByteArrayOutputStream bos = new ByteArrayOutputStream(); PrintWriter gzip = new PrintWriter(new GZIPOutputStream(bos)); gzip.print(content); gzip.flush(); gzip.close(); return bos.toByteArray(); } }
java
MIT
4463e58ffb73fe599bac2479abd84598c6e70a1a
2026-01-04T14:45:57.069771Z
false
eugenp/tutorials
https://github.com/eugenp/tutorials/blob/4463e58ffb73fe599bac2479abd84598c6e70a1a/jhipster-modules/jhipster-uaa/gateway/src/main/java/com/baeldung/jhipster/gateway/gateway/accesscontrol/AccessControlFilter.java
jhipster-modules/jhipster-uaa/gateway/src/main/java/com/baeldung/jhipster/gateway/gateway/accesscontrol/AccessControlFilter.java
package com.baeldung.jhipster.gateway.gateway.accesscontrol; import io.github.jhipster.config.JHipsterProperties; import java.util.List; import java.util.Map; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import org.springframework.cloud.netflix.zuul.filters.Route; import org.springframework.cloud.netflix.zuul.filters.RouteLocator; import org.springframework.http.HttpStatus; import com.netflix.zuul.ZuulFilter; import com.netflix.zuul.context.RequestContext; /** * Zuul filter for restricting access to backend micro-services endpoints. */ public class AccessControlFilter extends ZuulFilter { private final Logger log = LoggerFactory.getLogger(AccessControlFilter.class); private final RouteLocator routeLocator; private final JHipsterProperties jHipsterProperties; public AccessControlFilter(RouteLocator routeLocator, JHipsterProperties jHipsterProperties) { this.routeLocator = routeLocator; this.jHipsterProperties = jHipsterProperties; } @Override public String filterType() { return "pre"; } @Override public int filterOrder() { return 0; } /** * Filter requests on endpoints that are not in the list of authorized microservices endpoints. */ @Override public boolean shouldFilter() { String requestUri = RequestContext.getCurrentContext().getRequest().getRequestURI(); String contextPath = RequestContext.getCurrentContext().getRequest().getContextPath(); // If the request Uri does not start with the path of the authorized endpoints, we block the request for (Route route : routeLocator.getRoutes()) { String serviceUrl = contextPath + route.getFullPath(); String serviceName = route.getId(); // If this route correspond to the current request URI // We do a substring to remove the "**" at the end of the route URL if (requestUri.startsWith(serviceUrl.substring(0, serviceUrl.length() - 2))) { return !isAuthorizedRequest(serviceUrl, serviceName, requestUri); } } return true; } private boolean isAuthorizedRequest(String serviceUrl, String serviceName, String requestUri) { Map<String, List<String>> authorizedMicroservicesEndpoints = jHipsterProperties.getGateway() .getAuthorizedMicroservicesEndpoints(); // If the authorized endpoints list was left empty for this route, all access are allowed if (authorizedMicroservicesEndpoints.get(serviceName) == null) { log.debug("Access Control: allowing access for {}, as no access control policy has been set up for " + "service: {}", requestUri, serviceName); return true; } else { List<String> authorizedEndpoints = authorizedMicroservicesEndpoints.get(serviceName); // Go over the authorized endpoints to control that the request URI matches it for (String endpoint : authorizedEndpoints) { // We do a substring to remove the "**/" at the end of the route URL String gatewayEndpoint = serviceUrl.substring(0, serviceUrl.length() - 3) + endpoint; if (requestUri.startsWith(gatewayEndpoint)) { log.debug("Access Control: allowing access for {}, as it matches the following authorized " + "microservice endpoint: {}", requestUri, gatewayEndpoint); return true; } } } return false; } @Override public Object run() { RequestContext ctx = RequestContext.getCurrentContext(); ctx.setResponseStatusCode(HttpStatus.FORBIDDEN.value()); ctx.setSendZuulResponse(false); log.debug("Access Control: filtered unauthorized access on endpoint {}", ctx.getRequest().getRequestURI()); return null; } }
java
MIT
4463e58ffb73fe599bac2479abd84598c6e70a1a
2026-01-04T14:45:57.069771Z
false
eugenp/tutorials
https://github.com/eugenp/tutorials/blob/4463e58ffb73fe599bac2479abd84598c6e70a1a/jhipster-modules/jhipster-uaa/gateway/src/main/java/com/baeldung/jhipster/gateway/gateway/ratelimiting/RateLimitingFilter.java
jhipster-modules/jhipster-uaa/gateway/src/main/java/com/baeldung/jhipster/gateway/gateway/ratelimiting/RateLimitingFilter.java
package com.baeldung.jhipster.gateway.gateway.ratelimiting; import com.baeldung.jhipster.gateway.security.SecurityUtils; import java.time.Duration; import java.util.function.Supplier; import javax.cache.CacheManager; import javax.cache.Caching; import javax.cache.configuration.CompleteConfiguration; import javax.cache.configuration.MutableConfiguration; import javax.cache.spi.CachingProvider; import javax.servlet.http.HttpServletRequest; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import org.springframework.http.HttpStatus; import com.netflix.zuul.ZuulFilter; import com.netflix.zuul.context.RequestContext; import io.github.bucket4j.*; import io.github.bucket4j.grid.GridBucketState; import io.github.bucket4j.grid.ProxyManager; import io.github.bucket4j.grid.jcache.JCache; import io.github.jhipster.config.JHipsterProperties; /** * Zuul filter for limiting the number of HTTP calls per client. * * See the Bucket4j documentation at https://github.com/vladimir-bukhtoyarov/bucket4j * https://github.com/vladimir-bukhtoyarov/bucket4j/blob/master/doc-pages/jcache-usage * .md#example-1---limiting-access-to-http-server-by-ip-address */ public class RateLimitingFilter extends ZuulFilter { private final Logger log = LoggerFactory.getLogger(RateLimitingFilter.class); public final static String GATEWAY_RATE_LIMITING_CACHE_NAME = "gateway-rate-limiting"; private final JHipsterProperties jHipsterProperties; private javax.cache.Cache<String, GridBucketState> cache; private ProxyManager<String> buckets; public RateLimitingFilter(JHipsterProperties jHipsterProperties) { this.jHipsterProperties = jHipsterProperties; CachingProvider cachingProvider = Caching.getCachingProvider(); CacheManager cacheManager = cachingProvider.getCacheManager(); CompleteConfiguration<String, GridBucketState> config = new MutableConfiguration<String, GridBucketState>() .setTypes(String.class, GridBucketState.class); this.cache = cacheManager.createCache(GATEWAY_RATE_LIMITING_CACHE_NAME, config); this.buckets = Bucket4j.extension(JCache.class).proxyManagerForCache(cache); } @Override public String filterType() { return "pre"; } @Override public int filterOrder() { return 10; } @Override public boolean shouldFilter() { // specific APIs can be filtered out using // if (RequestContext.getCurrentContext().getRequest().getRequestURI().startsWith("/api")) { ... } return true; } @Override public Object run() { String bucketId = getId(RequestContext.getCurrentContext().getRequest()); Bucket bucket = buckets.getProxy(bucketId, getConfigSupplier()); if (bucket.tryConsume(1)) { // the limit is not exceeded log.debug("API rate limit OK for {}", bucketId); } else { // limit is exceeded log.info("API rate limit exceeded for {}", bucketId); apiLimitExceeded(); } return null; } private Supplier<BucketConfiguration> getConfigSupplier() { return () -> { JHipsterProperties.Gateway.RateLimiting rateLimitingProperties = jHipsterProperties.getGateway().getRateLimiting(); return Bucket4j.configurationBuilder() .addLimit(Bandwidth.simple(rateLimitingProperties.getLimit(), Duration.ofSeconds(rateLimitingProperties.getDurationInSeconds()))) .build(); }; } /** * Create a Zuul response error when the API limit is exceeded. */ private void apiLimitExceeded() { RequestContext ctx = RequestContext.getCurrentContext(); ctx.setResponseStatusCode(HttpStatus.TOO_MANY_REQUESTS.value()); if (ctx.getResponseBody() == null) { ctx.setResponseBody("API rate limit exceeded"); ctx.setSendZuulResponse(false); } } /** * The ID that will identify the limit: the user login or the user IP address. */ private String getId(HttpServletRequest httpServletRequest) { return SecurityUtils.getCurrentUserLogin().orElse(httpServletRequest.getRemoteAddr()); } }
java
MIT
4463e58ffb73fe599bac2479abd84598c6e70a1a
2026-01-04T14:45:57.069771Z
false
eugenp/tutorials
https://github.com/eugenp/tutorials/blob/4463e58ffb73fe599bac2479abd84598c6e70a1a/jhipster-modules/jhipster-uaa/gateway/src/main/java/com/baeldung/jhipster/gateway/repository/package-info.java
jhipster-modules/jhipster-uaa/gateway/src/main/java/com/baeldung/jhipster/gateway/repository/package-info.java
/** * Spring Data JPA repositories. */ package com.baeldung.jhipster.gateway.repository;
java
MIT
4463e58ffb73fe599bac2479abd84598c6e70a1a
2026-01-04T14:45:57.069771Z
false
eugenp/tutorials
https://github.com/eugenp/tutorials/blob/4463e58ffb73fe599bac2479abd84598c6e70a1a/jhipster-modules/jhipster-uaa/gateway/src/main/java/com/baeldung/jhipster/gateway/security/package-info.java
jhipster-modules/jhipster-uaa/gateway/src/main/java/com/baeldung/jhipster/gateway/security/package-info.java
/** * Spring Security configuration. */ package com.baeldung.jhipster.gateway.security;
java
MIT
4463e58ffb73fe599bac2479abd84598c6e70a1a
2026-01-04T14:45:57.069771Z
false
eugenp/tutorials
https://github.com/eugenp/tutorials/blob/4463e58ffb73fe599bac2479abd84598c6e70a1a/jhipster-modules/jhipster-uaa/gateway/src/main/java/com/baeldung/jhipster/gateway/security/SpringSecurityAuditorAware.java
jhipster-modules/jhipster-uaa/gateway/src/main/java/com/baeldung/jhipster/gateway/security/SpringSecurityAuditorAware.java
package com.baeldung.jhipster.gateway.security; import com.baeldung.jhipster.gateway.config.Constants; import java.util.Optional; import org.springframework.data.domain.AuditorAware; import org.springframework.stereotype.Component; /** * Implementation of AuditorAware based on Spring Security. */ @Component public class SpringSecurityAuditorAware implements AuditorAware<String> { @Override public Optional<String> getCurrentAuditor() { return Optional.of(SecurityUtils.getCurrentUserLogin().orElse(Constants.SYSTEM_ACCOUNT)); } }
java
MIT
4463e58ffb73fe599bac2479abd84598c6e70a1a
2026-01-04T14:45:57.069771Z
false
eugenp/tutorials
https://github.com/eugenp/tutorials/blob/4463e58ffb73fe599bac2479abd84598c6e70a1a/jhipster-modules/jhipster-uaa/gateway/src/main/java/com/baeldung/jhipster/gateway/security/SecurityUtils.java
jhipster-modules/jhipster-uaa/gateway/src/main/java/com/baeldung/jhipster/gateway/security/SecurityUtils.java
package com.baeldung.jhipster.gateway.security; import org.springframework.security.core.context.SecurityContext; import org.springframework.security.core.context.SecurityContextHolder; import org.springframework.security.core.userdetails.UserDetails; import java.util.Optional; /** * Utility class for Spring Security. */ public final class SecurityUtils { private SecurityUtils() { } /** * Get the login of the current user. * * @return the login of the current user */ public static Optional<String> getCurrentUserLogin() { SecurityContext securityContext = SecurityContextHolder.getContext(); return Optional.ofNullable(securityContext.getAuthentication()) .map(authentication -> { if (authentication.getPrincipal() instanceof UserDetails) { UserDetails springSecurityUser = (UserDetails) authentication.getPrincipal(); return springSecurityUser.getUsername(); } else if (authentication.getPrincipal() instanceof String) { return (String) authentication.getPrincipal(); } return null; }); } /** * Check if a user is authenticated. * * @return true if the user is authenticated, false otherwise */ public static boolean isAuthenticated() { SecurityContext securityContext = SecurityContextHolder.getContext(); return Optional.ofNullable(securityContext.getAuthentication()) .map(authentication -> authentication.getAuthorities().stream() .noneMatch(grantedAuthority -> grantedAuthority.getAuthority().equals(AuthoritiesConstants.ANONYMOUS))) .orElse(false); } /** * If the current user has a specific authority (security role). * <p> * The name of this method comes from the isUserInRole() method in the Servlet API * * @param authority the authority to check * @return true if the current user has the authority, false otherwise */ public static boolean isCurrentUserInRole(String authority) { SecurityContext securityContext = SecurityContextHolder.getContext(); return Optional.ofNullable(securityContext.getAuthentication()) .map(authentication -> authentication.getAuthorities().stream() .anyMatch(grantedAuthority -> grantedAuthority.getAuthority().equals(authority))) .orElse(false); } }
java
MIT
4463e58ffb73fe599bac2479abd84598c6e70a1a
2026-01-04T14:45:57.069771Z
false
eugenp/tutorials
https://github.com/eugenp/tutorials/blob/4463e58ffb73fe599bac2479abd84598c6e70a1a/jhipster-modules/jhipster-uaa/gateway/src/main/java/com/baeldung/jhipster/gateway/security/AuthoritiesConstants.java
jhipster-modules/jhipster-uaa/gateway/src/main/java/com/baeldung/jhipster/gateway/security/AuthoritiesConstants.java
package com.baeldung.jhipster.gateway.security; /** * Constants for Spring Security authorities. */ public final class AuthoritiesConstants { public static final String ADMIN = "ROLE_ADMIN"; public static final String USER = "ROLE_USER"; public static final String ANONYMOUS = "ROLE_ANONYMOUS"; private AuthoritiesConstants() { } }
java
MIT
4463e58ffb73fe599bac2479abd84598c6e70a1a
2026-01-04T14:45:57.069771Z
false
eugenp/tutorials
https://github.com/eugenp/tutorials/blob/4463e58ffb73fe599bac2479abd84598c6e70a1a/jhipster-modules/jhipster-uaa/gateway/src/main/java/com/baeldung/jhipster/gateway/security/oauth2/CookieCollection.java
jhipster-modules/jhipster-uaa/gateway/src/main/java/com/baeldung/jhipster/gateway/security/oauth2/CookieCollection.java
package com.baeldung.jhipster.gateway.security.oauth2; import javax.servlet.http.Cookie; import java.util.Arrays; import java.util.Collection; import java.util.HashMap; import java.util.Iterator; import java.util.Map; /** * A Collection of Cookies that allows modification - unlike a mere array. * <p> * Since {@link Cookie} doesn't implement <code>hashCode</code> nor <code>equals</code>, * we cannot simply put it into a <code>HashSet</code>. */ public class CookieCollection implements Collection<Cookie> { private final Map<String, Cookie> cookieMap; public CookieCollection() { cookieMap = new HashMap<>(); } public CookieCollection(Cookie... cookies) { this(Arrays.asList(cookies)); } public CookieCollection(Collection<? extends Cookie> cookies) { cookieMap = new HashMap<>(cookies.size()); addAll(cookies); } @Override public int size() { return cookieMap.size(); } @Override public boolean isEmpty() { return cookieMap.isEmpty(); } @Override public boolean contains(Object o) { if (o instanceof String) { return cookieMap.containsKey(o); } if (o instanceof Cookie) { return cookieMap.containsValue(o); } return false; } @Override public Iterator<Cookie> iterator() { return cookieMap.values().iterator(); } public Cookie[] toArray() { Cookie[] cookies = new Cookie[cookieMap.size()]; return toArray(cookies); } @Override public <T> T[] toArray(T[] ts) { return cookieMap.values().toArray(ts); } @Override public boolean add(Cookie cookie) { if (cookie == null) { return false; } cookieMap.put(cookie.getName(), cookie); return true; } @Override public boolean remove(Object o) { if (o instanceof String) { return cookieMap.remove((String)o) != null; } if (o instanceof Cookie) { Cookie c = (Cookie)o; return cookieMap.remove(c.getName()) != null; } return false; } public Cookie get(String name) { return cookieMap.get(name); } @Override public boolean containsAll(Collection<?> collection) { for(Object o : collection) { if (!contains(o)) { return false; } } return true; } @Override public boolean addAll(Collection<? extends Cookie> collection) { boolean result = false; for(Cookie cookie : collection) { result|= add(cookie); } return result; } @Override public boolean removeAll(Collection<?> collection) { boolean result = false; for(Object cookie : collection) { result|= remove(cookie); } return result; } @Override public boolean retainAll(Collection<?> collection) { boolean result = false; Iterator<Map.Entry<String, Cookie>> it = cookieMap.entrySet().iterator(); while(it.hasNext()) { Map.Entry<String, Cookie> e = it.next(); if (!collection.contains(e.getKey()) && !collection.contains(e.getValue())) { it.remove(); result = true; } } return result; } @Override public void clear() { cookieMap.clear(); } }
java
MIT
4463e58ffb73fe599bac2479abd84598c6e70a1a
2026-01-04T14:45:57.069771Z
false
eugenp/tutorials
https://github.com/eugenp/tutorials/blob/4463e58ffb73fe599bac2479abd84598c6e70a1a/jhipster-modules/jhipster-uaa/gateway/src/main/java/com/baeldung/jhipster/gateway/security/oauth2/OAuth2AuthenticationService.java
jhipster-modules/jhipster-uaa/gateway/src/main/java/com/baeldung/jhipster/gateway/security/oauth2/OAuth2AuthenticationService.java
package com.baeldung.jhipster.gateway.security.oauth2; import com.baeldung.jhipster.gateway.web.rest.errors.InvalidPasswordException; import io.github.jhipster.security.PersistentTokenCache; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import org.springframework.http.ResponseEntity; import org.springframework.security.oauth2.common.OAuth2AccessToken; import org.springframework.web.client.HttpClientErrorException; import javax.servlet.http.Cookie; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; import java.util.Map; /** * Manages authentication cases for OAuth2 updating the cookies holding access and refresh tokens accordingly. * <p> * It can authenticate users, refresh the token cookies should they expire and log users out. */ public class OAuth2AuthenticationService { private final Logger log = LoggerFactory.getLogger(OAuth2AuthenticationService.class); /** * Number of milliseconds to cache refresh token grants so we don't have to repeat them in case of parallel requests. */ private static final long REFRESH_TOKEN_VALIDITY_MILLIS = 10000l; /** * Used to contact the OAuth2 token endpoint. */ private final OAuth2TokenEndpointClient authorizationClient; /** * Helps us with cookie handling. */ private final OAuth2CookieHelper cookieHelper; /** * Caches Refresh grant results for a refresh token value so we can reuse them. * This avoids hammering UAA in case of several multi-threaded requests arriving in parallel. */ private final PersistentTokenCache<OAuth2Cookies> recentlyRefreshed; public OAuth2AuthenticationService(OAuth2TokenEndpointClient authorizationClient, OAuth2CookieHelper cookieHelper) { this.authorizationClient = authorizationClient; this.cookieHelper = cookieHelper; recentlyRefreshed = new PersistentTokenCache<>(REFRESH_TOKEN_VALIDITY_MILLIS); } /** * Authenticate the user by username and password. * * @param request the request coming from the client. * @param response the response going back to the server. * @param params the params holding the username, password and rememberMe. * @return the OAuth2AccessToken as a ResponseEntity. Will return OK (200), if successful. * If the UAA cannot authenticate the user, the status code returned by UAA will be returned. */ public ResponseEntity<OAuth2AccessToken> authenticate(HttpServletRequest request, HttpServletResponse response, Map<String, String> params) { try { String username = params.get("username"); String password = params.get("password"); boolean rememberMe = Boolean.valueOf(params.get("rememberMe")); OAuth2AccessToken accessToken = authorizationClient.sendPasswordGrant(username, password); OAuth2Cookies cookies = new OAuth2Cookies(); cookieHelper.createCookies(request, accessToken, rememberMe, cookies); cookies.addCookiesTo(response); if (log.isDebugEnabled()) { log.debug("successfully authenticated user {}", params.get("username")); } return ResponseEntity.ok(accessToken); } catch (HttpClientErrorException ex) { log.error("failed to get OAuth2 tokens from UAA", ex); throw new InvalidPasswordException(); } } /** * Try to refresh the access token using the refresh token provided as cookie. * Note that browsers typically send multiple requests in parallel which means the access token * will be expired on multiple threads. We don't want to send multiple requests to UAA though, * so we need to cache results for a certain duration and synchronize threads to avoid sending * multiple requests in parallel. * * @param request the request potentially holding the refresh token. * @param response the response setting the new cookies (if refresh was successful). * @param refreshCookie the refresh token cookie. Must not be null. * @return the new servlet request containing the updated cookies for relaying downstream. */ public HttpServletRequest refreshToken(HttpServletRequest request, HttpServletResponse response, Cookie refreshCookie) { //check if non-remember-me session has expired if (cookieHelper.isSessionExpired(refreshCookie)) { log.info("session has expired due to inactivity"); logout(request, response); //logout to clear cookies in browser return stripTokens(request); //don't include cookies downstream } OAuth2Cookies cookies = getCachedCookies(refreshCookie.getValue()); synchronized (cookies) { //check if we have a result from another thread already if (cookies.getAccessTokenCookie() == null) { //no, we are first! //send a refresh_token grant to UAA, getting new tokens String refreshCookieValue = OAuth2CookieHelper.getRefreshTokenValue(refreshCookie); OAuth2AccessToken accessToken = authorizationClient.sendRefreshGrant(refreshCookieValue); boolean rememberMe = OAuth2CookieHelper.isRememberMe(refreshCookie); cookieHelper.createCookies(request, accessToken, rememberMe, cookies); //add cookies to response to update browser cookies.addCookiesTo(response); } else { log.debug("reusing cached refresh_token grant"); } //replace cookies in original request with new ones CookieCollection requestCookies = new CookieCollection(request.getCookies()); requestCookies.add(cookies.getAccessTokenCookie()); requestCookies.add(cookies.getRefreshTokenCookie()); return new CookiesHttpServletRequestWrapper(request, requestCookies.toArray()); } } /** * Get the result from the cache in a thread-safe manner. * * @param refreshTokenValue the refresh token for which we want the results. * @return a RefreshGrantResult for that token. This will either be empty, if we are the first one to do the * request, * or contain some results already, if another thread already handled the grant for us. */ private OAuth2Cookies getCachedCookies(String refreshTokenValue) { synchronized (recentlyRefreshed) { OAuth2Cookies ctx = recentlyRefreshed.get(refreshTokenValue); if (ctx == null) { ctx = new OAuth2Cookies(); recentlyRefreshed.put(refreshTokenValue, ctx); } return ctx; } } /** * Logs the user out by clearing all cookies. * * @param httpServletRequest the request containing the Cookies. * @param httpServletResponse the response used to clear them. */ public void logout(HttpServletRequest httpServletRequest, HttpServletResponse httpServletResponse) { cookieHelper.clearCookies(httpServletRequest, httpServletResponse); } /** * Strips token cookies preventing them from being used further down the chain. * For example, the OAuth2 client won't checked them and they won't be relayed to other services. * * @param httpServletRequest the incoming request. * @return the request to replace it with which has the tokens stripped. */ public HttpServletRequest stripTokens(HttpServletRequest httpServletRequest) { Cookie[] cookies = cookieHelper.stripCookies(httpServletRequest.getCookies()); return new CookiesHttpServletRequestWrapper(httpServletRequest, cookies); } }
java
MIT
4463e58ffb73fe599bac2479abd84598c6e70a1a
2026-01-04T14:45:57.069771Z
false
eugenp/tutorials
https://github.com/eugenp/tutorials/blob/4463e58ffb73fe599bac2479abd84598c6e70a1a/jhipster-modules/jhipster-uaa/gateway/src/main/java/com/baeldung/jhipster/gateway/security/oauth2/OAuth2CookieHelper.java
jhipster-modules/jhipster-uaa/gateway/src/main/java/com/baeldung/jhipster/gateway/security/oauth2/OAuth2CookieHelper.java
package com.baeldung.jhipster.gateway.security.oauth2; import com.baeldung.jhipster.gateway.config.oauth2.OAuth2Properties; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import org.springframework.boot.json.JsonParser; import org.springframework.boot.json.JsonParserFactory; import org.springframework.security.jwt.Jwt; import org.springframework.security.jwt.JwtHelper; import org.springframework.security.oauth2.common.OAuth2AccessToken; import org.springframework.security.oauth2.common.OAuth2RefreshToken; import org.springframework.security.oauth2.common.exceptions.InvalidTokenException; import org.springframework.security.oauth2.provider.token.AccessTokenConverter; import org.springframework.util.StringUtils; import javax.servlet.http.Cookie; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; import java.util.Arrays; import java.util.List; import java.util.Map; import static org.apache.http.conn.util.InetAddressUtils.isIPv4Address; import static org.apache.http.conn.util.InetAddressUtils.isIPv6Address; import org.apache.http.conn.util.PublicSuffixMatcher; import org.apache.http.conn.util.PublicSuffixMatcherLoader; /** * Helps with OAuth2 cookie handling. */ public class OAuth2CookieHelper { /** * Name of the access token cookie. */ public static final String ACCESS_TOKEN_COOKIE = OAuth2AccessToken.ACCESS_TOKEN; /** * Name of the refresh token cookie in case of remember me. */ public static final String REFRESH_TOKEN_COOKIE = OAuth2AccessToken.REFRESH_TOKEN; /** * Name of the session-only refresh token in case the user did not check remember me. */ public static final String SESSION_TOKEN_COOKIE = "session_token"; /** * The names of the Cookies we set. */ private static final List<String> COOKIE_NAMES = Arrays.asList(ACCESS_TOKEN_COOKIE, REFRESH_TOKEN_COOKIE, SESSION_TOKEN_COOKIE); /** * Number of seconds to expire refresh token cookies before the enclosed token expires. * This makes sure we don't run into race conditions where the cookie is still there but * expires while we process it. */ private static final long REFRESH_TOKEN_EXPIRATION_WINDOW_SECS = 3L; /** * Public suffix matcher (to strip private subdomains off cookie scope). */ PublicSuffixMatcher suffixMatcher; private final Logger log = LoggerFactory.getLogger(OAuth2CookieHelper.class); private OAuth2Properties oAuth2Properties; /** * Used to parse JWT claims. */ private JsonParser jsonParser = JsonParserFactory.getJsonParser(); public OAuth2CookieHelper(OAuth2Properties oAuth2Properties) { this.oAuth2Properties = oAuth2Properties; // Alternatively, always get an up-to-date list by passing an URL this.suffixMatcher = PublicSuffixMatcherLoader.getDefault(); } public static Cookie getAccessTokenCookie(HttpServletRequest request) { return getCookie(request, ACCESS_TOKEN_COOKIE); } public static Cookie getRefreshTokenCookie(HttpServletRequest request) { Cookie cookie = getCookie(request, REFRESH_TOKEN_COOKIE); if (cookie == null) { cookie = getCookie(request, SESSION_TOKEN_COOKIE); } return cookie; } /** * Get a cookie by name from the given servlet request. * * @param request the request containing the cookie. * @param cookieName the case-sensitive name of the cookie to get. * @return the resulting Cookie; or null, if not found. */ private static Cookie getCookie(HttpServletRequest request, String cookieName) { if (request.getCookies() != null) { for (Cookie cookie : request.getCookies()) { if (cookie.getName().equals(cookieName)) { String value = cookie.getValue(); if (StringUtils.hasText(value)) { return cookie; } } } } return null; } /** * Create cookies using the provided values. * * @param request the request we are handling. * @param accessToken the access token and enclosed refresh token for our cookies. * @param rememberMe whether the user had originally checked "remember me". * @param result will get the resulting cookies set. */ public void createCookies(HttpServletRequest request, OAuth2AccessToken accessToken, boolean rememberMe, OAuth2Cookies result) { String domain = getCookieDomain(request); log.debug("creating cookies for domain {}", domain); Cookie accessTokenCookie = new Cookie(ACCESS_TOKEN_COOKIE, accessToken.getValue()); setCookieProperties(accessTokenCookie, request.isSecure(), domain); log.debug("created access token cookie '{}'", accessTokenCookie.getName()); OAuth2RefreshToken refreshToken = accessToken.getRefreshToken(); Cookie refreshTokenCookie = createRefreshTokenCookie(refreshToken, rememberMe); setCookieProperties(refreshTokenCookie, request.isSecure(), domain); log.debug("created refresh token cookie '{}', age: {}", refreshTokenCookie.getName(), refreshTokenCookie .getMaxAge()); result.setCookies(accessTokenCookie, refreshTokenCookie); } /** * Create a cookie out of the given refresh token. * Refresh token cookies contain the base64 encoded refresh token (a JWT token). * They also contain a hint whether the refresh token was for remember me or not. * If not, then the cookie will be prefixed by the timestamp it was created at followed by a pipe '|'. * This gives us the chance to expire session cookies regardless of the token duration. */ private Cookie createRefreshTokenCookie(OAuth2RefreshToken refreshToken, boolean rememberMe) { int maxAge = -1; String name = SESSION_TOKEN_COOKIE; String value = refreshToken.getValue(); if (rememberMe) { name = REFRESH_TOKEN_COOKIE; //get expiration in seconds from the token's "exp" claim Integer exp = getClaim(refreshToken.getValue(), AccessTokenConverter.EXP, Integer.class); if (exp != null) { int now = (int) (System.currentTimeMillis() / 1000L); maxAge = exp - now; log.debug("refresh token valid for another {} secs", maxAge); //let cookie expire a bit earlier than the token to avoid race conditions maxAge -= REFRESH_TOKEN_EXPIRATION_WINDOW_SECS; } } Cookie refreshTokenCookie = new Cookie(name, value); refreshTokenCookie.setMaxAge(maxAge); return refreshTokenCookie; } /** * Returns true if the refresh token cookie was set with remember me checked. * We can recognize this by the name of the cookie. * * @param refreshTokenCookie the cookie holding the refresh token. * @return true, if it was set persistently (i.e. for "remember me"). */ public static boolean isRememberMe(Cookie refreshTokenCookie) { return refreshTokenCookie.getName().equals(REFRESH_TOKEN_COOKIE); } /** * Extracts the refresh token from the refresh token cookie. * Since we encode additional information into the cookie, this needs to be called to get * hold of the enclosed JWT. * * @param refreshCookie the cookie we store the value in. * @return the refresh JWT from the cookie. */ public static String getRefreshTokenValue(Cookie refreshCookie) { String value = refreshCookie.getValue(); int i = value.indexOf('|'); if (i > 0) { return value.substring(i + 1); } return value; } /** * Checks if the refresh token session has expired. * Only makes sense for non-persistent cookies, i.e. when remember me was not checked. * The motivation for this is that we want to throw out a user after a while if he's inactive. * We cannot do this via refresh token validity because that one is also used for remember me. * * @param refreshCookie the refresh token cookie to check. * @return true, if the session is expired. */ public boolean isSessionExpired(Cookie refreshCookie) { if (isRememberMe(refreshCookie)) { //no session expiration for "remember me" return false; } //read non-remember-me session length in secs int validity = oAuth2Properties.getWebClientConfiguration().getSessionTimeoutInSeconds(); if (validity < 0) { //no session expiration configured return false; } Integer iat = getClaim(refreshCookie.getValue(), "iat", Integer.class); if (iat == null) { //token creating timestamp in secs is missing, session does not expire return false; } int now = (int) (System.currentTimeMillis() / 1000L); int sessionDuration = now - iat; log.debug("session duration {} secs, will timeout at {}", sessionDuration, validity); return sessionDuration > validity; //session has expired } /** * Retrieve the given claim from the given token. * * @param refreshToken the JWT token to examine. * @param claimName name of the claim to get. * @param clazz the Class we expect to find there. * @return the desired claim. * @throws InvalidTokenException if we cannot find the claim in the token or it is of wrong type. */ @SuppressWarnings("unchecked") private <T> T getClaim(String refreshToken, String claimName, Class<T> clazz) { Jwt jwt = JwtHelper.decode(refreshToken); String claims = jwt.getClaims(); Map<String, Object> claimsMap = jsonParser.parseMap(claims); Object claimValue = claimsMap.get(claimName); if (claimValue == null) { return null; } if (!clazz.isAssignableFrom(claimValue.getClass())) { throw new InvalidTokenException("claim is not of expected type: " + claimName); } return (T) claimValue; } /** * Set cookie properties of access and refresh tokens. * * @param cookie the cookie to modify. * @param isSecure whether it is coming from a secure request. * @param domain the domain for which the cookie is valid. If null, then will fall back to default. */ private void setCookieProperties(Cookie cookie, boolean isSecure, String domain) { cookie.setHttpOnly(true); cookie.setPath("/"); cookie.setSecure(isSecure); //if the request comes per HTTPS set the secure option on the cookie if (domain != null) { cookie.setDomain(domain); } } /** * Logs the user out by clearing all cookies. * * @param httpServletRequest the request containing the Cookies. * @param httpServletResponse the response used to clear them. */ public void clearCookies(HttpServletRequest httpServletRequest, HttpServletResponse httpServletResponse) { String domain = getCookieDomain(httpServletRequest); for (String cookieName : COOKIE_NAMES) { clearCookie(httpServletRequest, httpServletResponse, domain, cookieName); } } private void clearCookie(HttpServletRequest httpServletRequest, HttpServletResponse httpServletResponse, String domain, String cookieName) { Cookie cookie = new Cookie(cookieName, ""); setCookieProperties(cookie, httpServletRequest.isSecure(), domain); cookie.setMaxAge(0); httpServletResponse.addCookie(cookie); log.debug("clearing cookie {}", cookie.getName()); } /** * Returns the top level domain of the server from the request. This is used to limit the Cookie * to the top domain instead of the full domain name. * <p> * A lot of times, individual gateways of the same domain get their own subdomain but authentication * shall work across all subdomains of the top level domain. * <p> * For example, when sending a request to <code>app1.domain.com</code>, * this returns <code>.domain.com</code>. * * @param request the HTTP request we received from the client. * @return the top level domain to set the cookies for. * Returns null if the domain is not under a public suffix (.com, .co.uk), e.g. for localhost. */ private String getCookieDomain(HttpServletRequest request) { String domain = oAuth2Properties.getWebClientConfiguration().getCookieDomain(); if (domain != null) { return domain; } // if not explicitly defined, use top-level domain domain = request.getServerName().toLowerCase(); // strip off leading www. if (domain.startsWith("www.")) { domain = domain.substring(4); } // if it isn't an IP address if (!isIPv4Address(domain) && !isIPv6Address(domain)) { // strip off private subdomains, leaving public TLD only String suffix = suffixMatcher.getDomainRoot(domain); if (suffix != null && !suffix.equals(domain)) { // preserve leading dot return "." + suffix; } } // no top-level domain, stick with default domain return null; } /** * Strip our token cookies from the array. * * @param cookies the cookies we receive as input. * @return the new cookie array without our tokens. */ Cookie[] stripCookies(Cookie[] cookies) { CookieCollection cc = new CookieCollection(cookies); if (cc.removeAll(COOKIE_NAMES)) { return cc.toArray(); } return cookies; } }
java
MIT
4463e58ffb73fe599bac2479abd84598c6e70a1a
2026-01-04T14:45:57.069771Z
false
eugenp/tutorials
https://github.com/eugenp/tutorials/blob/4463e58ffb73fe599bac2479abd84598c6e70a1a/jhipster-modules/jhipster-uaa/gateway/src/main/java/com/baeldung/jhipster/gateway/security/oauth2/CookieTokenExtractor.java
jhipster-modules/jhipster-uaa/gateway/src/main/java/com/baeldung/jhipster/gateway/security/oauth2/CookieTokenExtractor.java
package com.baeldung.jhipster.gateway.security.oauth2; import org.springframework.security.oauth2.provider.authentication.BearerTokenExtractor; import javax.servlet.http.Cookie; import javax.servlet.http.HttpServletRequest; /** * Extracts the access token from a cookie. * Falls back to a <code>BearerTokenExtractor</code> extracting information from the Authorization header, if no * cookie was found. */ public class CookieTokenExtractor extends BearerTokenExtractor { /** * Extract the JWT access token from the request, if present. * If not, then it falls back to the {@link BearerTokenExtractor} behaviour. * * @param request the request containing the cookies. * @return the extracted JWT token; or null. */ @Override protected String extractToken(HttpServletRequest request) { String result; Cookie accessTokenCookie = OAuth2CookieHelper.getAccessTokenCookie(request); if (accessTokenCookie != null) { result = accessTokenCookie.getValue(); } else { result = super.extractToken(request); } return result; } }
java
MIT
4463e58ffb73fe599bac2479abd84598c6e70a1a
2026-01-04T14:45:57.069771Z
false
eugenp/tutorials
https://github.com/eugenp/tutorials/blob/4463e58ffb73fe599bac2479abd84598c6e70a1a/jhipster-modules/jhipster-uaa/gateway/src/main/java/com/baeldung/jhipster/gateway/security/oauth2/UaaSignatureVerifierClient.java
jhipster-modules/jhipster-uaa/gateway/src/main/java/com/baeldung/jhipster/gateway/security/oauth2/UaaSignatureVerifierClient.java
package com.baeldung.jhipster.gateway.security.oauth2; import com.baeldung.jhipster.gateway.config.oauth2.OAuth2Properties; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import org.springframework.beans.factory.annotation.Qualifier; import org.springframework.cloud.client.discovery.DiscoveryClient; import org.springframework.http.HttpEntity; import org.springframework.http.HttpHeaders; import org.springframework.http.HttpMethod; import org.springframework.security.jwt.crypto.sign.RsaVerifier; import org.springframework.security.jwt.crypto.sign.SignatureVerifier; import org.springframework.security.oauth2.common.exceptions.InvalidClientException; import org.springframework.stereotype.Component; import org.springframework.web.client.RestTemplate; import java.util.Map; /** * Client fetching the public key from UAA to create a SignatureVerifier. */ @Component public class UaaSignatureVerifierClient implements OAuth2SignatureVerifierClient { private final Logger log = LoggerFactory.getLogger(UaaSignatureVerifierClient.class); private final RestTemplate restTemplate; protected final OAuth2Properties oAuth2Properties; public UaaSignatureVerifierClient(DiscoveryClient discoveryClient, @Qualifier("loadBalancedRestTemplate") RestTemplate restTemplate, OAuth2Properties oAuth2Properties) { this.restTemplate = restTemplate; this.oAuth2Properties = oAuth2Properties; // Load available UAA servers discoveryClient.getServices(); } /** * Fetches the public key from the UAA. * * @return the public key used to verify JWT tokens; or null. */ @Override public SignatureVerifier getSignatureVerifier() throws Exception { try { HttpEntity<Void> request = new HttpEntity<Void>(new HttpHeaders()); String key = (String) restTemplate .exchange(getPublicKeyEndpoint(), HttpMethod.GET, request, Map.class).getBody() .get("value"); return new RsaVerifier(key); } catch (IllegalStateException ex) { log.warn("could not contact UAA to get public key"); return null; } } /** Returns the configured endpoint URI to retrieve the public key. */ private String getPublicKeyEndpoint() { String tokenEndpointUrl = oAuth2Properties.getSignatureVerification().getPublicKeyEndpointUri(); if (tokenEndpointUrl == null) { throw new InvalidClientException("no token endpoint configured in application properties"); } return tokenEndpointUrl; } }
java
MIT
4463e58ffb73fe599bac2479abd84598c6e70a1a
2026-01-04T14:45:57.069771Z
false
eugenp/tutorials
https://github.com/eugenp/tutorials/blob/4463e58ffb73fe599bac2479abd84598c6e70a1a/jhipster-modules/jhipster-uaa/gateway/src/main/java/com/baeldung/jhipster/gateway/security/oauth2/CookiesHttpServletRequestWrapper.java
jhipster-modules/jhipster-uaa/gateway/src/main/java/com/baeldung/jhipster/gateway/security/oauth2/CookiesHttpServletRequestWrapper.java
package com.baeldung.jhipster.gateway.security.oauth2; import javax.servlet.http.Cookie; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletRequestWrapper; /** * A request mapper used to modify the cookies in the original request. * This is needed such that we can modify the cookies of the request during a token refresh. * The token refresh happens before authentication by the <code>OAuth2AuthenticationProcessingFilter</code> * so we must make sure that further in the filter chain, we have the new cookies and not the expired/missing ones. */ class CookiesHttpServletRequestWrapper extends HttpServletRequestWrapper { /** * The new cookies of the request. Use these instead of the ones found in the wrapped request. */ private Cookie[] cookies; public CookiesHttpServletRequestWrapper(HttpServletRequest request, Cookie[] cookies) { super(request); this.cookies = cookies; } /** * Return the modified cookies instead of the original ones. */ @Override public Cookie[] getCookies() { return cookies; } }
java
MIT
4463e58ffb73fe599bac2479abd84598c6e70a1a
2026-01-04T14:45:57.069771Z
false
eugenp/tutorials
https://github.com/eugenp/tutorials/blob/4463e58ffb73fe599bac2479abd84598c6e70a1a/jhipster-modules/jhipster-uaa/gateway/src/main/java/com/baeldung/jhipster/gateway/security/oauth2/UaaTokenEndpointClient.java
jhipster-modules/jhipster-uaa/gateway/src/main/java/com/baeldung/jhipster/gateway/security/oauth2/UaaTokenEndpointClient.java
package com.baeldung.jhipster.gateway.security.oauth2; import com.baeldung.jhipster.gateway.config.oauth2.OAuth2Properties; import io.github.jhipster.config.JHipsterProperties; import org.springframework.beans.factory.annotation.Qualifier; import org.springframework.http.HttpHeaders; import org.springframework.stereotype.Component; import org.springframework.util.MultiValueMap; import org.springframework.web.client.RestTemplate; import java.nio.charset.StandardCharsets; import java.util.Base64; /** * Client talking to UAA's token endpoint to do different OAuth2 grants. */ @Component public class UaaTokenEndpointClient extends OAuth2TokenEndpointClientAdapter implements OAuth2TokenEndpointClient { public UaaTokenEndpointClient(@Qualifier("loadBalancedRestTemplate") RestTemplate restTemplate, JHipsterProperties jHipsterProperties, OAuth2Properties oAuth2Properties) { super(restTemplate, jHipsterProperties, oAuth2Properties); } @Override protected void addAuthentication(HttpHeaders reqHeaders, MultiValueMap<String, String> formParams) { reqHeaders.add("Authorization", getAuthorizationHeader()); } /** * @return a Basic authorization header to be used to talk to UAA. */ protected String getAuthorizationHeader() { String clientId = getClientId(); String clientSecret = getClientSecret(); String authorization = clientId + ":" + clientSecret; return "Basic " + Base64.getEncoder().encodeToString(authorization.getBytes(StandardCharsets.UTF_8)); } }
java
MIT
4463e58ffb73fe599bac2479abd84598c6e70a1a
2026-01-04T14:45:57.069771Z
false
eugenp/tutorials
https://github.com/eugenp/tutorials/blob/4463e58ffb73fe599bac2479abd84598c6e70a1a/jhipster-modules/jhipster-uaa/gateway/src/main/java/com/baeldung/jhipster/gateway/security/oauth2/OAuth2TokenEndpointClientAdapter.java
jhipster-modules/jhipster-uaa/gateway/src/main/java/com/baeldung/jhipster/gateway/security/oauth2/OAuth2TokenEndpointClientAdapter.java
package com.baeldung.jhipster.gateway.security.oauth2; import com.baeldung.jhipster.gateway.config.oauth2.OAuth2Properties; import io.github.jhipster.config.JHipsterProperties; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import org.springframework.http.HttpEntity; import org.springframework.http.HttpHeaders; import org.springframework.http.HttpStatus; import org.springframework.http.MediaType; import org.springframework.http.ResponseEntity; import org.springframework.security.oauth2.common.OAuth2AccessToken; import org.springframework.security.oauth2.common.exceptions.InvalidClientException; import org.springframework.util.LinkedMultiValueMap; import org.springframework.util.MultiValueMap; import org.springframework.web.client.HttpClientErrorException; import org.springframework.web.client.RestTemplate; /** * Default base class for an OAuth2TokenEndpointClient. * Individual implementations for a particular OAuth2 provider can use this as a starting point. */ public abstract class OAuth2TokenEndpointClientAdapter implements OAuth2TokenEndpointClient { private final Logger log = LoggerFactory.getLogger(OAuth2TokenEndpointClientAdapter.class); protected final RestTemplate restTemplate; protected final JHipsterProperties jHipsterProperties; protected final OAuth2Properties oAuth2Properties; public OAuth2TokenEndpointClientAdapter(RestTemplate restTemplate, JHipsterProperties jHipsterProperties, OAuth2Properties oAuth2Properties) { this.restTemplate = restTemplate; this.jHipsterProperties = jHipsterProperties; this.oAuth2Properties = oAuth2Properties; } /** * Sends a password grant to the token endpoint. * * @param username the username to authenticate. * @param password his password. * @return the access token. */ @Override public OAuth2AccessToken sendPasswordGrant(String username, String password) { HttpHeaders reqHeaders = new HttpHeaders(); reqHeaders.setContentType(MediaType.APPLICATION_FORM_URLENCODED); MultiValueMap<String, String> formParams = new LinkedMultiValueMap<>(); formParams.set("username", username); formParams.set("password", password); formParams.set("grant_type", "password"); addAuthentication(reqHeaders, formParams); HttpEntity<MultiValueMap<String, String>> entity = new HttpEntity<>(formParams, reqHeaders); log.debug("contacting OAuth2 token endpoint to login user: {}", username); ResponseEntity<OAuth2AccessToken> responseEntity = restTemplate.postForEntity(getTokenEndpoint(), entity, OAuth2AccessToken.class); if (responseEntity.getStatusCode() != HttpStatus.OK) { log.debug("failed to authenticate user with OAuth2 token endpoint, status: {}", responseEntity.getStatusCodeValue()); throw new HttpClientErrorException(responseEntity.getStatusCode()); } OAuth2AccessToken accessToken = responseEntity.getBody(); return accessToken; } /** * Sends a refresh grant to the token endpoint using the current refresh token to obtain new tokens. * * @param refreshTokenValue the refresh token to use to obtain new tokens. * @return the new, refreshed access token. */ @Override public OAuth2AccessToken sendRefreshGrant(String refreshTokenValue) { MultiValueMap<String, String> params = new LinkedMultiValueMap<>(); params.add("grant_type", "refresh_token"); params.add("refresh_token", refreshTokenValue); HttpHeaders headers = new HttpHeaders(); addAuthentication(headers, params); HttpEntity<MultiValueMap<String, String>> entity = new HttpEntity<>(params, headers); log.debug("contacting OAuth2 token endpoint to refresh OAuth2 JWT tokens"); ResponseEntity<OAuth2AccessToken> responseEntity = restTemplate.postForEntity(getTokenEndpoint(), entity, OAuth2AccessToken.class); if (responseEntity.getStatusCode() != HttpStatus.OK) { log.debug("failed to refresh tokens: {}", responseEntity.getStatusCodeValue()); throw new HttpClientErrorException(responseEntity.getStatusCode()); } OAuth2AccessToken accessToken = responseEntity.getBody(); log.info("refreshed OAuth2 JWT cookies using refresh_token grant"); return accessToken; } protected abstract void addAuthentication(HttpHeaders reqHeaders, MultiValueMap<String, String> formParams); protected String getClientSecret() { String clientSecret = oAuth2Properties.getWebClientConfiguration().getSecret(); if (clientSecret == null) { throw new InvalidClientException("no client-secret configured in application properties"); } return clientSecret; } protected String getClientId() { String clientId = oAuth2Properties.getWebClientConfiguration().getClientId(); if (clientId == null) { throw new InvalidClientException("no client-id configured in application properties"); } return clientId; } /** * Returns the configured OAuth2 token endpoint URI. * * @return the OAuth2 token endpoint URI. */ protected String getTokenEndpoint() { String tokenEndpointUrl = jHipsterProperties.getSecurity().getClientAuthorization().getAccessTokenUri(); if (tokenEndpointUrl == null) { throw new InvalidClientException("no token endpoint configured in application properties"); } return tokenEndpointUrl; } }
java
MIT
4463e58ffb73fe599bac2479abd84598c6e70a1a
2026-01-04T14:45:57.069771Z
false
eugenp/tutorials
https://github.com/eugenp/tutorials/blob/4463e58ffb73fe599bac2479abd84598c6e70a1a/jhipster-modules/jhipster-uaa/gateway/src/main/java/com/baeldung/jhipster/gateway/security/oauth2/OAuth2Cookies.java
jhipster-modules/jhipster-uaa/gateway/src/main/java/com/baeldung/jhipster/gateway/security/oauth2/OAuth2Cookies.java
package com.baeldung.jhipster.gateway.security.oauth2; import javax.servlet.http.Cookie; import javax.servlet.http.HttpServletResponse; /** * Holds the access token and refresh token cookies. */ class OAuth2Cookies { private Cookie accessTokenCookie; private Cookie refreshTokenCookie; public Cookie getAccessTokenCookie() { return accessTokenCookie; } public Cookie getRefreshTokenCookie() { return refreshTokenCookie; } public void setCookies(Cookie accessTokenCookie, Cookie refreshTokenCookie) { this.accessTokenCookie = accessTokenCookie; this.refreshTokenCookie = refreshTokenCookie; } /** * Add the access token and refresh token as cookies to the response after successful authentication. * * @param response the response to add them to. */ void addCookiesTo(HttpServletResponse response) { response.addCookie(getAccessTokenCookie()); response.addCookie(getRefreshTokenCookie()); } }
java
MIT
4463e58ffb73fe599bac2479abd84598c6e70a1a
2026-01-04T14:45:57.069771Z
false
eugenp/tutorials
https://github.com/eugenp/tutorials/blob/4463e58ffb73fe599bac2479abd84598c6e70a1a/jhipster-modules/jhipster-uaa/gateway/src/main/java/com/baeldung/jhipster/gateway/security/oauth2/OAuth2TokenEndpointClient.java
jhipster-modules/jhipster-uaa/gateway/src/main/java/com/baeldung/jhipster/gateway/security/oauth2/OAuth2TokenEndpointClient.java
package com.baeldung.jhipster.gateway.security.oauth2; import org.springframework.security.oauth2.common.OAuth2AccessToken; /** * Client talking to an OAuth2 Authorization server token endpoint. * * @see UaaTokenEndpointClient * @see OAuth2TokenEndpointClientAdapter */ public interface OAuth2TokenEndpointClient { /** * Send a password grant to the token endpoint. * * @param username the username to authenticate. * @param password his password. * @return the access token and enclosed refresh token received from the token endpoint. * @throws org.springframework.security.oauth2.common.exceptions.ClientAuthenticationException * if we cannot contact the token endpoint. */ OAuth2AccessToken sendPasswordGrant(String username, String password); /** * Send a refresh_token grant to the token endpoint. * * @param refreshTokenValue the refresh token used to get new tokens. * @return the new access/refresh token pair. * @throws org.springframework.security.oauth2.common.exceptions.ClientAuthenticationException * if we cannot contact the token endpoint. */ OAuth2AccessToken sendRefreshGrant(String refreshTokenValue); }
java
MIT
4463e58ffb73fe599bac2479abd84598c6e70a1a
2026-01-04T14:45:57.069771Z
false
eugenp/tutorials
https://github.com/eugenp/tutorials/blob/4463e58ffb73fe599bac2479abd84598c6e70a1a/jhipster-modules/jhipster-uaa/gateway/src/main/java/com/baeldung/jhipster/gateway/security/oauth2/OAuth2SignatureVerifierClient.java
jhipster-modules/jhipster-uaa/gateway/src/main/java/com/baeldung/jhipster/gateway/security/oauth2/OAuth2SignatureVerifierClient.java
package com.baeldung.jhipster.gateway.security.oauth2; import org.springframework.security.jwt.crypto.sign.SignatureVerifier; /** * Abstracts how to create a SignatureVerifier to verify JWT tokens with a public key. * Implementations will have to contact the OAuth2 authorization server to fetch the public key * and use it to build a SignatureVerifier in a server specific way. * * @see UaaSignatureVerifierClient */ public interface OAuth2SignatureVerifierClient { /** * Returns the SignatureVerifier used to verify JWT tokens. * Fetches the public key from the Authorization server to create * this verifier. * * @return the new verifier used to verify JWT signatures. * Will be null if we cannot contact the token endpoint. * @throws Exception if we could not create a SignatureVerifier or contact the token endpoint. */ SignatureVerifier getSignatureVerifier() throws Exception; }
java
MIT
4463e58ffb73fe599bac2479abd84598c6e70a1a
2026-01-04T14:45:57.069771Z
false