欢迎您访问程序员文章站本站旨在为大家提供分享程序员计算机编程知识!
您现在的位置是: 首页

springboot+springsecurity+mybatis实现一个登录、注册、主界面的权限管理

程序员文章站 2022-04-11 13:55:54
...

项目源码

百度网盘:链接: https://pan.baidu.com/s/17gZh2jOBa8MN1eAclduv-Q.提取码:lkyc

导入需要的jar

<!--jdbc-->
		<dependency>
			<groupId>org.springframework.boot</groupId>
			<artifactId>spring-boot-starter-jdbc</artifactId>
		</dependency>
		<!--web,tomcat-->
		<dependency>
			<groupId>org.springframework.boot</groupId>
			<artifactId>spring-boot-starter-web</artifactId>
		</dependency>

		<!--mysql-->
		<dependency>
			<groupId>mysql</groupId>
			<artifactId>mysql-connector-java</artifactId>
			<scope>runtime</scope>
		</dependency>

		<!--security-->
		<dependency>
		<groupId>org.springframework.boot</groupId>
		<artifactId>spring-boot-starter-security</artifactId>
		</dependency>

		<!--mybatis和spring整合-->
		<dependency>
			<groupId>org.mybatis.spring.boot</groupId>
			<artifactId>mybatis-spring-boot-starter</artifactId>
			<version>2.1.1</version>
		</dependency>

		<!--thymeleaf模板引擎-->
		<dependency>
			<groupId>org.thymeleaf</groupId>
			<artifactId>thymeleaf-spring5</artifactId>
		</dependency>
		<dependency>
			<groupId>org.thymeleaf.extras</groupId>
			<artifactId>thymeleaf-extras-java8time</artifactId>
		</dependency>

		<!-- thymeleaf整合springsecurity -->
		<dependency>
			<groupId>org.thymeleaf.extras</groupId>
			<artifactId>thymeleaf-extras-springsecurity5</artifactId>
			<version>3.0.4.RELEASE</version>
		</dependency>

实体类

public class SysRole {
//自增id
    private Integer id;
    //用户id
    private Integer userId;
    //用户权限名
    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;
    }
    public void setUserId(Integer userId) {
        this.userId = userId;
    }
    public Integer getUserId() {
        return userId;
    }
}


public class SysUser implements UserDetails  {

    private static final long serialVersionUID = 1L;

    private Integer id;
    private String username;
    private String password;

    private List<SysRole> roles;

    /**
     * 重写getAuthorities()方法
     * 将用户角色作为权限
     *
     * @return
     */

    @Override
    public Collection<? extends GrantedAuthority> getAuthorities() {
        List<GrantedAuthority> auths = new ArrayList<GrantedAuthority>();
        List<SysRole> roles = this.getRoles();
        for (SysRole role : roles) {
            auths.add(new SimpleGrantedAuthority(role.getName()));
        }
        return auths;
    }
    
    @Override
    public boolean isAccountNonExpired() {
        return true;
    }
    @Override
    public boolean isAccountNonLocked() {
        return true;
    }
    @Override
    public boolean isCredentialsNonExpired() {
        return true;
    }
    @Override
    public boolean isEnabled() {
        return true;
    }
    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;
    }
    public String getPassword() {
        return password;
    }
    public void setPassword(String password) {
        this.password = password;
    }

    pblic List<SysRole> getRoles() {
        return roles;
    }

    pblic void setRoles(List<SysRole> roles) {
        this.roles = roles;
    }
}

Security配置

@Component
public class CustomUserService implements UserDetailsService {
    @Autowired
    private SysUserMapper sysUserMapper;
    @Override
    //给账号密码授予权限
    public UserDetails loadUserByUsername(String username)  {
        System.out.println("执行了+====CustomUSerService");
        SysUser user = sysUserMapper.findByUsername(username);
        if (user == null) {
            throw new BadCredentialsException("用户名不存在");
        }
        Collection<SimpleGrantedAuthority> authorities = (Collection<SimpleGrantedAuthority>)user.getAuthorities();
        return new org.springframework.security.core.userdetails.User(user.getUsername(),
                user.getPassword(), authorities);
    }
}
@Configuration
@EnableWebSecurity
public class WebSecurityConfig extends WebSecurityConfigurerAdapter {
    @Autowired
    private  CustomUserService   customUserService;
    
    @Bean
    public PasswordEncoder passwordEncoder(){
        return  new BCryptPasswordEncoder();
    }

    @Override
    //身份验证
    protected void configure(AuthenticationManagerBuilder auth) throws Exception {
        System.out.println("身份验证");
        auth.userDetailsService(customUserService).passwordEncoder(passwordEncoder());
    }

    @Override
    //设置权限
    protected void configure(HttpSecurity http) throws Exception {
        System.out.println("设置权限");
        http.authorizeRequests()
                .antMatchers("/login").permitAll()  // login请求可以任意访问
                .antMatchers("/toVip").hasAnyAuthority("ROLE_VIP")
                .anyRequest().authenticated() //  所有请求必须要登录后才能认证
                .and()
                .formLogin() //跳转登录界面
                .loginPage("/login")
                //.loginProcessingUrl("/home")
                .passwordParameter("password")
                .usernameParameter("username")
               .defaultSuccessUrl("/toHome",true) //成功之后重定向请求
                .failureUrl("/login?error")//登录失败访问的页面
                .permitAll() // 登录页面可以任意访问
                .and()
                .logout().permitAll();//6 注销可以任意访问
        http.rememberMe().rememberMeParameter("re");
        http.csrf().disable();
    }
}

前端界面

//login界面
<!DOCTYPE html>
<html xmlns:th="http://www.thymeleaf.org">
<head>
    <meta content="text/html;charset=UTF-8"/>
    <title>登录页面</title>
    <style type="text/css">
        body {
            padding-top: 50px;
        }
        .starter-template {
            padding: 40px 15px;
            text-align: center;
        }
    </style>
</head>
<body>
<div class="container">
    <div class="starter-template">
        <p th:if="${param.logout}" class="bg-warning">已成功注销</p>
        <h2>Login</h2>
        <form name="form"   method="POST"> <!-- 3 -->
            <div class="form-group">
                <label for="username">账号</label>
                <input id="username" type="text" class="form-control" name="username" value="" placeholder="name" />
            </div>
            <div class="form-group">
                <label id="password" for="password">密码</label>
                <input type="password" class="form-control" name="password" placeholder="password" />
            </div>
            <p th:if="${param.error}" th:text="${session.SPRING_SECURITY_LAST_EXCEPTION.message}" style="color:red;" ></p>
            <input type="submit" id="login" value="Login" class="btn btn-primary" /><br>
            <input type="checkbox" name="re">记住我
        </form>
    </div>
</div>
</body>
</html>
//home.html
<!DOCTYPE html>
<html xmlns:th="http://www.thymeleaf.org"
      xmlns:sec="http://www.thymeleaf.org/thymeleaf-extras-springecurity5"><!-- 1 -->
<head>
    <meta content="text/html;charset=UTF-8"/>
    <title sec:authentication="name"></title>
    <style type="text/css">
        body {
            padding-top: 50px;
        }
        .starter-template {
            padding: 40px 15px;
            text-align: center;
        }
    </style>
</head>
<body>
<div class="container">
    <div class="starter-template">
        <div sec:authorize="hasRole('ROLE_ADMIN')"> <!-- 3 -->
           <p style="background-color: brown; color: white" >管理员可见</p>
        </div>
        <div sec:authorize="hasRole('ROLE_USER')"> <!-- 4-->
            <p style="background-color: brown; color: white">用户可见</p>
        </div>
        <a href="/toVip">vip链接</a>
        <form th:action="@{/logout}" method="post">
            <input type="submit" class="btn btn-primary" value="注销"/><!-- 5 -->
        </form>
        <!--name:<span sec:authentication="name"></span>-->
    </div>
</div>
</body>
</html>

跳转路由controller

@Controller
public class HomeController {
    @Autowired
    SysUserMapper sysUserMapper;

    @Autowired
    UserRoleMapper userRoleMapper;

    @RequestMapping("/toHome")
    public String toHome() {
        System.out.println("重定向到toHome ");
        return "home";
    }

    @RequestMapping("/login")
    public  String login(){
        return "login";
    }

//跳转至注册界面
    @RequestMapping("/toCreate")
    public  String toCreate(){
        return "create";
    }

//用户注册
    @RequestMapping("/create")
    public  String create(SysUser user){
        String password=user.getPassword();
        BCryptPasswordEncoder encoder =new BCryptPasswordEncoder();
        //需要把表单的密码用该加密方式加密存入数据库
        //因为security配置的就是这种加密方式
        user.setPassword(encoder.encode(password.trim()));
        sysUserMapper.create(user);
        //给该用户“ROLE_USER”权限
        SysRole sysRole=new SysRole();
        sysRole.setUserId(user.getId());
        sysRole.setName("ROLE_USER");
        userRoleMapper.insertSysRole(sysRole);
        return "login";
    }
//跳转vip界面
    @RequestMapping("/toVip")
    public  String toVip(){
        return  "vip";
    }
}

mapper接口及配置文件

//mapper接口
@Mapper
public interface SysUserMapper {
    SysUser findByUsername(String username);
    void create(SysUser sysUser);
}

//xml文件
<!DOCTYPE mapper
        PUBLIC "-//mybatis.org//DTD Mapper 3.0//EN"
        "http://mybatis.org/dtd/mybatis-3-mapper.dtd">
<mapper namespace="hut.gt.mapper.SysUserMapper">
    <resultMap id="map1" type="SysUser">
        <id column="id" property="id"></id>
        <result column="username" property="username"></result>
        <result column="password" property="password"></result>
        <collection property="roles" ofType="SysRole">
            <id column="qid" property="id"></id>
            <result column="userId" property="userId"></result>
            <result column="name" property="name"></result>
        </collection>
    </resultMap>
    <select id="findByUsername" parameterType="string" resultMap="map1">
       select sys_user.*,sys_role.id as qid,sys_role.userId,sys_role.name from sys_user,sys_role
        where sys_user.id=sys_role.userId
         and username=#{username}
    </select>
    <insert id="create" parameterType="SysUser">
        <selectKey resultType="int"  keyProperty="id">
            select LAST_INSERT_ID()
        </selectKey>
        insert into sys_user (username, password) values (#{username},#{password})
    </insert>
</mapper>
//mapper接口
@Mapper
public interface UserRoleMapper {
    List<SysRole> getRoleByUser(Integer id);
    void insertSysRole(SysRole sysRole);
}

//xml文件
<!DOCTYPE mapper
        PUBLIC "-//mybatis.org//DTD Mapper 3.0//EN"
        "http://mybatis.org/dtd/mybatis-3-mapper.dtd">
<mapper namespace="hut.gt.mapper.UserRoleMapper">
    <select id="getRoleByUser" parameterType="int" resultType="SysRole">
       select * from  sys_role where userId=#{id}
    </select>
    <insert id="insertSysRole" parameterType="SysRole">
        insert into sys_role (userId,name) values (#{userId},#{name})
    </insert>
</mapper>

效果展示

1.登录一个只有用户权限的用户
springboot+springsecurity+mybatis实现一个登录、注册、主界面的权限管理
点击vip链接
springboot+springsecurity+mybatis实现一个登录、注册、主界面的权限管理
进入了403错误界面,代表没有权限,因为我们这个用户确实只有普通用户权限

2.登录一个拥有所有权限的用户
springboot+springsecurity+mybatis实现一个登录、注册、主界面的权限管理
这时候多出来一个模块,即为管理员可见的

点击vip链接
springboot+springsecurity+mybatis实现一个登录、注册、主界面的权限管理
成功进入。

根据上面的例子,我们很好地进行了权限地控制,欢迎大家交流评论!

相关标签: 权限框架