Spring-boot(2)-认证和鉴权-@EnableWebSecurity,WebSecurityConfigurerAdapter-AuthenticationManagerBuilder

不同权限的用户浏览不同的页面是基本要求。这就是用户的认证和鉴权。
如何创建springboot的module不再赘述,之后添加依赖,写Controller和config。此篇代码亲测有效,不过需要你有点springboot的基础,不然理解会有点困难。demo链接
1.POM.XMl
 

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


2.Controller 响应前端
 

@Controller
public class RouterController {

    //此处的参数可以是一个数组 文件没有后缀名
    //http://localhost:8080/
   @RequestMapping({"/","/index"})
    public String index()
   {
       System.out.println("index");
       return "index";

   }

   //http://localhost:8080/toLogin
   @RequestMapping("/toLogin")
    public String toLogin()
   {
       System.out.println("toLogin");
       return "views/login";
   }

   //传参数
   @RequestMapping("/level1/{id}")
    public String level1(@PathVariable("id") int id)
   {
       System.out.println("/level1/{id}");
       return "views/level1/"+id;
   }

    @RequestMapping("/level2/{id}")
    public String level2(@PathVariable("id") int id)
    {
        System.out.println("/level2/{id}");
        return "views/level2/"+id;
    }

    @RequestMapping("/level3/{id}")
    public String level3(@PathVariable("id") int id)
    {
        System.out.println("/level3/{id}");
        return "views/level3/"+id;
    }
    
}



3.Config  
   
@EnableWebSecurity,WebSecurityConfigurerAdapter 
   授权:HttpSecurity
 

@EnableWebSecurity
public class SecurityConfig extends WebSecurityConfigurerAdapter {
    @Override
    protected void configure(HttpSecurity http) throws Exception {
        http.authorizeRequests()
                .antMatchers("/").permitAll() //将注册和登录放行,在controller处理
                .antMatchers("/level1/**").hasRole("vip1")
                .antMatchers("/level2/**").hasRole("vip2")
                .antMatchers("/level3/**").hasRole("vip3");

        //没有权限默认会到登录页面
        http.formLogin();
        }
}

 鉴权:AuthenticationManagerBuilder 可以是内存中也可以从JDBC中。
 注意:1.内存中读取数据鉴权
            2.JDBC 中读取数据鉴权
            3.加密 BCryptPasswordEncoder()
 

protected void configure(AuthenticationManagerBuilder auth) throws Exception {
        auth.inMemoryAuthentication().passwordEncoder(new BCryptPasswordEncoder())
                .withUser("user1").password("123").roles("vip2", "vip3")
                .and()
                .withUser("user2").password("password").roles("vip1", "vip2", "vip3");
    }
    

 

posted @ 2020-08-20 21:02  jasmineTang  阅读(510)  评论(0)    收藏  举报