I have a separate stand-alone Resource Service whose endpoints are protected by roles/authorities. The service receives a JWS token from a stand-alone Authorization Server. The Resource Service performs only token verification according to the public key etc.
How can I implement filter and add it to the configuration? Am I doing it right? And why Spring still generating a password?
What I have done:
public class JwtTokenVerifier extends OncePerRequestFilter {
@Override
protected void doFilterInternal(HttpServletRequest request, HttpServletResponse response, FilterChain filterChain) throws ServletException, IOException {
String authorizationHeader=request.getHeader("Authorization");
if (Strings.isNullOrEmpty(authorizationHeader)||!authorizationHeader.startsWith("Bearer ")){
filterChain.doFilter(request, response);
return;
}
try{
String token=authorizationHeader.replace("Bearer", "");
Jws<Claims> claimsJws= Jwts.parserBuilder()
.setSigningKey(getKeyFromPublicKey())
.build()
.parseClaimsJws(token);
Claims body=claimsJws.getBody();
String username=body.getSubject();
List<Map<String, String>> authorities=(List<Map<String, String>> )body.get("resource_access");
Set<SimpleGrantedAuthority> simpleGrantedAuthorities=authorities.stream()
.map(m-> new SimpleGrantedAuthority(...))
.collect(Collectors.toSet());
Authentication authentication=new UsernamePasswordAuthenticationToken(username, null, simpleGrantedAuthorities);
SecurityContextHolder.getContext().setAuthentication(authentication);
} catch (JwtException e){
throw new IllegalStateException(String.format("Token cannot be trusted"));
}
filterChain.doFilter(request, response);
}
}
@Override
protected void configure(HttpSecurity http) throws Exception {
http
.csrf().disable()
.sessionManagement().sessionCreationPolicy(SessionCreationPolicy.STATELESS) //JWT
.and()
.addFilterBefore(new JwtTokenVerifier(), UsernamePasswordAuthenticationFilter.class)
.authorizeRequests()
.antMatchers("/","index", "/css/*", "/js/*").permitAll()
.antMatchers(HttpMethod.DELETE, "movieapp/director/**").hasAnyRole(UserRoles.ADMIN.name())
.antMatchers(HttpMethod.POST, "movieapp/director/**").hasAnyRole(UserRoles.USER.name())
.antMatchers(HttpMethod.PUT, "movieapp/director/**").hasAnyRole(UserRoles.ADMIN.name())
.antMatchers(HttpMethod.GET, "movieapp/director/**").hasAnyRole(UserRoles.USER.name());
}