Я использую безопасность весенней загрузки для аутентификации и авторизации остальных http apis. Я вижу, что мы можем настроить авторизацию вот так
import org.springframework.context.annotation.Configuration;
import org.springframework.security.config.annotation.web.builders.HttpSecurity;
import org.springframework.security.config.annotation.web.configuration.EnableWebSecurity;
import org.springframework.security.config.annotation.web.configuration.WebSecurityConfigurerAdapter;
import org.springframework.security.config.http.SessionCreationPolicy;
@EnableWebSecurity
@Configuration
class WebSecurityConfig extends WebSecurityConfigurerAdapter {
@Override
protected void configure(HttpSecurity http) throws Exception {
http.sessionManagement()
.sessionCreationPolicy(SessionCreationPolicy.STATELESS).and()
.authorizeRequests()
// .anyRequest().permitAll()
.antMatchers("/user/health_check/*").permitAll()
.antMatchers("/user/registration").permitAll()
.antMatchers("/user/login","/user/logout").hasAnyRole("USER","ADMIN","MANAGER")
.antMatchers("/admin/*").fullyAuthenticated()
.and().httpBasic()
.and().csrf().disable();
}
}
Я хотел знать, как дать разные разрешения для разных URL-адресов, которые отличаются методами запроса?
Например: если мне нужно два URL-адреса, например
// GET /api/account/{id}
// POST /api/account/{id}
// PUT /api/account/{id}
Я хочу предоставить только доступ администратора к PUT и доступ пользователя к GET, а также доступ пользователя и администратора к POST .. как мне этого добиться?




Вы можете использовать аннотацию @PreAuthorize для методов контроллера:
@GetMapping("/api/account/{id}")
@PreAuthorize("hasAutority('readAccountById')")
public Account getAccount(@PathVariable Integer id){
...
}
Он работает с контекстом безопасности Spring, и вы можете проверять роли пользователей, полномочия и многое другое.
Для справки взгляните на эту статью https://www.baeldung.com/spring-security-method-security
Вы можете передать метод запроса в antMatchers.
Попробуйте с этим:
http
.httpBasic().and()
.authorizeRequests()
.antMatchers(HttpMethod.GET, "/api/account/**").hasRole("ADMIN")
.antMatchers(HttpMethod.POST, "/api/account/**").hasRole("ADMIN")
.antMatchers(HttpMethod.PUT, "/api/account/**").hasRole("ADMIN");