SpringSecurity登录及权限管理

SpringSecurity实现登录及权限管理

https://www.bilibili.com/video/av75202601

/*代码来源及讲解: https://www.bilibili.com/video/av75202601*/


@EnableWebSecurity
public class Security extends WebSecurityConfigurerAdapter{
    //关闭CSRF功能接受GET请求
    http.csrf().disable();
    //定制输入页 真正的登录界面Login.html
    //usernameParamter,usernameParamter 获取自定义的表单的参数
    http.formLogin().loginPage("/toLogin").usernameParamter("user").usernameParamter("pwd").loginProcessingUrl("/login")
    //链式编程
    @Override
    protected void configure(HttpSecurity http) throws Exception{
        //设置不同的角色所能访问到的界面
        http.authorizeRequests()
                 .antMatchers("/").permitAll()
                 .antMatchers("/level1/**").hasRole("vip1")
                 .antMatchers("/level2/**").hasRole("vip2")
                 .antMatchers("/level3/**").hasRole("vip3");
     }
    //没有权限将会回到默认的登录界面 "/login"
    http.formLogin();
    //登出成功后返回指定页面
    http.logout().logoutSuccessUrl("/");
    //remberme 保存cookie两周
    //remberMeParamter 获取自定义的参数
    http.remberMe().remberMeParamter("rember");
    //认证 
    //role通过thymeleaf互动
    //根据用户的角色动态实现
    @Override
    protected void configure(AuthenticationManagerBuilder auth) thows Exception{
        /*现在是预设inMemoryAuthentication下有从数据库中获取的方法
          密码要使用加密后的格式,否则会报错 */
        auth.inMemoryAuthentication()
                 .withUser("username1").password("123456").roles("vip1,vip2")
                 .and()
                 .withUser("username1").password("123456").roles("vip3,vip2")
                 .and()
                 .withUser("username1").password("123456").roles("vip1,vip3")
                 .and()
    }
}

猜你喜欢

转载自www.cnblogs.com/chendichen/p/12313634.html