SpringSecurity安全认证之:数据库方式权限认证

创建测试数据库

create database TEST;

use TEST;

# 创建用户表
create table t_user(
    id bigint primary key auto_increment ,
    username varchar(25) ,
    password varchar(65) ,
    name varchar(25));

# 创建角色表
create table t_role(
    id int primary key auto_increment,
    name varchar(25) ,
    keyword varchar(25)
);

# 创建用户角色表
create table t_user_role(uid bigint , rid int );

# 添加外键
alter table t_user_role add constraint FK_user_ur foreign key (uid) references t_user(id);
alter table t_user_role add constraint FK_role_ur foreign key (rid) references t_role(id);

# 添加数据 密码是 123456 加密后的效果
insert into t_user values ( null , 'zhangsan' , '$2a$10$ezVuPO6NaUsQZ66p7y0QSeWfO6s.Qoz01vbTcI2vlcuLXy8Wk.DOy' , '张三');
insert into t_user values ( null , 'lisi' , '$2a$10$ezVuPO6NaUsQZ66p7y0QSeWfO6s.Qoz01vbTcI2vlcuLXy8Wk.DOy' , '李四');

insert into t_role values ( null , '管理员' , 'ROLE_ADMIN' );
insert into t_role values ( null , '普通员工' , 'ROLE_USER' );

insert into t_user_role value( 1 , 1 );
insert into t_user_role value( 2 , 2 );

添加项目依赖:

<dependency>
    <groupId>com.baomidou</groupId>
    <artifactId>mybatis-plus-boot-starter</artifactId>
    <version>3.4.2</version>
</dependency>
<dependency>
    <groupId>mysql</groupId>
    <artifactId>mysql-connector-java</artifactId>
</dependency>
<dependency>
    <groupId>org.projectlombok</groupId>
    <artifactId>lombok</artifactId>
</dependency>

spring的配置文件配置:

spring:
  datasource:
    driver-class-name: com.mysql.cj.jdbc.Driver
    url: jdbc:mysql://localhost:3306/Test?useSSL=false&serverTimezone=UTC
    username: root
    password: zengfl

查询等等忽略:

配置角色详情类:


import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.core.GrantedAuthority;
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;

@Service
public class UserDetailServiceImpl implements UserDetailsService {

    @Autowired
    private UserDao userDao;

    @Override
    public UserDetails loadUserByUsername(String username) throws UsernameNotFoundException {

        //1. 根据用户名查询用户
        User user = userDao.findByUsernameUser(username);
        System.out.println("user = " + user);

        //2. 构建返回
        List<GrantedAuthority> list = new ArrayList<>();
        List<Role> roleList = user.getRoleList();
        for (Role role : roleList) {
            list.add(new SimpleGrantedAuthority(role.getKeyword()));
        }

        //返回用户详情信息
        return new org.springframework.security.core.userdetails.User(
                user.getUsername() ,
                user.getPassword() ,
                list);
    }
}

修改认证方法;

@Configuration
public class SecurityConfigure extends WebSecurityConfigurerAdapter {

    @Autowired
    private UserDetailServiceImpl us;


    @Bean
    public BCryptPasswordEncoder bp (){
        return new BCryptPasswordEncoder();
    }

    /*
        认证:
            什么样的账号和密码, 是什么样的角色

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

3. 注解动态授权

springsecurity允许程序员在Controller方法上使用注解来动态授权,即配置角色|权限到方法上。表明需要具备什么样的角色身份或者是权限,才允许访问该方法!

  • 1.在方法上使用 @PreAuthorize 进行调用 权限拦截

    //表明调用方法需具有该角色身份。
    
@PreAuthorize("hasRole('ADMIN')")
    @RequestMapping("/show66")
    public String show66(){
        System.out.println("执行了show66方法!~~!");
        return "show ... success...";
    }
  • 2.要想让注解生效,需要在启动类上面设置注解

//启用全局方法注解
@EnableGlobalMethodSecurity(prePostEnabled = true)
@SpringBootApplication
public class Demo1HelloworldApplication {

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

}

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

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值