Spring Security安全拦截基础实现

Spring Security是基于Spring的一个安全管理框架。它相比Shiro,它的功能更丰富,社区资源也比Shiro更丰富!

一:Spring Security授权认证登录实现

1.导入Maven依赖

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

2.创建实体类User

package com.yq.pojo;

import com.baomidou.mybatisplus.annotation.TableName;

@TableName("sys_user")
public class SysUser {

  private long userId;
  private long deptId;
  private String username;
  private String nickName;
  private String gender;
  private String phone;
  private String email;
  private String avatarName;
  private String avatarPath;
  private String password;
  private String isAdmin;
  private long enabled;
  private String createBy;
  private String updateBy;
  private java.sql.Timestamp pwdResetTime;
  private java.sql.Timestamp createTime;
  private java.sql.Timestamp updateTime;
}

3.访问数据库并验证用户密码

@Mapper
public interface userMapper extends BaseMapper {
}

为了偷懒,我这里用的是Mybatis plus,哈哈哈哈

4.添加Spring Security的配置

@EnableGlobalMethodSecurity(prePostEnabled = true, securedEnabled = true)
@Configuration
public class SecurityConfig1 extends WebSecurityConfigurerAdapter {
    @Autowired
    private UserDetailsService userDetailsService;

    @Override
    protected void configure(AuthenticationManagerBuilder auth) throws Exception {
       auth.userDetailsService(userDetailsService).passwordEncoder(getPasswordEncoder());
    }
    //密码加密的类
    @Bean
    PasswordEncoder getPasswordEncoder(){
        return new BCryptPasswordEncoder();
    }

    @Override
    protected void configure(HttpSecurity http) throws Exception {
        http.exceptionHandling().accessDeniedPage("/logOut.html");//无权限时跳转的页面
        http.logout().logoutUrl("/gg").logoutSuccessUrl("static/index.html").permitAll();//注销登录
        http.formLogin()
                .loginPage("/index.html")//登录页面设置
                .loginProcessingUrl("/user/login")//指定登录页面要跳转到的页面路径
                .defaultSuccessUrl("/work/info/1/5")//默认的成功跳转页面路径
                .and().authorizeRequests()
                .antMatchers("/","/index.html").permitAll()
//                .antMatchers("/").hasAnyAuthority("sb")//拥有这个权限才能访问该页面
                .anyRequest().authenticated()
                .and().csrf().disable();//关闭csrf防护
    }
}

继承WebSecurityConfigurerAdapter 类并实现configure两个方法(同名),注入PasswordEncoder 类(密码加密类)

该类是对用户权限的配置

5.编写Service层实现UserDetailsService 

@Service("userDetailsService")
public class MyDetailsPassWord implements UserDetailsService {
    @Autowired
    private userMapper userMapper;


    @Override
    public UserDetails loadUserByUsername(String username) throws UsernameNotFoundException {
        QueryWrapper qw = new QueryWrapper<>();
        qw.eq("username", username);
        SysUser user = userMapper.selectOne(qw);
        if (user == null) {
            throw new UsernameNotFoundException("用户不存在呀!!贴子");
        }
        //赋予权限
        System.out.println("授予权限!!"+username+"密码:"+user.getPassword());
        List auths = AuthorityUtils.commaSeparatedStringToAuthorityList("hyq,admin,sb");
        return new User(user.getUsername(), new BCryptPasswordEncoder().encode(user.getPassword()), auths);
    }
}

实现loadUserByUsername()方法对用户进行验证是否存在并授权

你可能感兴趣的:(spring,安全,java)