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");
    }
    

 

  • 1
    点赞
  • 2
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值