SpringBoot+Vue+Redis实现前后端分离的登录认证
⼀、需求分析
⽤户在浏览器登录后,跳转到其他页⾯,当⽤户在其他地⽅再次登录时,前⼀个页⾯⾃动退出登录,列如游戏或者qq挤号,显⽰该账号已经在另外的地⽅登录。
⼆、开始编写后端代码
1、创建数据库表并新增两条数据,⽤于测试
CREATE DATABASE
USE `login`;
DROP TABLE IF EXISTS `user`;
CREATE TABLE `user` (
`id` int(4) NOT NULL AUTO_INCREMENT,
`username` varchar(50) DEFAULT NULL,
`password` varchar(50) DEFAULT NULL,
PRIMARY KEY (`id`)
) ENGINE=InnoDB AUTO_INCREMENT=3 DEFAULT CHARSET=utf8;
//密码进⾏了MD5加密,更换了以前的未加密的密码
insert into `user`(`id`,`username`,`password`) values
(1,'root','63a9f0ea7bb98050796b649e85481845'),
(2,'admin','e10adc3949ba59abbe56e057f20f883e');
//root的password为 root
//admin的password为 123456
2、创建SpringBoot项⽬,项⽬结构如下,(截图的⽔印不晓得怎么去掉,就这样吧)
3、修改l,添加相关依賴
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-data-jdbc</artifactId> </dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-data-jpa</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-data-redis</artifactId> </dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-jdbc</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-web</artifactId>
</dependency>
<dependency>
<groupId>org.projectlombok</groupId>
<artifactId>lombok</artifactId>
<optional>true</optional>
</dependency>
<dependency>
<groupId>redis.clients</groupId>
<artifactId>jedis</artifactId>
<version>2.9.3</version>
</dependency>
<dependency>
<groupId>mysql</groupId>
<artifactId>mysql-connector-java</artifactId>
<version>5.1.46</version>
</dependency>
<dependency>
<groupId>org.apache.directory.studio</groupId>
<artifactId>org.apachemons.lang</artifactId>
<version>2.6</version>
</dependency>
4、开始配置l
spring:
redis:
database:0 #redis的默认数据库为0
host:127.0.0.1 #链接redis的ip
port:6379 #链接redis的端⼝号
password: #链接redis的密码默认为空
jedis:
pool:
max-total:200 #链接redis的总数⽬
max-active:100 #链接redis的最⼤
max-idle:8 #最⼤的链接数量
min-idle:5 #最⼩的链接数量
datasource:
#由于买的阿⾥云服务器内存不够了,docker容器中mysql镜像总是⾃动关闭,所以改⽤本地mysql url: jdbc:mysql://127.0.0.1:3306/login?useUnicode=true
username: root
password: sasa
driver-class-name: sql.jdbc.Driver
jpa:
show-sql:true
server:
port:8888
REDIS_KEY : USER_TOKEN
5、编写⽤户实体类
@Data
@Entity
@Table(name ="user")
public class User {
@Id
@GeneratedValue(strategy = GenerationType.IDENTITY)
@Column(name ="id")
private int id;
@Column(name ="username")
private String username;
@Column(name ="password")
private String password;
}
6、编写dao层
public interface UserDao extends JpaRepository<User,Integer>{
public User findByUsernameAndPassword(String username, String password);
}
7、编写service层
@Service
@Transactional
public class UserServiceImpl{
@Autowired
private UserDao userDao;
@Autowired
private JedisDao jedisDao;
@Value("${REDIS_KEY}")//从配置⽂件中取值
private String KEY;
private Map<Integer,String> UserLogin =new HashMap<>();
/**
* 登录
*/
public User userlogin(HttpServletRequest request, HttpServletResponse response, User u){ //查询登录是否成功
User user=userDao.Username(),u.getPassword());
User user=userDao.Username(),u.getPassword());
//判断us是否为空
if(user==null){
return null;
}
//调⽤MD5⽅法进⾏加密
String pwd=Password());
System.out.println("测试md5加密:"+pwd);
System.out.println("测试us对象密码"+us.getPassword());
//如果加密密码和未加密密码不⼀致,则返回null
if(!pwd.Password())){
System.out.println("测试:现加密密码和数据库内加密密码不⼀致");
return null;
}
/
/⽣成token
String token="user_"+ UUID.randomUUID().toString();
//从map中获得redis中的key
String oldToken = (Id());
//判断map中是否存在该id
if(!StringUtils.isEmpty(oldToken)){
//删除redis中⽼的值
jedisDao.delValue(oldToken);
}
//将新的的key保存到map中
vue element adminUserLogin.Id(),token);
/
/将信息存⼊redis
jedisDao.setValue(token, JsonUtils.objectToJson(user));
//将token放⼊cookie中
CookieUtils.setCookie(request,response,KEY,token,5*60,true);
return user;
}
/**
* 判断是否登录
*/
public String getUserByToken(HttpServletResponse response, HttpServletRequest request){ //从cookie中取出⽤户token
String CookieValue(request,KEY);
//从redis中取出⽤户信息
String user= Value(token);
return user;
}
/***
* MD5加码⽣成32位md5码
*/
public String string2MD5(String inStr){
MessageDigest md5 = null;
try{
md5 = Instance("MD5");
}catch(Exception e){
System.out.String());
e.printStackTrace();
return"";
}
char[] charArray = CharArray();
byte[] byteArray =new byte[charArray.length];
for(int i =0; i < charArray.length; i++)
byteArray[i]=(byte) charArray[i];
byte[] md5Bytes = md5.digest(byteArray);
StringBuffer hexValue =new StringBuffer();
for(int i =0; i < md5Bytes.length; i++){
int val =((int) md5Bytes[i])&0xff;
if(val <16)
if(val <16)
hexValue.append("0");
hexValue.HexString(val));
}
String();
}
}
8、编写controller层
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系QQ:729038198,我们将在24小时内删除。
发表评论