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

Springboot-SpringSecurity知识点

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

Springboot-SpringSecurity知识点

Spring Security两个主要目标:认证(Authentication)、授权(Authorization)

1.导入依赖


   org.springframework.boot
   spring-boot-starter-security

2.配置一个Security的配置类

@EnableWebSecurity//开启security模式
public class SecurityConfig extends WebSecurityConfigurerAdapter {
   //链式编程
    //授权
    @Override
    protected void configure(HttpSecurity http) throws Exception {
        http.authorizeRequests().antMatchers("/").permitAll()//权限请求,首页都可以允许访问
                .antMatchers("/leven1/**").hasRole("vip1");//用户角色为vip1才允许访问
        //读源码发现,登录默认登录页面/login,认证失败走login?error
        //自己的页面代替SpringSecurity的login页面, .loginPage("/tologin")
        //                     跳转真实的页面加上  .loginProcessingUrl("/login")
        http.formLogin().loginPage("/tologin");

        //开启注销功能,并跳到主页
        http.logout().logoutSuccessUrl("/");
        http.csrf().disable();//关闭csrf功能:跨站请求伪造,默认只能通过post方式提交logout请求  登出失败的原因
        http.rememberMe().rememberMeParameter("remember");//记住我功能, .rememberMeParameter("remember")自定义标签

    }
    //认证
    @Override
    protected void configure(AuthenticationManagerBuilder auth) throws Exception {
       //在内存中读,也可以在数据库中读
        auth.inMemoryAuthentication().passwordEncoder(new BCryptPasswordEncoder())//加密方式
                .withUser("aa").password(new BCryptPasswordEncoder().encode("123456")).roles("vip1","vip2")
                .and()
                .withUser("ww").password(new BCryptPasswordEncoder().encode("456")).roles("vip4");
    }
}

一般在thymeleaf中搭配:

1.引入启动类

 
        
            org.thymeleaf.extras
            thymeleaf-extras-springsecurity5
            3.0.4.RELEASE
        

2.常用标签

 


  
当前用户没有被认证/认证失败
当前用户认证成功
当前用户有vip1的权限的情况下
转载请注明:文章转载自 www.mshxw.com
本文地址:https://www.mshxw.com/it/726686.html
我们一直用心在做
关于我们 文章归档 网站地图 联系我们

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

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