栏目分类:
子分类:
返回
名师互学网用户登录
快速导航关闭
当前搜索
当前分类
子分类
实用工具
热门搜索
名师互学网 > IT > 软件开发 > 后端开发 > Java

SpringSecurity讲解与实践——用户认证与授权、注销、权限限制、记住我、首页定制

Java 更新时间: 发布时间: IT归档 最新发布 模块sitemap 名妆网 法律咨询 聚返吧 英语巴士网 伯小乐 网商动力

SpringSecurity讲解与实践——用户认证与授权、注销、权限限制、记住我、首页定制

SpringSecurity讲解与实践(代码仅供学习)
  • 下载本文的SpringSecurity实战代码链接:https://download.csdn.net/download/shooter7/37060883
说明

SpringSecurity讲解与实践,主要用于实现以下的功能:

  • 用户认证、授权
  • 注销、权限限制
  • 记住我、首页定制

由于是SpringBoot的一个现成的框架,所以我们需要在项目的config的文件夹下面新建一个SecurityConfig配置的类,用于实现配置以上的功能,具体的一些参数需要我们多看看源码。

安全
  • 做安全,应该在网站设计之初考虑的,因为架构一旦确定,才考虑安全,会改动比较多的代码
SpringSecurity
  • 功能权限
  • 访问权限
  • 菜单权限
  • 之前是用的拦截器、过滤器:大量的原生代码,过于冗余
配置类关键代码
@EnableWebSecurity
public class SecurityConfig extends WebSecurityConfigurerAdapter {
    //授权
    @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().loginPage("/toLogin").usernameParameter("ugh").passwordParameter("upwd").loginProcessingUrl("/login");
        http.formLogin();
        //注销,开启了注销
        http.csrf().disable();  //关闭csrf(防跨站攻击)功能,登出失败可能存在的原因
        http.logout().logoutSuccessUrl("/");
        //开启记住我的功能,默认保存2周的时间,自定义接受前端的参数
        http.rememberMe().rememberMeParameter("remember");
    }
    //认证 springboot2.1x 可以直接使用
    //密码编码:PasswordEncoder
    //在Spring Security5.0+中新增了很多加密的方式
    @Override
    protected void configure(AuthenticationManagerBuilder auth) throws Exception {
        //数据正常在数据库中被读取
        auth.inMemoryAuthentication().passwordEncoder(new BCryptPasswordEncoder())
                .withUser("kuangshen").password(new BCryptPasswordEncoder().encode("123456")).roles("vip2","vip3")
                .and()
                .withUser("root").password(new BCryptPasswordEncoder().encode("123456")).roles("vip2","vip3","vip1")
                .and()
                .withUser("guest").password(new BCryptPasswordEncoder().encode("123456")).roles("vip1");
    }
}
代码实践
  • 代码实践中有简单的登录页面,以及登录进去的首页,首页中有不同等级会员才会有的模块,需要进行用户的认证和授权才能够进入,以及实现一些权限的限制,注销,记住我、首页定制等的功能。


    注:如果出现不同权限进去还是能看到所有的level。那就可能是Springboot的版本的问题,版本过高,我们可以在pom.xml将其版本调为2.0.9.RELEASE。
转载请注明:文章转载自 www.mshxw.com
本文地址:https://www.mshxw.com/it/424029.html
我们一直用心在做
关于我们 文章归档 网站地图 联系我们

版权所有 (c)2021-2022 MSHXW.COM

ICP备案号:晋ICP备2021003244-6号