2016-10-06 1 views
0

Я хотел бы защитить свою конечную точку, так что только пользователи с ролью READ могут получить доступ к определенному ресурсу. Это мои конфигурации:Пользователь может получить доступ к ресурсу, даже если он не является частью «@Secured ([role])»

Контроллер:

@RestController 
@RequestMapping("/api/status") 
public class StatusController { 

    @RequestMapping(method = RequestMethod.GET) 
    @Secured("READ") 
    Map<String, Object> getSecureStatus() { 
     Map<String, Object> statusMap = new LinkedHashMap<>(); 

     Authentication auth = SecurityContextHolder.getContext().getAuthentication(); 

     statusMap.put("auth", auth); 
     return statusMap; 
    } 
} 

WebSecurityConfigurerAdapter:

@Configuration 
@EnableGlobalMethodSecurity(securedEnabled = true) 
@EnableWebSecurity 
public class SecurityConfig extends WebSecurityConfigurerAdapter { 
    @Override 
    protected void configure(HttpSecurity http) throws Exception { 
     http 
      .authorizeRequests() 
      // .antMatchers("/").permitAll() 
       .antMatchers("/api/**").authenticated() 
       .and() 
      .httpBasic(); 
    } 
} 

GlobalAuthenticationConfigurerAdapter:

@Configuration 
public class AuthenticationManagerConfig extends 
     GlobalAuthenticationConfigurerAdapter { 

    @Override 
    public void init(AuthenticationManagerBuilder auth) throws Exception { 
     auth.inMemoryAuthentication() 
       .withUser("teddy").password("password").roles("USER"); 
    } 

} 

Я бы предположил, что Тедди не должен быть в состоянии получить доступ к ресурс, так как его роль US ER, а не READ.

Но с этим вызовом, Тедди получает свою информацию в любом случае: curl -u teddy:password 'http://localhost:8080/api/status/':

{ 
    "auth": { 
    "details": { 
     "remoteAddress": "127.0.0.1", 
     "sessionId": null 
    }, 
    "authorities": [ 
     { 
     "authority": "ROLE_USER" 
     } 
    ], 
    "authenticated": true, 
    "principal": { 
     "password": null, 
     "username": "teddy", 
     "authorities": [ 
     { 
      "authority": "ROLE_USER" 
     } 
     ], 
     "accountNonExpired": true, 
     "accountNonLocked": true, 
     "credentialsNonExpired": true, 
     "enabled": true 
    }, 
    "credentials": null, 
    "name": "teddy" 
    } 
} 

Что мне не хватает?

Edit: убрана .antMatchers("/").permitAll()

ответ

0

Я нашел ошибку. Я упустил из виду, что getSecureStatus() не был определен явно public. Этот код исправляет это:

@RestController 
@RequestMapping("/api/status") 
public class StatusController { 

    @RequestMapping(method = RequestMethod.GET) 
    @Secured("READ") 
    public Map<String, Object> getSecureStatus() { 
     Map<String, Object> statusMap = new LinkedHashMap<>(); 

     Authentication auth = SecurityContextHolder.getContext().getAuthentication(); 

     statusMap.put("auth", auth); 
     return statusMap; 
    } 
} 
1

Вероятно, это потому, что вы используете .antMatchers("/").permitAll() это говорит весной, что вы позволяете каждый запрос.

Попробуйте удалить его из своей конфигурации.

+0

Благодарим за подсказку, но, к сожалению, поведение будет таким же, даже если я удалю линию. – user3105453

Смежные вопросы