Spring Security自定义登录认证

一.准备环境
开发工具:Intellij IDEA,Gradle,JDK14,MySql

二.创建项目
创建Spring Initializr项目
在这里插入图片描述

在这里插入图片描述
依赖选择Spring WEB,Mysql Driver,Spring Security

检查Gradle依赖!

plugins {
    id 'org.springframework.boot' version '2.4.3'
    id 'io.spring.dependency-management' version '1.0.11.RELEASE'
    id 'java'
}

group = 'cn.au'
version = '0.0.1-SNAPSHOT'
sourceCompatibility = '11'

repositories {
    mavenCentral()
}

dependencies {
    implementation 'org.springframework.boot:spring-boot-starter-security'
    implementation 'org.springframework.boot:spring-boot-starter-thymeleaf'
    implementation 'org.springframework.boot:spring-boot-starter-web'
    implementation 'org.thymeleaf.extras:thymeleaf-extras-springsecurity5'
    runtimeOnly 'mysql:mysql-connector-java'
    testImplementation 'org.springframework.boot:spring-boot-starter-test'
    testImplementation 'org.springframework.security:spring-security-test'
    implementation group: 'tk.mybatis', name: 'mapper', version: '4.1.5'
    implementation group: 'org.mybatis.spring.boot', name: 'mybatis-spring-boot-starter', version: '2.1.4'
}

test {
    useJUnitPlatform()
}

数据库:
用户表:user
在这里插入图片描述

权限表:role
在这里插入图片描述

用户权限关联表:user_role
在这里插入图片描述

三.项目开发

1.配置application.properties

//数据库相关配置
spring.datasource.driver-class-name=com.mysql.cj.jdbc.Driver
spring.datasource.username=root
spring.datasource.password=root
spring.datasource.url=jdbc:mysql://localhost:3306/springs?useUnicode=true&characterEncoding=UTF-8&serverTimezone=UTC

mybatis.mapper-locations=classpath:mapper/*Mapper.xml  //mapper地址
mybatis.type-aliases-package=cn.au.ssslogin.entity  //实体类地址

2.启动类

@MapperScan(value = "cn.au.ssslogin.mapper")
@SpringBootApplication
public class SssLoginApplication {

//查询用户数据
//    @Autowired
//    SysUserMapper userMapper;

    public static void main(String[] args) {
        SpringApplication.run(SssLoginApplication.class, args);
    }


//插入数据库数据
//@PostConstruct
//    public void jdbcInit(){
//        //密码加密
//        PasswordEncoder encoder=new BCryptPasswordEncoder();
//        //创建角色权限集合
//        List<GrantedAuthority> list=new ArrayList<>();
//        //获取时间
//        Date curDate=new Date();
//        //设置角色权限
//        GrantedAuthority authority=new SimpleGrantedAuthority("ROLE_"+"ADMIN");
//        //加入集合
//        list.add(authority);
//        SysUser user=new SysUser(
//                "zhang",encoder.encode("zhang"),"zhangsan",true,true
//                ,true,true,curDate,curDate,list
//        );
//        userMapper.insertSysUser(user);
//
//    }
}

3.创建实体类

	权限表
/**
 * 权限表
 */
public class SysRole {
    private Integer id; //主键 id
    private String name; //权限
    private String memo; // 权限名称

    public SysRole() {
      }

    public SysRole(Integer id, String name, String memo) {
        this.id = id;
        this.name = name;
        this.memo = memo;
    }

    @Override
    public String toString() {
        return "SysRole{" +
                "id=" + id +
                ", name='" + name + '\'' +
                ", memo='" + memo + '\'' +
                '}';
    }

    public Integer getId() {
        return id;
    }

    //get And Set
}

用户表(自定义实现UserDetails)
提供Get Set方法
实现UserDetails

/**
 * 用户表
 */
public class SysUser implements UserDetails {
    private Integer id; //用户id
    private String username; //用户名
    private String password;//密码
    private String realname;//昵称

    private boolean isExpired;//账号是否过期
    private boolean isLocked;//账号是否锁定
    private boolean isCredentials;//证书是否过期
    private boolean isEnabled;//账号是否启用

    private Date createTime;//注册时间
    private Date loginTime;//登陆时间

    private List<GrantedAuthority> authorities;

    public SysUser(String username, String password, String realname, boolean isExpired, boolean isLocked, boolean isCredentials, boolean isEnabled, Date createTime, Date loginTime, List<GrantedAuthority> authorities) {
        this.username = username;
        this.password = password;
        this.realname = realname;
        this.isExpired = isExpired;
        this.isLocked = isLocked;
        this.isCredentials = isCredentials;
        this.isEnabled = isEnabled;
        this.createTime = createTime;
        this.loginTime = loginTime;
        this.authorities = authorities;
    }

    public void setUsername(String username) {
        this.username = username;
    }

    public void setPassword(String password) {
        this.password = password;
    }

    public String getRealname() {
        return realname;
    }

    public void setRealname(String realname) {
        this.realname = realname;
    }

    public boolean isExpired() {
        return isExpired;
    }

    public void setExpired(boolean expired) {
        isExpired = expired;
    }

    public boolean isLocked() {
        return isLocked;
    }

    public void setLocked(boolean locked) {
        isLocked = locked;
    }

    public boolean isCredentials() {
        return isCredentials;
    }

    public void setCredentials(boolean credentials) {
        isCredentials = credentials;
    }

    public void setEnabled(boolean enabled) {
        isEnabled = enabled;
    }

    public Date getCreateTime() {
        return createTime;
    }

    public void setCreateTime(Date createTime) {
        this.createTime = createTime;
    }

    public Date getLoginTime() {
        return loginTime;
    }

    public void setLoginTime(Date loginTime) {
        this.loginTime = loginTime;
    }

    public SysUser() {
    }


    @Override
    public Collection<? extends GrantedAuthority> getAuthorities() {
        return authorities;
    }

    @Override
    public String getPassword() {
        return password;
    }

    @Override
    public String getUsername() {
        return username;
    }

    @Override
    public boolean isAccountNonExpired() {
        return isExpired;
    }

    @Override
    public boolean isAccountNonLocked() {
        return isLocked;
    }

    @Override
    public boolean isCredentialsNonExpired() {
        return isCredentials;
    }

    @Override
    public boolean isEnabled() {
        return isEnabled;
    }

    public Integer getId() {
        return id;
    }

    public void setId(Integer id) {
        this.id = id;
    }

    public void setAuthorities(List<GrantedAuthority> authorities) {
        this.authorities = authorities;
    }
}

4.创建Mapper类
权限查询Mapper

/**
 * 权限查询
 * 
 */
@Repository
public interface SysRoleMapper {
//通过UserId查询对应用户权限关联
    List<SysRole> selectRoleByUsername(Integer id);
}

对应Mapper XML文件

<?xml version="1.0" encoding="UTF-8" ?>
<!DOCTYPE mapper
        PUBLIC "-//mybatis.org//DTD Mapper 3.0//EN"
        "http://mybatis.org/dtd/mybatis-3-mapper.dtd">
<mapper namespace="cn.au.ssslogin.mapper.SysRoleMapper">
<!--表与实体类关联-->
    <resultMap id="roleMapper" type="cn.au.ssslogin.entity.SysRole">
        <id column="id" property="id"/>
        <result column="rolename" property="name"/>
        <result column="rolememo" property="memo"/>
    </resultMap>

    <select id="selectRoleByUsername" resultMap="roleMapper">
        SELECT r.id,r.rolename,r.rolememo FROM `sys_role` r, `sys_user_role` ur WHERE ur.roleid=r.id AND userid=#{id}
    </select>
</mapper>

用户增加查询Mapper

 @Repository
public interface SysUserMapper {
    int insertSysUser(SysUser user);
    SysUser selectSysUser(String username);
}

对应xml配置

<?xml version="1.0" encoding="UTF-8" ?>
<!DOCTYPE mapper
        PUBLIC "-//mybatis.org//DTD Mapper 3.0//EN"
        "http://mybatis.org/dtd/mybatis-3-mapper.dtd">
<mapper namespace="cn.au.ssslogin.mapper.SysUserMapper">
    <resultMap id="userMapper" type="cn.au.ssslogin.entity.SysUser">
        <id column="id" property="id"/>
        <result column="username" property="password"/>
        <result column="password" property="password"/>
        <result column="realname" property="realname"/>
        <result column="isenable" property="isEnabled"/>
        <result column="islock" property="isLocked"/>
        <result column="iscredentials" property="isCredentials"/>
        <result column="createtime" property="createTime"/>
        <result column="logintime" property="loginTime"/>
        <result column="isexpired" property="isExpired"/>
    </resultMap>
    
    <insert id="insertSysUser" >
        INSERT INTO sys_user(username,password,realname,isenable,islock,iscredentials,createtime,logintime,isexpired)
        VALUES(#{username},#{password},#{realname},#{isEnabled},#{isLocked},#{isCredentials},#{createTime},#{loginTime},#{isExpired})
    </insert>

    <select id="selectSysUser" resultMap="userMapper">
        SELECT id,username,password,realname,isenable,islock,iscredentials,createtime,logintime,isexpired
        FROM sys_user WHERE username=#{username}
    </select>
</mapper>

4.实现UserDetaIlsService创建Service层

@Service
public class JdbcUserDetailsService implements UserDetailsService {
    @Autowired
    private SysRoleMapper roleMapper;
    @Autowired
    private SysUserMapper userMapper;


    @Override
    public UserDetails loadUserByUsername(String username) throws UsernameNotFoundException {
		//根据Security返回的Username 查询用户名
        SysUser user = userMapper.selectSysUser(username);
        if (user!=null){
            List<SysRole> roles = roleMapper.selectRoleByUsername(user.getId());
            List<GrantedAuthority> authorities = new ArrayList<>();
            String roleName="";
            for (SysRole role:roles) {
                roleName=role.getName();
                GrantedAuthority authority=new 
                //设置权限前面必需要加入ROLE_
                SimpleGrantedAuthority("ROLE_"+roleName);
                authorities.add(authority);
            }
            user.setAuthorities(authorities);
        }
        return user;
    }
}

5.创建Security配置类

@Configuration
@EnableWebSecurity
public class SpringSecurityConfig extends WebSecurityConfigurerAdapter {


  @Qualifier("jdbcUserDetailsService")
  @Autowired
    private UserDetailsService userDetailsService;
    @Override
    protected void configure(AuthenticationManagerBuilder auth) throws Exception {
        auth.userDetailsService(userDetailsService).passwordEncoder(new BCryptPasswordEncoder());

    }

  @Override
  protected void configure(HttpSecurity http) throws Exception {
  		//设置白名单地址
        http.authorizeRequests().antMatchers("/","/toLogin","/login")
                .permitAll()
                //页面设置对应访问权限
                .antMatchers("/access/user").hasRole("USER")
                .antMatchers("/access/userA").hasRole("ADMIN")
                .anyRequest().authenticated().and().formLogin()
                //设置登陆页面
                .loginPage("/toLogin")
                //设置登录提交地址
                .loginProcessingUrl("/login")
                //设置错误页面
                .failureUrl("/error.html")
                //禁用跨域访问
                .and().csrf().disable();
  }

  @Override
  public void configure(WebSecurity web) throws Exception {

  }
}
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 2
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 2
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值