У меня есть загрузочное приложение Spring, обслуживающее конечные точки Rest, которые я защищаю с помощью безопасности Spring и Oauth2. Я хочу защитить все свои конечные точки, кроме конечных точек, используемых для аутентификации, создания учетной записи или некоторой информации.
Конфигурация безопасности такая:
@Configuration
@EnableAuthorizationServer
public class OAuth2Config extends AuthorizationServerConfigurerAdapter {
@Autowired
private AuthenticationManager authenticationManager;
@Autowired
private MongoTokenStore tokenStore;
@Override
public void configure(final AuthorizationServerSecurityConfigurer oauthServer) throws Exception {
oauthServer.tokenKeyAccess("permitAll()").checkTokenAccess("isAuthenticated()");
}
@Override
public void configure(final ClientDetailsServiceConfigurer clients) throws Exception {
//clients.withClientDetails(clientDetailsService);
clients.inMemory().withClient("app").secret("password")
.accessTokenValiditySeconds(30000).authorizedGrantTypes("password", "refresh_token")
.refreshTokenValiditySeconds(300000000)
.scopes("read");
}
@Override
public void configure(final AuthorizationServerEndpointsConfigurer endpoints) throws Exception {
endpoints.tokenStore(tokenStore()).authenticationManager(authenticationManager)
.pathMapping("/oauth/confirm_access", "/access_confirmation");
}
@Bean
public TokenStore tokenStore() {
return this.tokenStore;
}
}
@Configuration
@EnableResourceServer
@EnableGlobalMethodSecurity(prePostEnabled = true)
public class SecurityConfig extends WebSecurityConfigurerAdapter {
@Autowired
private UserRepository userRepository;
@Autowired
private SecurityContextService securityContextService;
@Autowired
private MongoTemplate mongoTemplate;
@Bean
public MongoUserDetailsManager mongoUserDetailsManager() throws Exception {
return new MongoUserDetailsManager(userRepository, securityContextService, authenticationManagerBean(), mongoTemplate);
}
@Override
protected void configure(final AuthenticationManagerBuilder auth) throws Exception {
auth.parentAuthenticationManager(authenticationManagerBean())
.userDetailsService(mongoUserDetailsManager());
}
@Override
@Bean
public AuthenticationManager authenticationManagerBean() throws Exception {
return super.authenticationManagerBean();
}
@Override
protected void configure(final HttpSecurity http) throws Exception {
http.
authorizeRequests()
.antMatchers("/login", "/oauth/authorize", "/oauth/token", "/server/version", "/clients/register").permitAll()
.and().csrf().disable()
.authorizeRequests()
.anyRequest()
.authenticated()
.and()
.formLogin()
.disable();
}
}
Я могу получить доступ к конечной точке токена, чтобы получить свой access_token, но я хочу получить доступ к другим защищенным конечным точкам с помощью этого access_token (добавив Authorization: Bearer {access_toke} в заголовок), я всегда получаю HTTP 403.
Я что-то пропустил? Я не должен считаться авторизованным, если добавляю заголовок авторизации?
Мои контроллеры аннотируются только этими @RestController, @CrossOrigin и @RequestMapping ("/ url")
Я использую Postman для тестирования, поэтому не уверен, что проблема в пространстве




В Spring существует 2 типа конфигураций безопасности в случае безопасности OAuth (что касается безопасности URL-адресов).
1. Базовая конфигурация безопасности
Этот класс должен реализовывать WebSecurityConfigurerAdapter. Он будет обрабатывать все запросы, поступающие без типа токена Bearer (URL-адреса, которые не должны быть защищены oauth).
@Configuration
@EnableWebSecurity
@EnableGlobalMethodSecurity(prePostEnabled = true)
public class SecurityConfig extends WebSecurityConfigurerAdapter {
@Autowired
private UserRepository userRepository;
@Autowired
private SecurityContextService securityContextService;
@Autowired
private MongoTemplate mongoTemplate;
@Bean
public MongoUserDetailsManager mongoUserDetailsManager() throws Exception {
return new MongoUserDetailsManager(userRepository, securityContextService, authenticationManagerBean(), mongoTemplate);
}
@Override
protected void configure(final AuthenticationManagerBuilder auth) throws Exception {
auth.parentAuthenticationManager(authenticationManagerBean())
.userDetailsService(mongoUserDetailsManager());
}
@Override
@Bean
public AuthenticationManager authenticationManagerBean() throws Exception {
return super.authenticationManagerBean();
}
@Override
protected void configure(final HttpSecurity http) throws Exception {
http.
authorizeRequests()
.antMatchers("/login", "/oauth/authorize", "/oauth/token", "/server/version", "/clients/register").permitAll()
.and().csrf().disable()
.authorizeRequests()
.anyRequest()
.authenticated()
.and()
.formLogin()
.disable();
}
}
2. Конфигурация сервера ресурсов (только для OAuth)
Этот класс отвечает за обработку всех тех запросов, которые идут с заголовком авторизации типа Bearer. Он должен быть расширен из класса ResourceServerConfigurerAdapter. Здесь вы должны упомянуть все те URL-адреса с конфигурациями безопасности, которые вы хотите защитить с помощью oauth.
@Configuration
@EnableResourceServer
public class OAuthResourceServerConfig extends ResourceServerConfigurerAdapter {
@Override
public void configure(HttpSecurity http) throws Exception {
http.requestMatchers().antMatchers("/resources-to-be-protected/**").and().authorizeRequests()
.antMatchers("/resources-to-be-protected/**").access("#oauth2.isClient()");
}
}
Вы можете подтвердить свой заголовок? Он написан как
Authorization:Bearer {token}, но обычно должен быть реализован какAuthorization: Bearer {token}(пространство очень важно)