【发布时间】:2018-08-19 20:11:13
【问题描述】:
我正在使用 Spring Security 内存身份验证,但它无法正常工作。 它正在生成默认密码,但没有采用我在配置中生成的 用户和密码。下面是我的控制器:
@CrossOrigin(origins = "*")
@EnableAutoConfiguration
@RestController
@RequestMapping("/api")
public class AppController {
@RequestMapping(value="/hello", method=RequestMethod.GET, produces="text/plain")
public String sayHello() {
return "Hello welcome to spring security!!!!";
}
}
下面是我的安全配置类:
@Component
@EnableWebSecurity
/*@EnableGlobalMethodSecurity*/
@EnableAutoConfiguration(exclude = {
org.springframework.boot.autoconfigure.security.SecurityAutoConfiguration.class
})
public class SecurityProvider extends WebSecurityConfigurerAdapter {
@Override
public void configure(HttpSecurity http) throws Exception {
http
.authorizeRequests()
.antMatchers("/api/*").hasRole("ADMIN")
.and()
.formLogin();
}
@Autowired
public void configureGlobal(AuthenticationManagerBuilder auth) throws Exception {
auth
.inMemoryAuthentication()
.withUser("ramu")
.password("password")
.roles("ADMIN")
.and()
.withUser("gopal")
.password("password")
.roles("USER");
}
@Bean
public AuthenticationManager authenticationManagerBean() throws Exception {
// ALTHOUGH THIS SEEMS LIKE USELESS CODE,
// ITS REQUIRED TO PREVENT SPRING BOOT AUTO-CONFIGURATION
return super.authenticationManagerBean();
}
}
我还尝试通过使用以下注释在主应用程序中排除 SecurityAutoconfiguration.class:
@SpringBootApplication(exclude = {SecurityAutoConfiguration.class })
public class App {
public static void main( String[] args ) {
SpringApplication.run(App.class, args);
}
}
但运气不好,它没有使用我在配置类中配置的用户名和密码。
【问题讨论】:
-
正如 git-flo 已经写的那样,您必须将
@Component更改为@Configuration并删除@EnableAutoConfiguration。同时删除authenticationManagerBean方法和exclude = {SecurityAutoConfiguration.class }。
标签: spring-boot spring-security