GirişBu sınıfın amacı eğer mümkünse SecurityContextHolder.getContext nesnesini doldurmak.
İskeleti
Bu sınıfın iskeleti
şöylepublic class JwtAuthenticationFilter extends OncePerRequestFilter {
@Override
protected void doFilterInternal(HttpServletRequest httpServletRequest,
HttpServletResponse httpServletResponse, FilterChain filterChain)
throws ServletException, IOException {
...
}
}
Bazı kodlarda
OncePerRequestFilter yerine
BasicAuthenticationFilter'dan kalıtıyor ancak bu sınıfın amacı
Http Basic Authentication yapmak. Amacının açıklaması
şöyle. Dolayısıyla
OncePerRequestFilter'dan kalıtmak daha iyi.
In summary, this filter is responsible for processing any request that has a HTTP request header of Authorization with an authentication scheme of Basic and a Base64-encoded username:password token. For example, to authenticate user "Aladdin" with password "open sesame" the following header would be presented:
Authorization: Basic QWxhZGRpbjpvcGVuIHNlc2FtZQ==
Filtreyi Tanıtmak
public class SecurityConfig extends WebSecurityConfigurerAdapter {
@Override
protected void configure(HttpSecurity http) throws Exception {
http...;
http.sessionManagement().sessionCreationPolicy(SessionCreationPolicy.STATELESS)
http.addFilterBefore(jwtAuthenticationFilter(),
UsernamePasswordAuthenticationFilter.class);
}
JWT Token'ı Elde Etmek
private String getJwtFromRequest(HttpServletRequest request) {
String bearerToken = request.getHeader("Authorization");
if (StringUtils.hasText(bearerToken) && bearerToken.startsWith("Bearer ")) {
return bearerToken.substring(7, bearerToken.length());
}
return null;
}
SecurityContextHolder Nesnesini Doldurmak
if(validToken(jwtToken)){
String username = ...;//JWT token'dan username alınır
//Eğer username varsa ve SecurityContextHolder.getContext boş ise
SecurityContextHolder securityContextHolder = SecurityContextHolder.getContext();
if (username != null && securityContextHolder.getAuthentication() == null) {
UserDetails userDetails = userDetailsService.loadUserByUsername(username);
UsernamePasswordAuthenticationToken usernamePasswordAuthenticationToken =
new UsernamePasswordAuthenticationToken(userDetails, null,
userDetails.getAuthorities());
usernamePasswordAuthenticationToken.setDetails(new
WebAuthenticationDetailsSource().buildDetails(request));
securityContextHolder.setAuthentication(usernamePasswordAuthenticationToken);
}
}
filterChain.doFilter(request, response);
validToken() metodu bir sürü exception fırlatabilir. Bunlar şöyle
import io.jsonwebtoken.MalformedJwtException;
import io.jsonwebtoken.SignatureAlgorithm;
import io.jsonwebtoken.SignatureException;
import io.jsonwebtoken.UnsupportedJwtException;