SpringBoot+Spring security+Mybatis 完整代码

前言

本项目使用Spring-Boot 2.1.1+Spring-Security 5.2.1+Mybatis 3.5.3搭建,实现从数据库中取用户信息完成登陆。

实现

数据库结构

image-20200108101149094

java代码

对应数据库需要2个实体类:SysRole,SysUser

SysRole.java

package com.sbk.pojo;

import lombok.Data;

@Data
public class SysRole {
    private Integer id;

    private String name;

    public Integer getId() {
        return id;
    }

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

    public String getName() {
        return name;
    }

    public void setName(String name) {
        this.name = name == null ? null : name.trim();
    }
}

SysUser.java

package com.sbk.pojo;

import lombok.Data;

import java.util.List;
@Data
public class SysUser {
    private Integer id;

    private String username;

    private String password;

    private List<SysRole> roles;

    public Integer getId() {
        return id;
    }

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

    public String getUsername() {
        return username;
    }

    public void setUsername(String username) {
        this.username = username == null ? null : username.trim();
    }

    public String getPassword() {
        return password;
    }

    public void setPassword(String password) {
        this.password = password == null ? null : password.trim();
    }
}

写一个根据用户名查询user 和 roleName的方法:

SysUserMapper.java

package com.sbk.mapper;


import com.sbk.pojo.SysUser;
import org.apache.ibatis.annotations.Mapper;

@Mapper
public interface SysUserMapper {

    SysUser findByUserName(String username);
}

SysUserMapper.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="com.sbk.mapper.SysUserMapper">
    <resultMap id="userMap" type="com.sbk.pojo.SysUser">
        <id property="id" column="id"/>
        <result property="username" column="username"/>
        <result property="password" column="password"/>
        <collection property="roles" ofType="com.sbk.pojo.SysRole">
            <result column="name" property="name"/>
        </collection>

    </resultMap>
    <select id="findByUserName" parameterType="String" resultMap="userMap">
        select u.*
        ,r.name
        from Sys_User u
        LEFT JOIN sys_role_user sru on u.id= sru.Sys_User_id
        LEFT JOIN Sys_Role r on sru.Sys_Role_id=r.id
        where username= #{username}
    </select>
</mapper>

UserService.java

package com.sbk.service;

import com.sbk.pojo.SysUser;

/**
 * @author Bokai Sun
 * @version 1.0
 * @date 2020/1/7 17:26
 */
public interface UserService {
    SysUser findByUserName(String username);
}

UserServiceImpl.java

package com.sbk.service.impl;

import com.sbk.mapper.SysUserMapper;
import com.sbk.pojo.SysUser;
import com.sbk.service.UserService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

/**
 * @author Bokai Sun
 * @version 1.0
 * @date 2020/1/7 17:27
 */
@Service
public class UserServiceImpl implements UserService {
    @Autowired
    SysUserMapper sysUserMapper;

    @Override
    public SysUser findByUserName(String username) {
        return sysUserMapper.findByUserName(username);
    }
}

再写个Controller用于页面跳转

PageController

package com.sbk.controller;

import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;

/**
 * @author Bokai Sun
 * @version 1.0
 * @date 2019/12/27 15:28
 */

@RequestMapping(value = "/")
@Controller
public class PageController {
    @RequestMapping(value = "{page}", method = RequestMethod.GET)
    public String goPage(@PathVariable("page") String page) {
        return page;
    }

}

到这一步我们就做好了基础的准备工作了,接下来就是开始配置security了。

WebSecurityConfig

package com.sbk.config;

import com.sbk.service.CustomUserService;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
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.core.userdetails.UserDetailsService;
import org.springframework.security.crypto.password.NoOpPasswordEncoder;
import org.springframework.security.crypto.password.PasswordEncoder;

/**
 * @author Bokai Sun
 * @version 1.0
 * @date 2020/1/7 17:34
 */
@Configuration
@EnableWebSecurity
public class WebSecurityConfig extends WebSecurityConfigurerAdapter {

    @Bean
    UserDetailsService customUserService() { //注册UserDetailsService 的bean
        return new CustomUserService();
    }

    @Override
    protected void configure(AuthenticationManagerBuilder auth) throws Exception {
        auth.userDetailsService(customUserService()); //user Details Service验证

    }

    @Override
    protected void configure(HttpSecurity http) throws Exception {
        http.authorizeRequests()
                .antMatchers("/", "/index", "/about", "/style/**").permitAll()
                .anyRequest().authenticated() //任何请求,登录后可以访问
                .and()
                .formLogin()
//                .loginPage("/login")
//                .failureUrl("/login?error")
//                .permitAll() //登录页面用户任意访问
                .and()
                .logout().permitAll(); //注销行为任意访问
    }

    @Bean
    public static PasswordEncoder passwordEncoder() {
        return NoOpPasswordEncoder.getInstance();//不对密码进行加密
    }
}

CustomUserService

package com.sbk.service;

import com.sbk.pojo.SysRole;
import com.sbk.pojo.SysUser;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.core.authority.SimpleGrantedAuthority;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.core.userdetails.UsernameNotFoundException;
import org.springframework.stereotype.Service;

import java.util.ArrayList;
import java.util.List;

/**
 * @author Bokai Sun
 * @version 1.0
 * @date 2020/1/7 17:34
 */
@Service
public class CustomUserService implements UserDetailsService {
    @Autowired
    UserService userService;

    @Override
    public UserDetails loadUserByUsername(String username) { //重写loadUserByUsername 方法获得 userdetails 类型用户
        System.out.println(username);
        SysUser user = userService.findByUserName(username);
        if (user == null) {
            throw new UsernameNotFoundException("用户名不存在");
        }
        List<SimpleGrantedAuthority> authorities = new ArrayList<>();
        //用于添加用户的权限。只要把用户权限添加到authorities 就万事大吉。
        for (SysRole role : user.getRoles()) {
            authorities.add(new SimpleGrantedAuthority(role.getName()));
            System.out.println(role.getName());
        }
        return new org.springframework.security.core.userdetails.User(user.getUsername(),
                user.getPassword(), authorities);
    }
}


然后就可以运行了。

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

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值