SpringBoot集成Security(二)----实现简单登陆
上篇文章已经搭建好了项目,那么现在就让我们来看看一些自定义配置吧。
创建一个WebSecurityConfig类继承于WebSecurityConfigurerAdapter,然后我们可以复写它的方法。
注意要添加@Configuration和@EnableWebSecurity注解。
为什么要添加EnableWebSecurity注解?
HttpSecurity自定义配置(配置拦截路径和角色)
@Override
protected void configure(HttpSecurity http) throws Exception {
http.authorizeRequests()
.antMatchers("/admin/**")
.hasRole("admin")
.antMatchers("/user/**")
.hasAnyRole("ADMIN", "USER")
.antMatchers("/superadmin/**")
.access("hasRole('ADMIN') and hasRole('MANAGER')")
.anyRequest().authenticated()
.and()
.formLogin() /*表单登陆相关配置*/
.loginPage() //自定义登陆界面
.loginProcessingUrl("/login") //登陆请求处理接口
.usernameParameter("name") //登陆接口传参用户名参数名
.passwordParameter("password") //登陆接口传参密码参数名
.successForwardUrl() //登陆成功跳转Url
.successHandler() //自定义登陆成功处理逻辑
.failureForwardUrl("/login") //登陆失败跳转Url
.failureHandler() //自定义登陆失败处理逻辑
.permitAll() //登陆处理的Url不进行拦截
.and()
.logout() //注销配置
.logoutUrl() //注销请求Url
.clearAuthentication(true) //是否清除身份信息
.invalidateHttpSession(true) //是否失效session
.addLogoutHandler() //添加自定义注销处理逻辑
.logoutSuccessUrl() //注销成功跳转Url
.logoutSuccessHandler() //注销成功处理逻辑
.permitAll() //注销Url放行
.rememberMe() //使用rememberMe功能
.and()
.csrf().disable();
}
WebSecurity自定义配置 (放行静态资源)
复写该方法用来放行一些不需要进行拦截的资源
@Override
public void configure(WebSecurity web) throws Exception {
web.ignoring()
.antMatchers("/static/**", "/swagger2/**");
}
基于内存的配置
inMemoryAuthentication()标明我们将使用内存的方法,后续用.withUser()进行用户名配置,用.password()进行密码配置,.roles()进行角色配置,多用户用.and()进行连接,.accountExpired()可以设置账户是否过期,.accountLocked()设置账户是否被锁定。
@Override
protected void configure(AuthenticationManagerBuilder auth) throws Exception {
auth.inMemoryAuthentication()
.withUser("admin")
.password("123456")
.roles("ADMIN", "USER")
.and()
.withUser("user")
.password("12321")
.roles("USER")
.accountExpired(false)
.accountLocked(false);
}
注意:如果使用了密码加密相应的需要更改密码为:
.password(passwordEncoder().encode(“123456”))