由于Springboot使用自动化配置,所以减少了繁琐的XML配置,使用起来更加方便和简单,所以这次简单探索下Springboot中,Spring Security的使用方法。
1. 创建Springboot项目,引入依赖,,选择web和Security依赖
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-security</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-web</artifactId>
</dependency>
2. 配置Spring Security的两种方法。
为了能看到效果,这里写一个简单的Controller进行测试。
@RestController
public class HelloController {
@GetMapping("/hello")
public String hello() {
return "cybzc";
}
}
由于使用Security,该策略下使我们访问接口时会先进行登录,当我们访问http://localhost:8080/hello时,会跳转到一个登录的页面,效果如下:
这时看到控制台会输出一行
Using generated security password: 9f83113a-9554-4ebe-ada6-4f8e6f451d2c
这个就是Spring Security帮我们做的安全登录处理,使用用户名user和那段密文,登陆成功后才能正常访问我们写的接口。
这里我们可以想要修改用户名和密码,有两种方法:
- 在application.properties文件中定义:
spring.security.user.name=cybzc
spring.security.user.password=123
- 写一个配置类,这里的案例代码如下:
@Configuration
public class SecurityConfig extends WebSecurityConfigurerAdapter{
@Bean
PasswordEncoder passwordEncoder() {
return NoOpPasswordEncoder.getInstance();
}
/**
* 定义角色,用户名,密码方法
*/
@Override
protected void configure(AuthenticationManagerBuilder auth) throws Exception { auth.inMemoryAuthentication().withUser("cybtju").password("123456").roles("admin");
}
/**
* 配置过滤器,把CSS,JS等一些静态资源放行
*/
@Override
public void configure(WebSecurity web) throws Exception {
web.ignoring().antMatchers("/css/**","/js/**","/images/**");
}
/**
* 自定义登录页面
*/
@Override
protected void configure(HttpSecurity http) throws Exception { http.authorizeRequests().anyRequest().authenticated().and().formLogin().loginPage("/login.html").permitAll().and().csrf().disable();
}
}