我没有例外,但即使用户没有指定角色,也会调用标有@Secured
的方法。我在pom.xml中使用spring-boot-starter-security
1.3.5但没有使用Spring Boot autoconfig或其他注释。
@RequestMapping(value={"/l"}, method=RequestMethod.GET)
@Secured({"ROLE_TORZSMOD"})
public String list() {
return "partnerList";
}
我的安全配置:
@Configuration
@EnableWebSecurity
@EnableGlobalMethodSecurity(securedEnabled=true)
public class SecurityConfig extends WebSecurityConfigurerAdapter {
@Autowired
DataSource dataSource;
@Autowired
protected void configureGlobal(AuthenticationManagerBuilder auth) throws Exception {
PasswordEncoder encoder = new StandardPasswordEncoder();
auth.jdbcAuthentication()
.dataSource(dataSource)
.passwordEncoder(encoder);
}
@Bean
@Override
public AuthenticationManager authenticationManagerBean() throws Exception {
return super.authenticationManagerBean();
}
@Override
protected void configure(HttpSecurity http) throws Exception {
http
.formLogin().loginPage("/login").permitAll()
.and()
.logout().logoutSuccessUrl("/login?logout").permitAll()
.and()
.authorizeRequests()
.antMatchers("/resources/**").permitAll()
.anyRequest().authenticated();
}
}
来自调试日志的登录信息(ROLE_TORZSMOD不在权限列表中):
2016-06-17 09:55:10,378 DEBUG o.s.s.w.a.i.FilterSecurityInterceptor - Previously Authenticated: org.springframework.security.authentication.UsernamePasswordAuthenticationToken@d78c39df:
Principal: org.springframework.security.core.userdetails.User@65812e3: Username: pappt; Password: [PROTECTED]; Enabled: true; AccountNonExpired: true; credentialsNonExpired: true;
AccountNonLocked: true; Granted Authorities: ROLE_BIZMOD; Credentials: [PROTECTED]; Authenticated: true; Details: org.springframework.security.web.authentication.WebAuthenticationDetails@0:
RemoteIpAddress: 0:0:0:0:0:0:0:1; SessionId: 7CE797647B43DEDCED00AF439F446FA1; Granted Authorities: ROLE_BIZMOD
答案 0 :(得分:3)
在这里找到答案:spring @PreAuthorize not working with @EnableGlobalMethodSecurity(prePostEnabled = true)
解决方案1:
将注释移动到另一个配置类。现在@Secured和@PreAuthorize都有效。
@Configuration
@ComponentScan("name.gmail.nsomlai.sawmill.controller")
@EnableWebMvc
@EnableGlobalMethodSecurity(prePostEnabled=true, securedEnabled=true)
public class WebConfig extends WebMvcConfigurerAdapter {
...
}
解决方案2:
将注释保留在原来的位置,并将安全配置类添加到主配置中(不确定这是否有任何副作用,但它有效):
public class MasterConfig extends AbstractAnnotationConfigDispatcherServletInitializer {
...
@Override
protected Class<?>[] getServletConfigClasses() {
return new Class<?>[] { WebConfig.class, SecurityConfig.class };
}
...
}
由于我花了3天时间来实现一个简单的自定义登录页面和URL安全性,如果我想保持最后期限,我发现使用Spring Security风险太大。我可能会实现我自己的基于拦截器的简单安全性。对于简单的访问控制来说,这太复杂了,版本太多,教程冲突,文档庞大。