springboot + security 基本使用

发布时间:2022-06-27 发布网站:脚本宝典
脚本宝典收集整理的这篇文章主要介绍了springboot + security 基本使用脚本宝典觉得挺不错的,现在分享给大家,也给大家做个参考。

简单使用

依赖

        <dePEndency>
            <groupId>org.sPRingframework.boot</groupId>
            <artifactId>spring-boot-starter-securITy</artifactId>
        </dependency>

配置

创建配置类

@EnableWebSecurity // 该类开启 Security
public class MySecurityconfig extends WebSecurityConfigurerAdapter {

}

重写方法定义授权规则

  1. 可配置请求路径和角色
  2. 开启自带的登录功能 /login
  3. 开启自带的注销功能 /LOGout
  4. 开启记住我功能(存用户密码到session)
    @override
    protected void configure(HttpSecurity http) throws Exception {
        // 定制请求授权规则
        http.authorizeHttpRequests()
                .antMatchers("/").permitAll() // 所有用户都可访问
                .antMatchers("/level1/**").hasRole("user")
                .antMatchers("/level2/**").hasRole("user")
                .antMatchers("/level3/**").hasRole("admin");

        // 开启自动配置的登录功能(/login),重定向到 /login?error 表示登录失败
        http.forMLogin();

        // 开启自动配置的注销功能(/logout),并在注销成功后返回首页
        http.logout().logoutSuccessUrl("/");

        // 开启记住我功能
        http.rememberMe();
    }

重写方法定义认证规则

配置用户密码和角色

这里使用内存信息,数据库信息需要使用 auth.jdbcAuthentication() 方法

    @Override
    protected void configure(AuthenticationManagerBuilder auth) throws Exception {

        auth.inMemoryAuthentication().passwordEncoder(new BCryptPasswordEncoder())
                .withUser("admin").password(new BCryptPasswordEncoder().encode("admin")).roles("admin", "user")
                .and()
                .withUser("user").password(new BCryptPasswordEncoder().encode("user")).roles("user");
    }

脚本宝典总结

以上是脚本宝典为你收集整理的springboot + security 基本使用全部内容,希望文章能够帮你解决springboot + security 基本使用所遇到的问题。

如果觉得脚本宝典网站内容还不错,欢迎将脚本宝典推荐好友。

本图文内容来源于网友网络收集整理提供,作为学习参考使用,版权属于原作者。
如您有任何意见或建议可联系处理。小编QQ:384754419,请注明来意。