SpringSecurity连接数据库并设置权限

一、数据库数据

SpringSecurity连接数据库并设置权限_第1张图片

SpringSecurity连接数据库并设置权限_第2张图片role表 

SpringSecurity连接数据库并设置权限_第3张图片

user表

SpringSecurity连接数据库并设置权限_第4张图片

user_role表

SpringSecurity连接数据库并设置权限_第5张图片

role_menu表

SpringSecurity连接数据库并设置权限_第6张图片

二、项目结构 

SpringSecurity连接数据库并设置权限_第7张图片

三、pom.xml依赖


            org.springframework.boot
            spring-boot-starter-web
        

        
            org.projectlombok
            lombok
            true
        
        
            org.springframework.boot
            spring-boot-starter-test
            test
        
        
            org.springframework.boot
            spring-boot-starter-security
        


        
        
            org.mybatis
            mybatis
            3.5.11
        
        
            com.baomidou
            mybatis-plus-boot-starter
            3.5.3.1
        

        
        
            mysql
            mysql-connector-java
            8.0.26
        

四、SecurityConfig类的配置

package com.aaa.config;

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.WebSecurityConfigurerAdapter;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder;
import org.springframework.security.crypto.password.PasswordEncoder;

import javax.annotation.Resource;


@Configuration
public class SecurityConfig extends WebSecurityConfigurerAdapter {
    @Resource
    protected UserDetailsService userDetailsService;
    @Bean
    public PasswordEncoder passwordEncoder(){
        return new BCryptPasswordEncoder();
    }


    @Override
    protected void configure(HttpSecurity http) throws Exception {
        /*------------------------------------------------------------------------*/
        // 开始 配置自定义的信息
        http.formLogin().loginPage("/login.html")//路径前面必须加  /
                .loginProcessingUrl("/login")//跟提交的路径一样
                .usernameParameter("username")//登陆账号
                .passwordParameter("userpassword");//登陆密码
        //.defaultSuccessUrl("/test");//登陆成功的跳转路径
        /*------------------------------------------------------------------------*/
        /*------------------------------------------------------------------------*/
        http.authorizeRequests().antMatchers("/login.html", "login").permitAll();//不用验证
        //http.authorizeRequests().antMatchers("/test").hasRole("test");//必须有哪个权限才能访问
        //http.authorizeRequests().antMatchers("/test").hasAnyAuthority("resource");//必须有哪个资源才能访问
        //其他路径进行验证
        http.authorizeRequests().anyRequest().authenticated();
        //关闭csrf保护
        http.csrf().disable();
        /*------------------------------------------------------------------------*/
    }

    @Override
    protected void configure(AuthenticationManagerBuilder auth) throws Exception {
        auth.userDetailsService(userDetailsService).passwordEncoder(passwordEncoder());
    }
}

五、Securityservice的类

package com.aaa.service;


import com.aaa.entity.Menu;
import com.aaa.entity.Role;
import com.aaa.entity.User;
import com.aaa.mapper.MenuMapper;
import com.aaa.mapper.RoleMapper;
import com.aaa.mapper.UserMapper;
import com.aaa.mapper.UserRoleMapper;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
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 javax.annotation.Resource;
import java.util.ArrayList;
import java.util.List;
import java.util.stream.Collectors;

@Service
public class TestService implements UserDetailsService {
    @Resource
    private UserMapper userMapper;
    @Resource
    private UserRoleMapper userRoleMapper;
    @Resource
    private RoleMapper roleMapper;
    @Resource
    private MenuMapper menuMapper;
    @Override
    public UserDetails loadUserByUsername(String username) throws UsernameNotFoundException {


        QueryWrapper queryUser = new QueryWrapper<>();
        queryUser.eq("loginname",username);
        User user = userMapper.selectOne(queryUser);

        if (user!=null){
            Integer uid =user.getUid();
            //根据用户查找权限rid
            QueryWrapper queryrole = new QueryWrapper<>();
            queryrole.eq("uid",uid);
            Integer rid = userRoleMapper.selectOne(queryrole).getRid();
            //根据rid查找对应的所有信息
            Role role = roleMapper.selectById(rid);

            List authorities = new ArrayList<>();
            //添加role权限
            authorities.add(new SimpleGrantedAuthority("ROLE_CE"+role.getRcode()));
            //根据role查询所拥有的菜单信息
            List menus = menuMapper.selectMenus(rid);
            //添加资源权限
            List collect = menus.stream().map(menu -> new SimpleGrantedAuthority(menu.getMcode())).collect(Collectors.toList());
            authorities.addAll(collect);
            return new org.springframework.security.core.userdetails.User(username,user.getPassword(),authorities);
        }

        return null;
    }
}

六、controller类的配置

@RestController
@RequestMapping("/test")
public class TestController {
-------------可以用注解设置访问权限了------------------
    @GetMapping
    public Object gets(Principal principal){
        return principal;
    }

   /* @Secured({"ROLE_CE"})
    @GetMapping
    public String test(){
        return "Hello World!";
    }*/

 /*   @RolesAllowed({"CE"})
    @GetMapping
    public String test(){
        return "Hello World!";
    }*/

/* @PreAuthorize("hasRole('user')")
    @GetMapping
    public String test(){
        return "Hello World!";
    }*/

/*    @GetMapping
    public String test(){
        return "Hello World!";
    }*/
}

 七、login.html页面

SpringSecurity连接数据库并设置权限_第8张图片




    
    Title




用户名:
密  码:

八、测试

在页面显示权限是否正确

SpringSecurity连接数据库并设置权限_第9张图片

数据库数据:

SpringSecurity连接数据库并设置权限_第10张图片

SpringSecurity连接数据库并设置权限_第11张图片

你可能感兴趣的:(数据库,spring,boot)