Autorização baseada em funções com Granted Authorities
Depois de autenticar usuários a partir de um banco de dados, aprenda a autorizá-los usando funções e autoridades, protegendo endpoints e métodos no Spring Security.
Autorização baseada em funções com Granted Authorities é uma aula grátis de Spring Security 6 & JWT Authentication no CoddyKit. Esta é a aula 4 de 4. Você pode ler a aula completa abaixo gratuitamente — depois pratica ao vivo no navegador com um editor de código integrado e um tutor de IA 24/7. Faz parte do caminho de aprendizado de Spring Security 6 & JWT Authentication, e seu progresso é sincronizado entre a web e o app CoddyKit. O curso de Spring Security 6 & JWT Authentication inclui 4 aulas no total.
Partes desta aula ainda não foram traduzidas e aparecem em 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/hasAnyRolevs exacthasAuthority@EnableMethodSecurity+@PreAuthorizefor method-level rules- Map DB roles to
SimpleGrantedAuthorityin your UserDetailsService
Perguntas Frequentes
A aula “Autorização baseada em funções com Granted Authorities” é grátis?
Sim — o texto completo de “Autorização baseada em funções com Granted Authorities” é grátis para ler aqui na web. Para praticá-la interativamente (um editor de código integrado e um tutor de IA 24/7) e desbloquear o restante do curso de Spring Security 6 & JWT Authentication, atualize para CoddyKit PRO. O curso de Spring Security 6 & JWT Authentication inclui 4 aulas no total.
O que vou aprender em “Autorização baseada em funções com Granted Authorities”?
Depois de autenticar usuários a partir de um banco de dados, aprenda a autorizá-los usando funções e autoridades, protegendo endpoints e métodos no Spring Security. Você pratica Spring Security 6 & JWT Authentication com código prático que executa diretamente no navegador, e um tutor de IA 24/7 responde suas dúvidas enquanto trabalha na aula.
Preciso ter experiência prévia para começar Spring Security 6 & JWT Authentication?
Nenhuma experiência prévia é necessária. Spring Security 6 & JWT Authentication no CoddyKit é estruturado para alunos iniciantes até avançados, então você pode começar aqui ou desde o início e aprender no seu ritmo. Esta é a aula 4 de 4.
Quanto tempo leva a aula “Autorização baseada em funções com Granted Authorities”?
A maioria das aulas CoddyKit leva cerca de 5–10 minutos. Cada uma é compacta e interativa, então você faz progresso constante e retoma exatamente de onde parou entre web e app.
Posso escrever e executar código nesta aula de Spring Security 6 & JWT Authentication?
Sim. Cada aula de Spring Security 6 & JWT Authentication inclui um editor de código integrado, então você escreve e executa código real direto no navegador e recebe feedback de IA instantaneamente — nenhuma configuração local necessária.
Todas as aulas deste curso
- Implementação personalizada de UserDetailsService
- Entendendo codificadores de senhas
- Integração do gerenciamento de usuários com banco de dados
- Autorização baseada em funções com Granted Authorities