1、创建sprogboot项目,注入依赖
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-security</artifactId>
</dependency>
2、启动项目之后,控制台会打印密码(由于我们没有自定义用户名和密码,所以框架会生成UUID的默认密码。默认用户名为user),然后请求项目任何一个地址,都会跳转默认的登录页login(这也是框架自己支持的)
3、怎么自定义用户名/密码
第一种方式就是在配置文件中增加对应配置:
spring.security.user.name=test
spring.security.user.password=11111111
第二种方式就是在配置类中配置,代码如下:
@Configuration
public class SecurityConfig extends WebSecurityConfigurerAdapter {
/**
* 设置密码加密
* @return 返回加密后的密码
*/
@Bean
PasswordEncoder passwordEncoder() {
return NoOpPasswordEncoder.getInstance();
}
/**
* 认证配置
* @param auth 认证
* @throws Exception
*/
@Override
protected void configure(AuthenticationManagerBuilder auth) throws Exception {
// 在内存中配置账户和密码
auth.inMemoryAuthentication()
.withUser("lingdong")
.password("22222222")
.roles("admin");
}
}
其中,在配置类中配置的属性优先级会高于配置文件
4、怎么自定义登录页(框架自己支持的登录页太简单),也可以理解为怎么开放登录页面和登录接口
@Override
protected void configure(HttpSecurity http) throws Exception {
http.authorizeRequests()
.anyRequest().authenticated()
.and()
.formLogin()
.loginPage("/district/getDistrictInfoById?id=87875989476085760")
.permitAll()
.and()
.csrf()
.disable();
}
上述配置也是在SecurityConfig配置类中配置,这段配置代表开放“/district/getDistrictInfoById?id=87875989476085760”这个接口,经测试,任何请求都会转发到这个接口
5、怎么配置不拦截静态资源
/**
* 取消静态拦截
* @param web
* @throws Exception
*/
@Override
public void configure(WebSecurity web) throws Exception {
// 忽略某些路径
web.ignoring().antMatchers("/css/**", "/js/**", "/images/**");
}