Skip to content

Commit

Permalink
adding component to fetch authenticated user-id
Browse files Browse the repository at this point in the history
  • Loading branch information
hardikSinghBehl committed Mar 18, 2024
1 parent 7b423c3 commit 9f7ff42
Show file tree
Hide file tree
Showing 2 changed files with 25 additions and 2 deletions.
Original file line number Diff line number Diff line change
@@ -1,5 +1,7 @@
package com.behl.flare.filter;

import java.util.Optional;

import org.apache.commons.lang3.StringUtils;
import org.springframework.security.authentication.UsernamePasswordAuthenticationToken;
import org.springframework.security.core.context.SecurityContextHolder;
Expand All @@ -25,6 +27,7 @@ public class JwtAuthenticationFilter extends OncePerRequestFilter {

private static final String AUTHORIZATION_HEADER = "Authorization";
private static final String BEARER_PREFIX = "Bearer ";
private static final String USER_ID_CLAIM = "user_id";

@Override
@SneakyThrows
Expand All @@ -37,9 +40,9 @@ protected void doFilterInternal(HttpServletRequest request, HttpServletResponse
if (StringUtils.isNotEmpty(authorizationHeader) && authorizationHeader.startsWith(BEARER_PREFIX) ) {
final var token = authorizationHeader.replace(BEARER_PREFIX, StringUtils.EMPTY);
final var firebaseToken = firebaseAuth.verifyIdToken(token);
final var emailId = firebaseToken.getEmail();
final var userId = Optional.ofNullable(firebaseToken.getClaims().get(USER_ID_CLAIM)).orElseThrow(IllegalStateException::new);

final var authentication = new UsernamePasswordAuthenticationToken(emailId, null, null);
final var authentication = new UsernamePasswordAuthenticationToken(userId, null, null);
authentication.setDetails(new WebAuthenticationDetailsSource().buildDetails(request));
SecurityContextHolder.getContext().setAuthentication(authentication);
}
Expand Down
Original file line number Diff line number Diff line change
@@ -0,0 +1,20 @@
package com.behl.flare.utility;

import java.util.Optional;

import org.springframework.security.core.Authentication;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.stereotype.Component;

@Component
public class AuthenticatedUserIdProvider {

public String getUserId() {
return Optional.ofNullable(SecurityContextHolder.getContext().getAuthentication())
.map(Authentication::getPrincipal)
.filter(String.class::isInstance)
.map(String.class::cast)
.orElseThrow(IllegalStateException::new);
}

}

0 comments on commit 9f7ff42

Please sign in to comment.