spring security 配置

导入依赖


        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-security</artifactId>
        </dependency>

然后创建配置类

配置类继承 WebSecurityConfigurerAdapter 类 然后通过 @EnableWebSecurity 注释 开启springsecurity


@EnableWebSecurity
public class MySecurityConfig extends WebSecurityConfigurerAdapter {

然后重写 WebSecurityConfigurerAdapter 中的相关方法 AuthenticationManagerBuilder (认证) HttpSecurity(授权)

HttpSecurity 授权 规定什么权限的人能够进入什么环境


     // 授权
    @Override
    protected void configure(HttpSecurity http) throws Exception {
        http.authorizeRequests().antMatchers("/").permitAll()
                .antMatchers("/level1/**").hasRole("VIP1")
                .antMatchers("/level2/**").hasRole("VIP2")
                .antMatchers("/level3/**").hasRole("VIP3");

        http.formLogin().usernameParameter("user").passwordParameter("pwd")
                .loginPage("/userlogin");/*.loginProcessingUrl("/userlogin")*/;

        //springsecurity 默认以 /login 的post请求 处理登录 当使用 .loginPage 后会以loginPage的 post 处理登录信息
        // 如果想改变默认可以使用 loginProcessingUrl 去指定想要的页面 的post形式 处理登录
        // .loginPage() 重定向跳转自定义的登录页面
        
        http.logout().logoutSuccessUrl("/");
        //注销 注销以后默认实在/login页面 需要.loginSuccessUrl() 配置想要跳转重定向的页面

        http.rememberMe().rememberMeParameter("remember");
        // 记住我 功能 rememberMe 以后是创建在默认的/login页面中的 如果需要自定义页面 得在自定义的页面中 创建一个标签name的值与.rememberMeParameter() 中的值一致 ;

    }

AuthenticationManagerBuilder 认证


    // 认证
    @Override
    protected void configure(AuthenticationManagerBuilder auth) throws Exception {
        auth.inMemoryAuthentication() // 内存存储
                .passwordEncoder(new BCryptPasswordEncoder())  //新版本需要对密码进行一个 BCrypt 加密
                .withUser("zhangsan") // 创建一个用户
                .password(new BCryptPasswordEncoder().encode("123456")) // 创建它的密码
                .roles("VIP1","VIP2")  // 给他的角色权限 与 授权类中的配置相互配合
                .and()
                .passwordEncoder(new BCryptPasswordEncoder())
                .withUser("lisi")
                .password(new BCryptPasswordEncoder().encode("123456"))
                .roles("VIP1","VIP3")
                .and()
                .passwordEncoder(new BCryptPasswordEncoder())
                .withUser("wangwu")
                .password(new BCryptPasswordEncoder().encode("123456"))
                .roles("VIP1","VIP3");

        

    }

猜你喜欢

转载自www.cnblogs.com/nineberg/p/12468992.html