Created
June 27, 2024 07:56
-
-
Save shortthirdman/84e32169cb7a9e714163f57c59ed8186 to your computer and use it in GitHub Desktop.
JWT Authentication Filter
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
import io.jsonwebtoken.Claims; | |
import io.jsonwebtoken.Jwts; | |
import org.springframework.beans.factory.annotation.Value; | |
import org.springframework.http.HttpHeaders; | |
import org.springframework.security.authentication.UsernamePasswordAuthenticationToken; | |
import org.springframework.security.core.context.SecurityContextHolder; | |
import org.springframework.util.StringUtils; | |
import org.springframework.web.filter.OncePerRequestFilter; | |
import javax.servlet.FilterChain; | |
import javax.servlet.ServletException; | |
import javax.servlet.http.HttpServletRequest; | |
import javax.servlet.http.HttpServletResponse; | |
import java.io.IOException; | |
public class JwtAuthenticationFilter extends OncePerRequestFilter { | |
@Value("${jwt.secret}") | |
private String jwtSecret; | |
@Override | |
protected void doFilterInternal(HttpServletRequest request, HttpServletResponse response, FilterChain filterChain) throws ServletException, IOException { | |
try { | |
String jwt = getJwtFromRequest(request); | |
if (StringUtils.hasText(jwt) && validateToken(jwt)) { | |
Claims claims = Jwts.parser() | |
.setSigningKey(jwtSecret) | |
.parseClaimsJws(jwt) | |
.getBody(); | |
String username = claims.getSubject(); | |
// You can do further validation or processing here | |
UsernamePasswordAuthenticationToken authentication = new UsernamePasswordAuthenticationToken(username, null, null); | |
SecurityContextHolder.getContext().setAuthentication(authentication); | |
} | |
} catch (Exception ex) { | |
// Handle exception if token is invalid | |
} | |
filterChain.doFilter(request, response); | |
} | |
private String getJwtFromRequest(HttpServletRequest request) { | |
String bearerToken = request.getHeader(HttpHeaders.AUTHORIZATION); | |
if (StringUtils.hasText(bearerToken) && bearerToken.startsWith("Bearer ")) { | |
return bearerToken.substring(7); | |
} | |
return null; | |
} | |
private boolean validateToken(String jwt) { | |
// Implement your validation logic here | |
// For example, you can check token expiration, signature validity, etc. | |
return true; | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment