初入门
核心依赖文件
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-security</artifactId>
</dependency>
当我们的web项目引入这个依赖之后 我们在访问请求 会弹出一个登录框
登录的默认名是user 密码则是随机生成打印在控制台上
如果不想随机生成 那么可以在application的配置文件中配置
#spring.security.user.name=wx
#spring.security.user.password=123
#spring.security.user.roles=admin
除了上面的配置外
还可以继承别的类 重写方法
/**
* @author w
*/
@Configuration //配置
public class MyWebSecurityConfig extends WebSecurityConfigurerAdapter {
@Bean
PasswordEncoder passwordEncoder(){
return NoOpPasswordEncoder.getInstance();//表示不对密码加密
}
@Override
protected void configure(AuthenticationManagerBuilder auth) throws Exception {
auth.inMemoryAuthentication()
.withUser("admin").password("123").roles("ADMIN","USER")//配置用户和用户角色
.and()
.withUser("jack").password("123").roles("USER")
.and()
.withUser("root").password("123").roles("ADMIN","DBA");
}
@Override
protected void configure(HttpSecurity http) throws Exception {
http.authorizeRequests()//开启HttpSecurity的配置
.antMatchers("/admin/**")//这行以及下面表示 访问这个路径 必须有下面的角色
.hasRole("ADMIN")
.antMatchers("/user/**")
.access("hasAnyRole('ADMIN','USER')")
.antMatchers("/db/**")
.access("hasRole('ADMIN') and hasRole('DBA')")
.anyRequest()//这行和下面一行表示表示除了前面定义的URL模式之外,用户访问其他的URL都必须认证后访问 .authenticated()
.and()
.formLogin()
.loginProcessingUrl("/login")//这行以及上两行表示开启表单登录
.permitAll()//表示和登录相关的不需要认证即可访问
.and()
.csrf()
.disable();
}
}