Security by roles in spring boot api

0

Good, I'm having a problem with the securization of my API, I have everything mounted, a login that returns a token which passed through headers and a series of classes that authorize me to enter thanks to that token, but I want to go beyond that and certain methods I only want them authorized besides the token for a role type (admin) but as much as I try, I do not get anything.

The first thing I do is write down my api with hasrole

@PreAuthorize("hasRole('ROLE_ADMIN')")
@RequestMapping(value = "/categorias", method = RequestMethod.GET)
public List<TmCategorias> getAllCategories() {
    return (List<TmCategorias>) service.getCategorias();
}

And then I validate the token

private UsernamePasswordAuthenticationToken getAuthentication(HttpServletRequest request) {
        String token = request.getHeader(Constants.HEADER_AUTHORIZACION_KEY);
        if (token != null) {
            // Se procesa el token y se recupera el usuario.
            Claims user = Jwts.parser()
                        .setSigningKey(Constants.SUPER_SECRET_KEY)
                        .parseClaimsJws(token.replace(Constants.TOKEN_BEARER_PREFIX, ""))
                        .getBody();

            UserToken userToken= new UserToken();
            userToken.setCorreo(user.getId());
            userToken.setUsuario(user.getSubject());
            userToken.setRole((String) user.get("role"));

           List<GrantedAuthority> grantedAuths = new ArrayList<GrantedAuthority>();
           grantedAuths.add(new SimpleGrantedAuthority(userToken.getRole()));

            if (user != null) {
                return new UsernamePasswordAuthenticationToken(userToken, null, grantedAuths);
            }

            return null;
        }
        return null;
    }

What am I missing? since the access without token if it stops me but by role not

    
asked by Rulogarcillan 04.01.2018 в 16:38
source

1 answer

0

Try adding:

@EnableGlobalMethodSecurity(prePostEnabled=true)
    
answered by 04.01.2018 в 17:26