springBoot中Security的使用
需要有自动装配
@EnableWebSecurity
public class SecurityConfig extends WebSecurityConfigurerAdapter {
//链式编程
@Override
protected void configure(HttpSecurity http) throws Exception {
http.authorizeRequests()
.antMatchers("/").permitAll()
.antMatchers("/页面").hasRole("角色名1")
.antMatchers("/页面2").hasRole("角色名2");
//没有登录就会自动跳转到登录页(自带的)
//可以自定义如下:定制登录页
http.formLogin().loginPage("/toLogin").usernameParameter("userName").passwordParameter("passWord").loginProcessingUrl("/login");
//防止网站工具:get,post
http.csrf().disable();//关闭csrf功能,登陆失败肯存在的原因
//注销
http.logout().logoutSuccessUrl("/");
}
//认证
@Override
protected void configure(AuthenticationManagerBuilder auth) throws Exception {
auth.inMemoryAuthentication().passwordEncoder(new BCryptPasswordEncoder())
.withUser("userName1").password(new BCryptPasswordEncoder().encode("password1")).roles("角色名1","角色名2")
.and()
.withUser("userName2").password(new BCryptPasswordEncoder().encode("password2")).roles("角色名3","角色名4");
}
}
本文详细介绍了如何在SpringBoot项目中启用WebSecurity,实现自动装配和权限控制,包括URL权限设置、登录验证、CSRF防护及注销功能。同时涵盖了认证过程中的用户角色管理和默认登录页面定制。
1295

被折叠的 条评论
为什么被折叠?



