Segui um tutorial sobre autenticação via token com spring, consegui gerar o token e autenticar com tranquilidade, porem para autorização não está funcionando, acredito que seja pelo retorno do método com as GrantedAuthority como emptyList().
Desculpe pela ignorância e já agradeço pela ajuda.
Quando realizo um get “no header vai o tokem” em “/produtos/list” recebo não autorizado, comecei a depurar as classes o token é obtido é valido também.
@Configuration
@EnableWebSecurity
public class SecurityConfiguration extends WebSecurityConfigurerAdapter {
@Override
protected void configure(HttpSecurity http) throws Exception {
http
.csrf().disable()
.authorizeRequests()
.antMatchers("/").permitAll()
.antMatchers(HttpMethod.POST, "/login").permitAll()
.antMatchers("/shopping/**").hasRole("ADMIN")
.antMatchers(HttpMethod.GET,"/produtos/list").hasRole("ADMIN")
.anyRequest().authenticated()
.and()
.addFilterBefore(new JWTLoginFilter("/login", authenticationManager()), UsernamePasswordAuthenticationFilter.class)
// And filter other requests to check the presence of JWT in header
.addFilterBefore(new JWTAuthenticationFilter(), UsernamePasswordAuthenticationFilter.class);
}
@Override
protected void configure(AuthenticationManagerBuilder auth)
throws Exception {
System.out.println("SecurityConfiguration - configure - AuthenticationManagerBuilder");
// Create a default account
auth.inMemoryAuthentication()
.withUser("admin")
.password("password")
.roles("ADMIN");
}
public class JWTLoginFilter extends AbstractAuthenticationProcessingFilter {
public JWTLoginFilter(String url, AuthenticationManager authManager) {
super(new AntPathRequestMatcher(url));
setAuthenticationManager(authManager);
}
@Override
public Authentication attemptAuthentication(HttpServletRequest req, HttpServletResponse res)
throws AuthenticationException, IOException, ServletException {
System.out.println("JWTLoginFilter - attemptAuthentication ");
AccountCredentials creds = new ObjectMapper().readValue(req.getInputStream(), AccountCredentials.class);
return getAuthenticationManager().authenticate(
new UsernamePasswordAuthenticationToken(
creds.getUsername(),
creds.getPassword(),
Collections.emptyList()
)
);
}
@Override
protected void successfulAuthentication(
HttpServletRequest req,
HttpServletResponse res, FilterChain chain,
Authentication auth) throws IOException, ServletException {
System.out.println("JWTLoginFilter - successfulAuthentication ");
TokenAuthenticationService
.addAuthentication(res, auth.getName());
}
}
public class JWTAuthenticationFilter extends GenericFilterBean {
@Override
public void doFilter(ServletRequest request,
ServletResponse response,
FilterChain filterChain)
throws IOException, ServletException {
System.out.println("JWTAuthenticationFilter - doFilter ");
Authentication authentication = TokenAuthenticationService
.getAuthentication((HttpServletRequest)request);
///System.out.println("JWTAuthenticationFilter - doFilter - getPrincipal : "+authentication.getPrincipal()+" Credencials : "+authentication.getCredentials()+" roles : "+authentication.getAuthorities().size());
SecurityContextHolder.getContext()
.setAuthentication(authentication);
filterChain.doFilter(request,response);
}
}
public class TokenAuthenticationService {
static final long EXPIRATIONTIME = 864_000_000; // 10 days
static final String SECRET = "ThisIsASecret";
static final String TOKEN_PREFIX = "Bearer";
static final String HEADER_STRING = "Authorization";
static void addAuthentication(HttpServletResponse res, String username) {
System.out.println("TokenAuthenticationService - addAuthentication ");
String JWT = Jwts.builder()
.setSubject(username)
.setExpiration(new Date(System.currentTimeMillis() + EXPIRATIONTIME))
.signWith(SignatureAlgorithm.HS512, SECRET)
.compact();
res.addHeader(HEADER_STRING, TOKEN_PREFIX + " " + JWT);
}
static Authentication getAuthentication(HttpServletRequest request) {
System.out.println("TokenAuthenticationService - getAuthentication ");
String token = request.getHeader(HEADER_STRING);
System.out.println("Token - "+token);
if (token != null) {
// parse the token.
String user = Jwts.parser()
.setSigningKey(SECRET)
.parseClaimsJws(token.replace(TOKEN_PREFIX, ""))
.getBody()
.getSubject();
System.out.println("User - "+user);
if(user != null){
System.out.println("return UsernamePasswordAuthenticationToken");
return new UsernamePasswordAuthenticationToken(user, null, emptyList());
}else{
System.out.println("User Null ");
return null;
}
}
System.out.println("Token Nulo ");
return null;
}
}