Search code examples
javahibernatespring-securityoauth-2.0microservices

How to manage security context within multiple microservices


I am developing a system that relies on multiple microservices to provide analytics. I have one of the microservices managing authorization using OAuth2 (Resource Owner Password Credentials). My goal is to audit who created/updated a certain entity in an embedded column that look like this:

@Data
@Builder
@NoArgsConstructor
@AllArgsConstructor
@Embeddable
public class AuditEmbeddable implements Serializable {

    @CreatedBy
    @Builder.Default
    @Column(name = "created_by", nullable = false, length = 64, updatable = false)
    private String createdBy = "system";

    @CreatedDate
    @Builder.Default
    @Column(name = "created_at", nullable = false)
    private Instant createdAt = Instant.now();

    @LastModifiedBy
    @Column(name = "modified_by", length = 64)
    private String modifiedBy;

    @LastModifiedDate
    @Column(name = "modified_at")
    private Instant modifiedAt;
}

I am sure that token is always sent with the request because we using an ambassador gateway that authenticates every request. Right now I am using very kinky and wrong (in my opinion) method. I take the token attached to request using @RequestHeader("Authentication"), send the request to the authentication server to get user email (and roles) and pass as a parameter to the service, which in turns sets created_by or updated_by column. Is there a way to intercept and have some kind of context I can pull user info from automatically (with spring calling authentication service for me)?


Solution

  • Your main problem seems to be the propagation of identity and claims across micro services and of course how to design it in a best possible way. Right now you seem to be using OAuth2/OpenID. If you are using JWT as token then it is a standard self contained token which contains the user identity and claims.There are standard classes (ResourceServerConfigurerAdapter , TokenStore etc.) in Spring security which can be configured in each microservice where these JWT tokens can be extracted via a common logic across all microservices.If your token is something other than JWT then you will need to write custom logic to extract the user info and pass it further. Some good references for design can be seen here and here.