1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54
| package com.alten.assistantnc.security;
import java.io.IOException;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;
import javax.servlet.FilterChain;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import org.springframework.security.authentication.UsernamePasswordAuthenticationToken;
import org.springframework.security.core.GrantedAuthority;
import org.springframework.security.core.authority.SimpleGrantedAuthority;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.web.filter.OncePerRequestFilter;
import io.jsonwebtoken.Claims;
import io.jsonwebtoken.Jwts;
public class JWTAuthorizationFilter extends OncePerRequestFilter{
@Override
protected void doFilterInternal(HttpServletRequest request, HttpServletResponse response, FilterChain filterChain)
throws ServletException, IOException {
String jwt = request.getHeader(SecurityConstant.HEADER_STRING);
if(jwt == null || !jwt.startsWith(SecurityConstant.TOKEN_PREFIX)) {
continu(request, response, filterChain);
}else {
treatJwt(request, response, filterChain, jwt);
}
}
private void continu(HttpServletRequest request, HttpServletResponse response, FilterChain filterChain) throws IOException, ServletException {
filterChain.doFilter(request, response);
}
@SuppressWarnings("unchecked")
private void treatJwt(HttpServletRequest request, HttpServletResponse response, FilterChain filterChain,String jwt) throws IOException, ServletException {
Claims claims = Jwts.parser()
.setSigningKey(SecurityConstant.SECRET)
.parseClaimsJws(jwt.replace(SecurityConstant.TOKEN_PREFIX, ""))
.getBody();
String userName = claims.getSubject();
List<Map<String, String>> roles = (List<Map<String, String>>)claims.get(SecurityConstant.ROLES);
List<GrantedAuthority> authorithies = new ArrayList<>();
roles.stream().forEach(r -> authorithies.add(new SimpleGrantedAuthority(r.get("authority"))));
UsernamePasswordAuthenticationToken authenticatioonToken = new UsernamePasswordAuthenticationToken(userName, null, authorithies);
SecurityContextHolder.getContext().setAuthentication(authenticatioonToken);
continu(request, response, filterChain);
}
} |
Partager