Skip to content

Commit

Permalink
Task 50 : Revise user service and product service for jwt authorization
Browse files Browse the repository at this point in the history
  • Loading branch information
Rapter1990 committed Jul 19, 2024
1 parent cfc88e2 commit 5aac581
Show file tree
Hide file tree
Showing 5 changed files with 89 additions and 6 deletions.
Original file line number Diff line number Diff line change
Expand Up @@ -11,16 +11,14 @@
@Getter
@Configuration
public class TokenConfigurationParameter {
private final String issuer;

private final int accessTokenExpireMinute;
private final int refreshTokenExpireDay;
private final PublicKey publicKey;
private final PrivateKey privateKey;

public TokenConfigurationParameter() {

this.issuer = ConfigurationParameter.ISSUER.getDefaultValue();

this.accessTokenExpireMinute = Integer.parseInt(
ConfigurationParameter.AUTH_ACCESS_TOKEN_EXPIRE_MINUTE.getDefaultValue()
);
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -7,8 +7,6 @@
@RequiredArgsConstructor
public enum ConfigurationParameter {

ISSUER("ISSUER"),

AUTH_ACCESS_TOKEN_EXPIRE_MINUTE("30"),
AUTH_REFRESH_TOKEN_EXPIRE_DAY("1"),
AUTH_PUBLIC_KEY("""
Expand Down
Original file line number Diff line number Diff line change
@@ -1,14 +1,21 @@
package com.springbootmicroservices.productservice.model.common.entity;

import com.springbootmicroservices.productservice.model.auth.enums.TokenClaims;
import jakarta.persistence.Column;
import jakarta.persistence.MappedSuperclass;
import jakarta.persistence.PrePersist;
import jakarta.persistence.PreUpdate;
import lombok.AllArgsConstructor;
import lombok.Getter;
import lombok.NoArgsConstructor;
import lombok.Setter;
import lombok.experimental.SuperBuilder;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.security.oauth2.jwt.Jwt;

import java.time.LocalDateTime;
import java.util.Optional;

/**
* Base entity class named {@link BaseEntity} with common fields for audit tracking and lifecycle management.
Expand All @@ -34,4 +41,34 @@ public class BaseEntity {
@Column(name = "UPDATED_BY")
private String updatedBy;

/**
* Sets the createdBy and createdAt fields before persisting the entity.
* If no authenticated user is found, sets createdBy to "anonymousUser".
*/
@PrePersist
public void prePersist() {
this.createdBy = Optional.ofNullable(SecurityContextHolder.getContext().getAuthentication())
.map(Authentication::getPrincipal)
.filter(user -> !"anonymousUser".equals(user))
.map(Jwt.class::cast)
.map(jwt -> jwt.getClaim(TokenClaims.USER_EMAIL.getValue()).toString())
.orElse("anonymousUser");
this.createdAt = LocalDateTime.now();
}

/**
* Sets the updatedBy and updatedAt fields before updating the entity.
* If no authenticated user is found, sets updatedBy to "anonymousUser".
*/
@PreUpdate
public void preUpdate() {
this.updatedBy = Optional.ofNullable(SecurityContextHolder.getContext().getAuthentication())
.map(Authentication::getPrincipal)
.filter(user -> !"anonymousUser".equals(user))
.map(Jwt.class::cast)
.map(jwt -> jwt.getClaim(TokenClaims.USER_EMAIL.getValue()).toString())
.orElse("anonymousUser");
this.updatedAt = LocalDateTime.now();
}

}
Original file line number Diff line number Diff line change
Expand Up @@ -4,13 +4,18 @@
import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.databind.*;
import com.fasterxml.jackson.databind.annotation.JsonDeserialize;
import com.fasterxml.jackson.databind.node.ArrayNode;
import com.fasterxml.jackson.datatype.jsr310.JavaTimeModule;
import com.springbootmicroservices.productservice.model.auth.JwtRecord;
import lombok.RequiredArgsConstructor;
import org.springframework.security.authentication.UsernamePasswordAuthenticationToken;
import org.springframework.security.core.GrantedAuthority;
import org.springframework.security.core.authority.SimpleGrantedAuthority;
import org.springframework.security.oauth2.jwt.Jwt;

import java.io.IOException;
import java.util.ArrayList;
import java.util.List;

public class UsernamePasswordAuthenticationTokenDeserializer extends JsonDeserializer<UsernamePasswordAuthenticationToken> {

Expand All @@ -35,6 +40,14 @@ public UsernamePasswordAuthenticationToken deserialize(JsonParser p, Deserializa
// Extracting the credentials
String credentials = node.get("credentials").isNull() ? null : node.get("credentials").asText();

return new UsernamePasswordAuthenticationToken(principal, credentials);
// Extracting the authorities
List<GrantedAuthority> authorities = new ArrayList<>();
ArrayNode authoritiesNode = (ArrayNode) node.get("authorities");
for (JsonNode authorityNode : authoritiesNode) {
String authority = authorityNode.get("authority").asText();
authorities.add(new SimpleGrantedAuthority(authority));
}

return new UsernamePasswordAuthenticationToken(principal, credentials, authorities);
}
}
Original file line number Diff line number Diff line change
@@ -1,14 +1,21 @@
package com.springbootmicroservices.userservice.model.common.entity;

import com.springbootmicroservices.userservice.model.user.enums.TokenClaims;
import jakarta.persistence.Column;
import jakarta.persistence.MappedSuperclass;
import jakarta.persistence.PrePersist;
import jakarta.persistence.PreUpdate;
import lombok.AllArgsConstructor;
import lombok.Getter;
import lombok.NoArgsConstructor;
import lombok.Setter;
import lombok.experimental.SuperBuilder;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.security.oauth2.jwt.Jwt;

import java.time.LocalDateTime;
import java.util.Optional;

/**
* Base entity class named {@link BaseEntity} with common fields for audit tracking and lifecycle management.
Expand All @@ -34,4 +41,34 @@ public class BaseEntity {
@Column(name = "UPDATED_BY")
private String updatedBy;

/**
* Sets the createdBy and createdAt fields before persisting the entity.
* If no authenticated user is found, sets createdBy to "anonymousUser".
*/
@PrePersist
public void prePersist() {
this.createdBy = Optional.ofNullable(SecurityContextHolder.getContext().getAuthentication())
.map(Authentication::getPrincipal)
.filter(user -> !"anonymousUser".equals(user))
.map(Jwt.class::cast)
.map(jwt -> jwt.getClaim(TokenClaims.USER_EMAIL.getValue()).toString())
.orElse("anonymousUser");
this.createdAt = LocalDateTime.now();
}

/**
* Sets the updatedBy and updatedAt fields before updating the entity.
* If no authenticated user is found, sets updatedBy to "anonymousUser".
*/
@PreUpdate
public void preUpdate() {
this.updatedBy = Optional.ofNullable(SecurityContextHolder.getContext().getAuthentication())
.map(Authentication::getPrincipal)
.filter(user -> !"anonymousUser".equals(user))
.map(Jwt.class::cast)
.map(jwt -> jwt.getClaim(TokenClaims.USER_EMAIL.getValue()).toString())
.orElse("anonymousUser");
this.updatedAt = LocalDateTime.now();
}

}

0 comments on commit 5aac581

Please sign in to comment.