目录
SpringSecurity Web 权限方案
设置登录系统的账号、密码
未认证请求跳转到登录页
基于角色或权限进行访问控制
hasAuthority 方法
hasAnyAuthority 方法
基于数据库实现权限认证
自定义 403 页面
SpringSecurity Web 权限方案
设置登录系统的账号、密码
方式一:在 application.properties spring.security.user.name = ezio spring.security.user.password = 1234 方式二:编写类实现接口@Service("userDetailsService")
public class UserDetailServiceImpl implements UserDetailsService {
@Override
public UserDetails loadUserByUsername(String username) throws UsernameNotFoundException {
// 权限
List auth = AuthorityUtils.commaSeparatedStringToAuthorityList("role");
return new User("ezio",new BCryptPasswordEncoder().encode("123"),auth);
}
}
@Configuration
public class configtest extends WebSecurityConfigurerAdapter {
@Autowired
private UserDetailsService userDetailsService;
@Bean
public PasswordEncoder passwordEncoder(){
return new BCryptPasswordEncoder();
}
// 没有配置用户名密码会来这里找到一个userDetailService对象
@Override
protected void configure(AuthenticationManagerBuilder auth) throws Exception {
auth.userDetailsService(userDetailsService).passwordEncoder(passwordEncoder());
}
}
未认证请求跳转到登录页 重写新的config方法,具体写法如下图
基于角色或权限进行访问控制
hasAuthority 方法
如果当前的主体具有指定的权限,则返回
true,
否则返回
false
添加一个控制器
给用户登录主体赋予权限
hasAnyAuthority 方法
如果当前的主体有任何提供的角色(给定的作为一个逗号分隔的字符串列表)的话,返回
true.
hasRole
方法
如果用户具备给定角色就允许访问
,
否则出现
403
。
如果当前主体具有指定的角色,则返回
true
。
基于数据库实现权限认证
查询用户后获得用户的所有角色添加到SimpleGrantedAuthority中,然后add到 list中
@Configuration
public class configtest extends WebSecurityConfigurerAdapter {
@Autowired
private UserDetailsService userDetailsService;
@Bean
public PasswordEncoder passwordEncoder(){
return new BCryptPasswordEncoder();
}
// 没有配置用户名密码会来这里找到一个userDetailService对象
@Override
protected void configure(AuthenticationManagerBuilder auth) throws Exception {
auth.userDetailsService(userDetailsService).passwordEncoder(passwordEncoder());
}
@Override
protected void configure(HttpSecurity http) throws Exception {
http.formLogin()
.usernameParameter("username")
.passwordParameter("password")
.loginPage("/toLogin") // 设置登陆页面
.loginProcessingUrl("/login") // 设置登陆后跳转的路径
.defaultSuccessUrl("/index").permitAll()
;
http.authorizeRequests()
.antMatchers("/toLogin",
"**/*.css"
).permitAll()
.antMatchers("/level1/**").hasRole("student")
.antMatchers("/level2/**").hasRole("teacher")
.antMatchers("/level3/**").hasRole("admin")
.anyRequest() // 任何请求
.authenticated(); //需要认证
}
}



