使用Spring security时遇到的问题

创建springboot 项目,选择jpa, Thymeleaf,security这三个依赖。

项目创建好之后,加上如下访问:

@RestController
public class UserController {
	@RequestMapping("/")
	public String info(){
		return "hello security";
	}
}

启动启动类时,报错

***************************
APPLICATION FAILED TO START
***************************
Description:
Failed to auto-configure a DataSource: 'spring.datasource.url' is not specified and no embedded datasource could be auto-configured.
Reason: Failed to determine a suitable driver class
Action:
Consider the following:
If you want an embedded database (H2, HSQL or Derby), please put it on the classpath.

If you have database settings to be loaded from a particular profile you may need to activate it (no profiles are currently active).

在多方查证后,需要在启动类的@EnableAutoConfiguration或@SpringBootApplication中添加exclude

= {DataSourceAutoConfiguration.class},排除此类的autoconfig。

加上如上code,排除自动配置datasource.

@SpringBootApplication(exclude= {DataSourceAutoConfiguration.class})
public class SecurityDemoApplication {

	public static void main(String[] args) {
		SpringApplication.run(SecurityDemoApplication.class, args);
	}
}
public class SecurityDemoApplication {

	public static void main(String[] args) {
		SpringApplication.run(SecurityDemoApplication.class, args);
	}
}

正常启动。

访问localhost:8080/   ,url会变成http://localhost:8080/login,出现了如下的登陆界面,但是我们创建项目后并没有添加任何代码。

这是因为在SpringBoot中,默认的Spring Security生效了的,此时的接口都是被保护的,我们需要通过验证才能正常的访问。 Spring Security提供了一个默认的用户,用户名是user,而密码则是启动项目的时候自动生成的。 我们查看项目启动的日志,会发现如下的一段Log。

我们直接用user和启动日志中的密码进行登录。然后就能正常进行。

但是如果不想使用Spring Security,

在Application启动类上(或者任意@Configure配置类上)增加如下注解:

(最开始是在配置文件中设置过security.basic.enabled = false,但是发现这个设置已经不起作用了,我用的是Spring security 5.0.5)

@EnableAutoConfiguration(exclude = {  
        org.springframework.boot.autoconfigure.security.servlet.SecurityAutoConfiguration.class  
})  

最后启动类的code如下:

@EnableAutoConfiguration(exclude = {org.springframework.boot.autoconfigure.security.servlet.SecurityAutoConfiguration.class})  
@SpringBootApplication(exclude= {DataSourceAutoConfiguration.class})
public class SecurityDemoApplication {

	public static void main(String[] args) {
		SpringApplication.run(SecurityDemoApplication.class, args);
	}
}

启动  启动类,又报datasource的错误,

Description:

Failed to auto-configure a DataSource: 'spring.datasource.url' is not specified and no embedded datasource could be auto-configured.

Reason: Failed to determine a suitable driver class

怎么回事?

原来:

@SpringbootApplication相当于@Configuration,@EnableAutoConfiguration和 @ComponentScan

于是将启动类上的注解进行修改,如下:

@SpringBootApplication(exclude= {DataSourceAutoConfiguration.class,org.springframework.boot.autoconfigure.security.servlet.SecurityAutoConfiguration.class})

项目正常启动,并且不出现spring security自带的登陆验证页面。

猜你喜欢

转载自blog.csdn.net/qq_26817225/article/details/80574219