RolesAllowed и antMatchers.hasRole возвращают отказ в доступе, вызванный @Order - PullRequest
0 голосов
/ 05 апреля 2020

Я ограничил /api/topics и GET: /api/users только для администраторов, и когда я пытаюсь получить к ним доступ, я получаю следующее сообщение:

{
    "timestamp": "2020-04-05T09:26:49.938+0000",
    "status": 403,
    "error": "Forbidden",
    "message": "Access Denied",
    "path": "/api/topics"
}

Это вызвано @Order(2) в WebSecurityConfiguration, но если я удалю аннотацию @Order, antMatchers.permitAll не позволит мне посетить любую конечную точку REST без токена. Это сообщение:

{
    "error": "unauthorized",
    "error_description": "Full authentication is required to access this resource"
}

Больше информации о @Order здесь . И вы можете проверить мою предыдущую тему на stackoverflow .

Порядок полностью испорчен. Любые идеи, как решить это?

Это работает, если я делаю следующее вместо antMatches.permitAll, но тогда какой смысл в allowAll и всей этой конфигурации http?

@Override
public void configure(WebSecurity web) throws Exception {
    web.ignoring().antMatchers("/api/topics/**");
}

Полный код :

@Configuration
@EnableWebSecurity
@EnableGlobalMethodSecurity(jsr250Enabled = true)
@Order(2)
public class WebSecurityConfiguration extends WebSecurityConfigurerAdapter {

    @Bean
    @Override
    public AuthenticationManager authenticationManagerBean() throws Exception {
        return super.authenticationManagerBean();
    }

    @Override
    protected void configure(HttpSecurity http) throws Exception {
        http
                .csrf().disable()
                .authorizeRequests()
                .antMatchers("/api/topics/**").hasRole("ADMIN")
                .antMatchers("/api/users/**").permitAll()
                .anyRequest().authenticated();
    }

    @Bean
    public BCryptPasswordEncoder bCryptPasswordEncoder() {
        return new BCryptPasswordEncoder();
    }

}

@Configuration
@EnableAuthorizationServer
public class AuthorizationServerConfiguration extends AuthorizationServerConfigurerAdapter {

    @Autowired
    private BCryptPasswordEncoder bCryptPasswordEncoder;

    @Autowired
    private TokenStore tokenStore;

    @Autowired
    private AuthenticationManager authenticationManager;

    @Override
    public void configure(ClientDetailsServiceConfigurer clients) throws Exception {
        clients
                .inMemory()
                .withClient("trusted")
                .secret(bCryptPasswordEncoder.encode("secret"))
                .authorizedGrantTypes("password", "get_token", "refresh_token")
                .scopes("read", "write")
                .autoApprove(true)
                .accessTokenValiditySeconds(15 * 60)
                .refreshTokenValiditySeconds(30 * 60);
    }

    @Override
    public void configure(AuthorizationServerEndpointsConfigurer endpoints) throws Exception {
        endpoints
                .authenticationManager(authenticationManager)
                .tokenStore(tokenStore);
    }

    @Bean
    public TokenStore tokenStore() {
        return new InMemoryTokenStore();
    }

}

@Configuration
@EnableResourceServer
public class ResourceServerConfiguration {

}

// UserController.java
@RolesAllowed("ADMIN")
@GetMapping
public ResponseEntity<List<UserDTO>> getAll() {
    return ResponseEntity.ok(userMapper.toUserDTOs(userService.getAll()));
}

1 Ответ

0 голосов
/ 05 апреля 2020

Вы должны authenticated() после hasRole()

    @Override
    protected void configure(HttpSecurity http) throws Exception {
        http
                .csrf().disable()
                .authorizeRequests()
                .antMatchers("/api/topics/**").hasRole("ADMIN").authenticated() // You need to authenticate here
                .antMatchers("/api/users/**").permitAll()
                .anyRequest().authenticated();
    }
Добро пожаловать на сайт PullRequest, где вы можете задавать вопросы и получать ответы от других членов сообщества.
...