0Pricing
Spring Security 6 & JWT Authentication · Lección

Autorización basada en roles con Granted Authorities

Después de autenticar a los usuarios desde una base de datos, aprenda a autorizarlos mediante roles y autoridades, protegiendo endpoints y métodos en Spring Security.

Autorización basada en roles con Granted Authorities es una lección gratuita de Spring Security 6 & JWT Authentication en CoddyKit. Esta es la lección 4 de 4. Puedes leer la lección completa abajo gratuitamente — luego la practicas en el navegador con un editor de código integrado y un tutor de IA 24/7. Forma parte de la ruta de aprendizaje de Spring Security 6 & JWT Authentication, y tu progreso se sincroniza en la web y la app de CoddyKit. El curso de Spring Security 6 & JWT Authentication incluye 4 lecciones en total.

Partes de esta lección aún no han sido traducidas y se muestran en inglés.

Authentication vs Authorization

You can now load users from a database and verify passwords. That is authentication (who you are). The next question is authorization (what you may do), driven by roles and authorities.

Authorities and Roles

Spring represents permissions as GrantedAuthority objects. A role is just an authority with a ROLE_ prefix, e.g. ROLE_ADMIN.

Assigning Authorities to a User

When building your UserDetails, attach the authorities the user holds.

User.withUsername('alice')
    .password(encoded)
    .roles('ADMIN', 'USER')
    .build();

Securing URLs by Role

In the filter chain, restrict paths with hasRole. Spring adds the ROLE_ prefix for you here.

http.authorizeHttpRequests(a -> a
    .requestMatchers('/admin/**').hasRole('ADMIN')
    .anyRequest().authenticated());

Requiring Specific Authorities

For finer control use hasAuthority, which matches the authority string exactly with no prefix added.

http.authorizeHttpRequests(a -> a
    .requestMatchers('/reports/**').hasAuthority('REPORT_READ'));

Multiple Allowed Roles

hasAnyRole permits access if the user has at least one of several roles.

http.authorizeHttpRequests(a -> a
    .requestMatchers('/staff/**').hasAnyRole('ADMIN', 'MANAGER'));

Method-Level Security

Enable annotation-based security to protect service methods, not just URLs.

@EnableMethodSecurity
@Configuration
public class SecurityConfig { }

Using @PreAuthorize

@PreAuthorize runs a SpEL expression before the method executes, blocking unauthorized callers.

@PreAuthorize("hasRole('ADMIN')")
public void deleteUser(Long id) { }

Checking the Current User

SpEL can reference the authenticated principal, e.g. to allow users to edit only their own data.

@PreAuthorize("#username == authentication.name")
public void updateProfile(String username) { }

Mapping DB Roles to Authorities

In your UserDetailsService, convert role rows from the database into SimpleGrantedAuthority objects so authorization rules apply.

var auths = roles.stream()
    .map(r -> new SimpleGrantedAuthority('ROLE_' + r))
    .toList();

Putting It Together

The full picture: authenticate from the DB, map roles to authorities, secure URLs with hasRole/hasAuthority, and protect methods with @PreAuthorize.

Quick Check

What is the difference between hasRole('ADMIN') and hasAuthority('ADMIN')?

Recap

You can now control what authenticated users may do:

  • Roles are authorities with a ROLE_ prefix
  • hasRole/hasAnyRole vs exact hasAuthority
  • @EnableMethodSecurity + @PreAuthorize for method-level rules
  • Map DB roles to SimpleGrantedAuthority in your UserDetailsService

Preguntas frecuentes

¿La lección «Autorización basada en roles con Granted Authorities» es gratis?

Sí — el texto completo de «Autorización basada en roles con Granted Authorities» es gratis para leer aquí en la web. Para practicarla de forma interactiva (editor de código integrado y tutor de IA 24/7) y desbloquear el resto del curso de Spring Security 6 & JWT Authentication, actualiza a CoddyKit PRO. El curso de Spring Security 6 & JWT Authentication incluye 4 lecciones en total.

¿Qué aprenderé en «Autorización basada en roles con Granted Authorities»?

Después de autenticar a los usuarios desde una base de datos, aprenda a autorizarlos mediante roles y autoridades, protegiendo endpoints y métodos en Spring Security. Practicas Spring Security 6 & JWT Authentication con código real que ejecutas directamente en el navegador, y un tutor de IA 24/7 responde tus preguntas mientras trabajas en la lección.

¿Necesito experiencia previa para empezar Spring Security 6 & JWT Authentication?

No se requiere experiencia previa. Spring Security 6 & JWT Authentication en CoddyKit está estructurado para principiantes hasta estudiantes avanzados, así que puedes empezar aquí o desde el inicio y avanzar a tu ritmo. Esta es la lección 4 de 4.

¿Cuánto tiempo toma la lección «Autorización basada en roles con Granted Authorities»?

La mayoría de las lecciones de CoddyKit toman alrededor de 5–10 minutos. Cada una es compacta e interactiva, así que avanzas constantemente y retomas exactamente por donde dejaste en la web y la app.

¿Puedo escribir y ejecutar código en esta lección de Spring Security 6 & JWT Authentication?

Sí. Cada lección de Spring Security 6 & JWT Authentication incluye un editor de código integrado, así que escribes y ejecutas código real directamente en tu navegador y obtienes retroalimentación instantánea de IA — sin configuración local necesaria.

Todas las lecciones de este curso

  1. Implementación personalizada de UserDetailsService
  2. Comprensión de los codificadores de contraseñas
  3. Integración de la gestión de usuarios con una base de datos
  4. Autorización basada en roles con Granted Authorities
← Volver a Spring Security 6 & JWT Authentication