복붙노트

[SPRING] 스프링 보안에서 @Secured 메소드 보안 어노테이션을 사용할 수 없다.

SPRING

스프링 보안에서 @Secured 메소드 보안 어노테이션을 사용할 수 없다.

나는 많은 연구를 해왔다. 그리고 나에게 모든 것은 올바르게 보인다. .. 그러나 나는 이것을 일하게 할 수 없다! 누구든지 어떤 생각을 가지고 있습니까?

내가하는 일과 상관없이, 관련 매핑은 누구에게나 공개됩니다 (익명 또는 로그인, 역할에 관계없이).

이상 적으로 @Secured ()에 의해 주석이 달린 요청을 제외하고 모든 요청이 공용이되도록하고 싶습니다. 특정 역할을 가진 사용자 만이 이러한 매핑에 액세스 할 수 있습니다.

그게 가능하니?

해결 방법으로 FYI 나는 현재 로그인 한 사용자의 역할을 확인하는 메서드 "hasRole (String role)"을 작성하고 메서드가 false를 반환하면 NotAuthorizedException (사용자 정의 만든)을 throw합니다.

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;
  }

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);;
    }

AccountController

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

감사!

해결법

  1. ==============================

    1.Spring HttpSecurity로 컨트롤러 범위 보안을 사용할 수 있습니다. configure 메소드에 다음을 추가하십시오.

    Spring HttpSecurity로 컨트롤러 범위 보안을 사용할 수 있습니다. configure 메소드에 다음을 추가하십시오.

    .antMatchers("rest/accounts*").hasRole("ADMIN")
    

    그리고 어떤 요청이 공개 되길 원한다면 (정말로?) :

    .anyRequest().permitAll()
    

    어디에서나 액세스 할 때 UserDetailsService에 MethodInvocation 예제를 추가로 보안 설정할 수 있습니다.

    @Secured("ROLE_USER")
    public getAllAccounts(...){...}
    

    그래야만 SecurityConfig에 주석을 달아야합니다.

    @EnableGlobalMethodSecurity(securedEnabled = true)
    

    참조 : http://docs.spring.io/autorepo/docs/spring-security/4.0.0.CI-SNAPSHOT/reference/htmlsingle/#request-matching

  2. from https://stackoverflow.com/questions/29275890/can-not-get-the-secured-method-security-annotations-working-in-spring-security by cc-by-sa and MIT license