最近学习了基于springsecurity来验证授权Restful API
准备工作:
1.mysql表,一共5张表用户,用户,角色,用户角色,权限,角色权限:
DROP TABLE if exists users,role,userrole,permission,rolepermission ;
CREATE TABLE IF NOT EXISTS user (
id INT AUTO_INCREMENT PRIMARY KEY,
username VARCHAR(255) NOT NULL,
password VARCHAR(255) NOT NULL,
created_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP
) ENGINE=INNODB,
AUTO_INCREMENT = 100 ;
CREATE TABLE IF NOT EXISTS userrole (
id INT AUTO_INCREMENT PRIMARY KEY,
userid INT NOT NULL,
roleid INT NOT NULL,
created_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP
) ENGINE=INNODB,
AUTO_INCREMENT = 100 ;
CREATE TABLE IF NOT EXISTS role (
id INT AUTO_INCREMENT PRIMARY KEY,
role varchar(255) NOT NULL,
created_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP
) ENGINE=INNODB,
AUTO_INCREMENT = 100 ;
CREATE TABLE IF NOT EXISTS rolepermission (
id INT AUTO_INCREMENT PRIMARY KEY,
roleid INT NOT NULL,
permissionid INT NOT NULL,
created_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP
) ENGINE=INNODB,
AUTO_INCREMENT = 100 ;
CREATE TABLE IF NOT EXISTS permission (
id INT AUTO_INCREMENT PRIMARY KEY,
permission varchar(255) NOT NULL,
created_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP
) ENGINE=INNODB,
AUTO_INCREMENT = 100 ;
2.测试数据:
delete from user;
delete from userrole;
delete from role;
delete from rolepermission;
delete from permission;
INSERT INTO user(username,password)
VALUES('trainee', '123'), ('admin','123'), ('supervisor', '123'),('marketing','123'),('inspector','123');
INSERT INTO role(role)
VALUES('trainee'), ('admin'),('supervisor'),('marketing'),('inspector');
INSERT INTO userrole(userid,roleid)
VALUES(100,100),(101,101),(102,102),(103,103),(104,104),(105,105);
INSERT INTO permission(id,permission)
values(100, 'user_read'),(101, 'user_write');
INSERT INTO rolepermission(roleid,permissionid)
VALUES(101,100),(101,101),(102,100),(102,101),(103,100),(104,101)
3.springboot空架子
至此就可以开发了,希望大家的mybatis和mysql环境都ok,我主要说说security的配置
工作量主要集中在:
1)创建下面三个文件,
ApplicationSecurityConfiger:
对security做http拦截器的配置,说简单点就是告诉spring怎么保护api,
保护步骤为
1: 验证用户名密码(从数据库user表读数据)
2.:验证权限(权限从role和permission表一起读出来的)
这两部都pass了,api就可以让你用,就这个思路
customUserDetailsService :
这个自定义类主要重写loadUserByUsername,我用mybatis读,你随意
CustomUserDetails
这个也是自定义类,implements Userdetails
主要是重写这个方法getAuthorities,把role和permissions组装成Collection实现类都可以
至此,我们告诉了springsecurity
1.验证username/password
2.验证roles/permission
你的api就这样被保护了
我也是新手,篇幅有限,大概思路就是这样,具体实现没必要追求一致。
spingsecurity的灵活之处是,表设计好后,读出来给spring,然后配置要保护的api就完事了
而且可以灵活的根据role和permission两个维度保护,十分灵活
本人还在学习中
有问题一起探讨