无法在Spring Security中获取@Secured Method Security注释

Joa*_*nck 2 java spring annotations spring-security

我已经做了很多研究,对我而言,一切看起来都很正确......但是我无法让它发挥作用!任何人有任何想法?

无论我做什么,相关的映射仍然公开给任何人(匿名或登录,无论他们有什么角色).

理想情况下,我希望所有请求都是公共的,除了那些由@Secured()注释的请求 - 显然只有具有特定角色的用户才能访问这些映射.

那可能吗?

仅供参考我作为一种解决方法我目前构建了一个方法"hasRole(String role)",它检查登录用户的角色,如果方法返回false,则抛出NotAuthorizedException(自定义).

的UserDetails

  @Override
  public Collection<? extends GrantedAuthority> getAuthorities() {

      List<GrantedAuthority> grantedAuthorities = null;

      System.out.print("Account role... ");
      System.out.println(account.getRole());

      if (account.getRole().equals("USER")) {
          GrantedAuthority grantedAuthority = new SimpleGrantedAuthority("ROLE_USER");
          grantedAuthorities = Arrays.asList(grantedAuthority);
      }

      if (account.getRole().equals("ADMIN")) {
          GrantedAuthority grantedAuthorityUser = new SimpleGrantedAuthority("ROLE_USER");
          GrantedAuthority grantedAuthorityAdmin = new SimpleGrantedAuthority("ROLE_ADMIN");
          grantedAuthorities = Arrays.asList(grantedAuthorityUser, grantedAuthorityAdmin);
      }

      return grantedAuthorities;
  }
Run Code Online (Sandbox Code Playgroud)

SecurityConfig

@Configuration
@EnableWebSecurity
@EnableGlobalMethodSecurity(securedEnabled = true)
public class SecurityConfig extends WebSecurityConfigurerAdapter {

    @Autowired
    private AuthFailure authFailure;

    @Autowired
    private AuthSuccess authSuccess;

    @Autowired
    private EntryPointUnauthorizedHandler unauthorizedHandler;

    @Autowired
    private UserDetailsServiceImpl userDetailsService;

    /*@Autowired
    public void configAuthBuilder(AuthenticationManagerBuilder builder) throws Exception {
        builder.userDetailsService(userDetailsService);
    }*/

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

    @Autowired
    @Override
    public void configure(AuthenticationManagerBuilder builder) throws Exception {
        builder.userDetailsService(userDetailsService);
    }

  private CsrfTokenRepository csrfTokenRepository() {
    HttpSessionCsrfTokenRepository repository = new HttpSessionCsrfTokenRepository();
    repository.setHeaderName("X-XSRF-TOKEN");
    return repository;
  }

    @Override
    public void configure(HttpSecurity http) throws Exception {
      http.csrf().csrfTokenRepository(csrfTokenRepository())
        .and().exceptionHandling().authenticationEntryPoint(unauthorizedHandler)
        .and().formLogin().loginPage("/login").successHandler(authSuccess).failureHandler(authFailure)
        //.and().authorizeRequests().antMatchers("/rest/**").authenticated()
        //.and().authorizeRequests().antMatchers("/**").permitAll()
        .and().addFilterAfter(new CsrfHeaderFilter(), CsrfFilter.class);;
    }
Run Code Online (Sandbox Code Playgroud)

的AccountController

  @Secured("ROLE_USER")
  @RequestMapping(method = RequestMethod.GET)
  public List<Account> getAllAccounts(@RequestParam(value = "mail", required = false) String mail) {
Run Code Online (Sandbox Code Playgroud)

谢谢!

sve*_*tek 5

您可以使用Spring HttpSecurity的Controller作用域安全性.尝试将此添加到您的configure方法:

.antMatchers("rest/accounts*").hasRole("ADMIN")
Run Code Online (Sandbox Code Playgroud)

如果您希望任何请求公开(真的吗?):

.anyRequest().permitAll()
Run Code Online (Sandbox Code Playgroud)

当您从任何地方访问它时,您还可以在UserDetailsS​​ervice中保护您的Methodinvocation for Example:

@Secured("ROLE_USER")
public getAllAccounts(...){...}
Run Code Online (Sandbox Code Playgroud)

只有这样你才需要用以下方法注释你的SecurityConfig:

@EnableGlobalMethodSecurity(securedEnabled = true)
Run Code Online (Sandbox Code Playgroud)

实际上,我们建议您在服务层使用方法安全性,以控制对应用程序的访问,而不是完全依赖于在Web应用程序级别定义的安全性约束.URL发生变化,很难考虑应用程序可能支持的所有可能的URL以及如何操作请求.您应该尝试限制自己使用一些简单易懂的简单蚂蚁路径.始终尝试使用"默认拒绝"方法,其中您最后定义了一个全能通配符(/或)并拒绝访问.在服务层定义的安全性更强大,更难以绕过,因此您应该始终利用Spring Security的方法安全选项.

请参阅:http://docs.spring.io/autorepo/docs/spring-security/4.0.0.CI-SNAPSHOT/reference/htmlsingle/#request-matching