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

SpringBoot Security安装配置及Thymeleaf整合

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

SpringBoot Security安装配置及Thymeleaf整合

功能:解决web站点的登录,权限验证,授权等功能

优点:在不影响站点业务代码,可以权限的授权与验证横切到业务中

1、要添加的依赖


    
      org.springframework.boot
      spring-boot-starter-thymeleaf
    
    
    
      org.thymeleaf.extras
      thymeleaf-extras-springsecurity5
    
    
    
      org.springframework.boot
      spring-boot-starter-web
    
    
    
      org.springframework.boot
      spring-boot-starter-security
    

2、Security 下授权与验证的简单配置(Security下有登录,注销,记住我等功能,可以快速集成到自己的login页上)
Tis:如果template页中使用了 frame页,默认是不能访问的,需要添加 http.headers().frameOptions().sameOrigin();

@EnableWebSecurity
public class SecurityConfig extends WebSecurityConfigurerAdapter {
  //授权
  @Override
  protected void configure(HttpSecurity http) throws Exception {

    //请求授权的规则
    http.authorizeRequests()
 //.antMatchers("/tologin").permitAll() //登录页所有人都可以访问
 //.antMatchers("/admin/**").hasRole("admin1")
 .antMatchers("/admin/list").hasRole("admin1")
 .antMatchers("/admin/role").hasRole("admin1")
 .antMatchers("/admin/cate").hasRole("admin2")
 .antMatchers("/admin/rule").hasRole("admin2");

    // 项目里面使用了springSecurity spring Security下,X-frame-Options默认为DENY,非spring Security环境下,X-frame-Options的默认大多也是DENY,这种情况下,浏览器拒绝当前页面加载任何frame页面
    http.headers().frameOptions().sameOrigin();

    //登录页(Security默认有一个登录页)
    http.formLogin().permitAll()
 .loginPage("/tologin") //指定自定义的登录页地址
 .successForwardUrl("/admin/index") //登录成功跳转地址
 .usernameParameter("username").passwordParameter("password");//匹配自定义登录页的name元素名称

    // 开启注销功能,跳转到登录页
    http.csrf().disable(); //退出失败可能能的原因
    http.logout().logoutSuccessUrl("/tologin");

    //开启记住我功能,cookie 默认保存14天
    http.rememberMe()
 .rememberMeParameter("remember");//匹配自定义登录页的name元素名称

  }

  //认证
  @Override
  protected void configure(AuthenticationManagerBuilder auth) throws Exception {
    auth.inMemoryAuthentication()
 .passwordEncoder(new BCryptPasswordEncoder())//密码加密方式(有些版本的Security必须要指定)
 .withUser("root").password(new BCryptPasswordEncoder().encode("123")).roles("admin1","admin2","admin3")
 .and()
 .withUser("yeqiu").password(new BCryptPasswordEncoder().encode("123")).roles("admin1")
 .and()
 .withUser("admin").password(new BCryptPasswordEncoder().encode("123")).roles("admin2");

  }
}

3、Security 和 Thymeleaf 页面整合(添加依赖:thymeleaf-extras-springsecurity)







  ,您好 您的身份是
    
  


  • 权限管理
  • 以上就是本文的全部内容,希望对大家的学习有所帮助,也希望大家多多支持考高分网。

    转载请注明:文章转载自 www.mshxw.com
    本文地址:https://www.mshxw.com/it/130004.html
    我们一直用心在做
    关于我们 文章归档 网站地图 联系我们

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

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