Spring Security 6 & JWT Authentication · Урок

Авторизация на основе ролей с Granted Authorities

После аутентификации пользователей из базы данных научитесь авторизовывать их с помощью ролей и полномочий, защищая конечные точки и методы в Spring Security

Урок 4 из 413 шагов

«Авторизация на основе ролей с Granted Authorities» — бесплатный урок Spring Security 6 & JWT Authentication на CoddyKit. Это урок 4 из 4. Ты можешь прочитать весь урок бесплатно ниже — а потом практиковать его прямо в браузере с встроенным редактором кода и ИИ-репетитором 24/7. Это часть пути обучения Spring Security 6 & JWT Authentication, и твой прогресс синхронизируется между веб-версией и приложением CoddyKit. Курс Spring Security 6 & JWT Authentication содержит 4 уроков всего.

Части этого урока еще не переведены и отображаются на английском.

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
Можно начать бесплатно

Изучай Java с ИИ-репетитором — бесплатно

Пиши и запускай код прямо в браузере, получай мгновенную помощь от ИИ-репетитора 24/7 и продолжи учиться на сайте или в приложении.

Курсы
12
Уроки
48

Часто задаваемые вопросы

Урок «Авторизация на основе ролей с Granted Authorities» бесплатный?

Да — полный текст урока «Авторизация на основе ролей с Granted Authorities» бесплатно доступен здесь в веб-версии. Чтобы практиковать его интерактивно (встроенный редактор кода и ИИ-репетитор 24/7) и разблокировать остальной курс Spring Security 6 & JWT Authentication, подпишись на CoddyKit PRO. Курс Spring Security 6 & JWT Authentication содержит 4 уроков всего.

Чему я научусь в уроке «Авторизация на основе ролей с Granted Authorities»?

После аутентификации пользователей из базы данных научитесь авторизовывать их с помощью ролей и полномочий, защищая конечные точки и методы в Spring Security Ты практикуешь Spring Security 6 & JWT Authentication с помощью реального кода, который запускаешь прямо в браузере, и ИИ-репетитор 24/7 отвечает на твои вопросы во время урока.

Нужен ли мне опыт, чтобы начать Spring Security 6 & JWT Authentication?

Предыдущий опыт не требуется. Spring Security 6 & JWT Authentication на CoddyKit структурирован для всех уровней — от новичков до продвинутых, поэтому ты можешь начать отсюда или с самого начала и учиться в своем темпе. Это урок 4 из 4.

Сколько времени занимает урок «Авторизация на основе ролей с Granted Authorities»?

Большинство уроков CoddyKit занимают около 5–10 минут. Каждый из них компактный и интерактивный, поэтому ты постоянно делаешь прогресс и продолжаешь с того же места в веб-версии и приложении.

Можно ли писать и запускать код в этом уроке Spring Security 6 & JWT Authentication?

Да. Каждый урок Spring Security 6 & JWT Authentication включает встроенный редактор кода, поэтому ты пишешь и запускаешь реальный код прямо в браузере и получаешь моментальную обратную связь от AI — локальная установка не требуется.

Все уроки этого курса

  1. Реализация пользовательского UserDetailsService
  2. Понимание кодировщиков паролей
  3. Интеграция управления пользователями с базой данных
  4. Авторизация на основе ролей с Granted Authorities
← Назад к Spring Security 6 & JWT Authentication