SpringSecurity简单配置教程

SpringSecurity

web开发中,安全第一位,过滤器,拦截器,安全应该在设计之初考虑.

shiro,SpringSecurity:很像

简介

是针对Spring项目的安全框架,也是Springboot底层安全模块默认的技术选型, 他可以实行强大的web安全控制,对于安全控制我们只需要引入spring-boot-stater-security模块,进行少量的配置,即可实现欠打的安全管理

  • WebSecurityConfigurerAdapter:自定义Secruity策略
  • AuthenticationManagerBuilder:自定义认证策略
  • @EnableWebSecurity:开启WebSecurity模式

“认证” (Authentication)

“授权” (Authoriztion)

依赖
<!--secruity-->
<dependency>
    <groupId>org.springframework.boot</groupId>
    <artifactId>spring-boot-starter-security</artifactId>
</dependency>
<!--thymeleaf security整合-->
<dependency>
    <groupId>org.thymeleaf.extras</groupId>
    <artifactId>thymeleaf-extras-springsecurity5</artifactId>
    <version>3.0.4.RELEASE</version>
</dependency>
不使用数据库配置
import org.springframework.security.config.annotation.authentication.builders.AuthenticationManagerBuilder;
import org.springframework.security.config.annotation.web.builders.HttpSecurity;
import org.springframework.security.config.annotation.web.configuration.EnableWebSecurity;
import org.springframework.security.config.annotation.web.configuration.WebSecurityConfigurerAdapter;
import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder;

@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");
        //没有权限默认返回登录页面
        //定制登录页 passwordParameter前端的与后面对照  loginProcessingUrl提交表单的action对照
        http.formLogin().loginPage("/toLogin").passwordParameter("pwd").loginProcessingUrl("/login");
        //防止网站工具
        http.csrf().disable();//关闭cerf功能,登录失败肯定存在的原因
        //注销 注销成功返回首页
        http.logout().logoutSuccessUrl("/");
        //开启记住我功能 cookie,默认保存两周
        http.rememberMe();
    }
    //认证
    @Override
    protected void configure(AuthenticationManagerBuilder auth) throws Exception {
        auth.inMemoryAuthentication().passwordEncoder(new BCryptPasswordEncoder())
            .withUser("lazy").password(new BCryptPasswordEncoder().encode("123456")).roles("vip1","vip2")
            .and()
            .withUser("root").password(new BCryptPasswordEncoder().encode("123456")).roles("vip1","vip2","vip3")
            .and()
            .withUser("guset").password(new BCryptPasswordEncoder().encode("123456")).roles("vip1");
    }
}
连接数据库配置

**关键:**实现UserDetailsService

@Component
public class CustomUserDetailsService implements UserDetailsService {

    @Autowired
    UserService userService;
    @Autowired
    PasswordEncoder passwordEncoder;

    @Override
    public UserDetails loadUserByUsername(String s) throws UsernameNotFoundException {
        //根据登录的用户名 查询出用户信息对象
        UserInfo userInfo = userService.queryByName(s);
        //判断用户信息对象是否为空
        if (userInfo == null) {
            throw new UsernameNotFoundException("用户不存在");
        }
        //获取角色
        String roles = userInfo.getRole();
        //角色集合
        List<GrantedAuthority> authorities = new ArrayList<>();
        //多角色处理,根据数据库存储的情况进行分割
        for (String role : roles.split(",")) {
            //角色这里角色必须以ROLE_开头,比如数据库中,前端中不需要.
            authorities.add(new SimpleGrantedAuthority("ROLE_" + role));
        }
        //因为数据库中密码是明文所以需要加密一下.如果不是则可直接根据配置的加密类型填写密文
        return new User(userInfo.getName(), passwordEncoder.encode(userInfo.getPassword()), authorities);
    }
}

配置类

@EnableWebSecurity
public class SecurityConfig extends WebSecurityConfigurerAdapter {

    @Autowired
    CustomUserDetailsService customUserDetailsService;

    @Bean
    public PasswordEncoder getPasswordEncoder(){
        return new BCryptPasswordEncoder();
    }

    //认证
    @Override
    protected void configure(AuthenticationManagerBuilder auth) throws Exception {
        //从数据库读取的信息
        auth.userDetailsService(customUserDetailsService)
            .passwordEncoder(getPasswordEncoder());
    }

    @Override
    protected void configure(HttpSecurity http) throws Exception {
        //首页可以访问,功能页面需要权限才可以
        http.authorizeRequests()
            .antMatchers("/").permitAll()
            .antMatchers("/level1/**").hasRole("vip1")
            .antMatchers("/level2/**").hasRole("vip2")
            .antMatchers("/level3/**").hasRole("vip3");

        //没有权限默认返回登录页面
        //定制登录页 passwordParameter前端的与后面对照  loginProcessingUrl提交表单的action对照
        http.formLogin()
            .loginPage("/toLogin")
            .passwordParameter("pwd")
            .loginProcessingUrl("/login");

        //关闭cerf功能,登录失败肯定存在的原因
        http.csrf().disable();

        //注销 注销成功返回首页
        http.logout().logoutSuccessUrl("/");

        //开启记住我功能 cookie,默认保存两周
        http.rememberMe();
    }
}

  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值