Bu sınıfın amacı eğer mümkünse SecurityContextHolder.getContext nesnesini doldurmak.
İskeleti
Bu sınıfın iskeleti şöyle
public 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
Şöyle yaparız
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
Filtre sınıfında şöyley yaparız
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
Şöyle yaparız
validToken() metodu bir sürü exception fırlatabilir. Bunlar şöyleif(validToken(jwtToken)){String username = ...;//JWT token'dan username alınır//Eğer username varsa ve SecurityContextHolder.getContext boş iseSecurityContextHolder 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);
import io.jsonwebtoken.MalformedJwtException;import io.jsonwebtoken.SignatureAlgorithm;import io.jsonwebtoken.SignatureException;import io.jsonwebtoken.UnsupportedJwtException;
Hiç yorum yok:
Yorum Gönder