网站建设资讯

NEWS

网站建设资讯

SpringSecurity安全拦截基础实现-创新互联

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

创新互联长期为近千家客户提供的网站建设服务,团队从业经验10年,关注不同地域、不同群体,并针对不同对象提供差异化的产品和服务;打造开放共赢平台,与合作伙伴共同营造健康的互联网生态环境。为甘井子企业提供专业的成都做网站、成都网站制作,甘井子网站改版等技术服务。拥有十多年丰富建站经验和众多成功案例,为您定制开发。一:Spring Security授权认证登录实现 1.导入Maven依赖
org.springframework.bootspring-boot-starter-security2.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 {
        QueryWrapperqw = new QueryWrapper<>();
        qw.eq("username", username);
        SysUser user = userMapper.selectOne(qw);
        if (user == null) {
            throw new UsernameNotFoundException("用户不存在呀!!贴子");
        }
        //赋予权限
        System.out.println("授予权限!!"+username+"密码:"+user.getPassword());
        Listauths = AuthorityUtils.commaSeparatedStringToAuthorityList("hyq,admin,sb");
        return new User(user.getUsername(), new BCryptPasswordEncoder().encode(user.getPassword()), auths);
    }
}

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

你是否还在寻找稳定的海外服务器提供商?创新互联www.cdcxhl.cn海外机房具备T级流量清洗系统配攻击溯源,准确流量调度确保服务器高可用性,企业级服务器适合批量采购,新人活动首月15元起,快前往官网查看详情吧


网页标题:SpringSecurity安全拦截基础实现-创新互联
网站网址:http://njwzjz.com/article/dccdjd.html