2017-10-12 109 views
-1

我用彈簧後備箱2彈簧安全。春天開機不把考慮

我分裂安全的休息和MVC。

@EnableWebSecurity 
public class MultiHttpSecurityConfig extends WebSecurityConfigurerAdapter { 

    @Autowired 
    private UserDetailsService userDetailsService; 

    @Bean 
    public PasswordEncoder passwordEncoder() { 
     return new BCryptPasswordEncoder(); 
    } 

    @Override 
    protected void configure(AuthenticationManagerBuilder auth) throws Exception { 
     auth.userDetailsService(userDetailsService).passwordEncoder(passwordEncoder()); 
    } 

    @Configuration 
    @Order(1) 
    public class RestWebSecurityConfigurationAdapter extends WebSecurityConfigurerAdapter { 

     @Override 
     protected void configure(HttpSecurity http) throws Exception { 
      http 
        .antMatcher("/rest/**") 
        .authorizeRequests() 
        .anyRequest().authenticated() 
        .and() 
        .httpBasic().and().sessionManagement().sessionCreationPolicy(SessionCreationPolicy.STATELESS).and().csrf().disable(); 
     } 
    } 

    @Configuration 
    @Order(2) 
    public class FormLoginWebSecurityConfigurerAdapter extends WebSecurityConfigurerAdapter { 

     @Override 
     protected void configure(HttpSecurity http) throws Exception { 
      http 
        .authorizeRequests() 
        .antMatchers("/css/**", "/js/**", "/img/**", "/").permitAll() 
        .anyRequest().authenticated() 
        .and() 
        .formLogin().loginPage("/login").permitAll().successHandler(new CustomAuthenticationSuccessHandler()) 
        .and() 
        .logout() 
        .logoutUrl("/logout") 
        .logoutSuccessHandler(new CustomLogoutHandler()) 
        .and().csrf().disable(); 
     } 
    } 
} 

我在DB的角色是

超級用戶,管理員,集成商。

在我的休息控制器的一個,我把

@Secured("hasRole('user')") 

這個角色在我的應用程序不存在。

我試圖與誰擁有角色的用戶:超級用戶和集成商和合作......

@PreAuthorize("hasAuthority('user')") 

同樣的事情是否有任何其他的配置呢?

+1

的可能的複製[如何啓用安全的註解與基於Java的配置?(https://stackoverflow.com/questions/24865588/how-to-enable-secured-annotations-with-java-based-configuration) – dur

回答

2

爲了確保你必須通過@EnableGlobalMethodSecurity註釋,使方法安全方法。

@Configuration 
@EnableGlobalMethodSecurity(prePostEnabled=true) 
public class HelloMethodSecurityConfig { 

    @Bean 
    public MethodSecurityService methodSecurityService() { 
     return new MethodSecurityServiceImpl(); //Class managed by Spring 
    } 

    @Autowired 
    public void registerGlobal(AuthenticationManagerBuilder auth) throws Exception { 
     auth 
      .inMemoryAuthentication() 
      .withUser("user").password("password").roles("USER").and() 
      .withUser("admin").password("password").roles("USER", "ADMIN"); 
    } 

} 

利用上述最小配置,類MethodSecurityService的方法現在可以用安全的方法固定。

欲瞭解更多定製的方法,安全性,您將需要擴展GlobalMethodSecurityConfiguration

查看官方docs