Springboot实现简单登录

 全部代码:

链接:https://pan.baidu.com/s/1dFQOXLhVwQyHHqVTUvQFEw 
提取码:thk6

登录流程

1.浏览器发起请求获取验证码

2.接收请求,生成验证码,保存到redis中,设置过期时间5分钟,返回浏览器

3.浏览器输入用户名,密码,验证码,uuid

4.接收请求,通过用户名到数据库中查询用户

5.数据库返回数据库,判断用户是否存在

6.从通过uuid到redis中查询验证码和浏览器传入的验证码进行对比,判断验证码是否一样

7.判断密码是否一样

8.判断账户是否被禁用

9.Jwt生成touken

10.以token为key,用户id为value保存到redis中,设置过期时间30分钟

11.修改数据库当前登录对象信息

12.返回token到浏览器

部分代码:

package com.thk.controller;

import com.thk.constant.Constant;
import com.thk.domain.People;
import com.thk.domain.login.LoginUser;
import com.thk.service.IPeopleService;
import com.thk.utils.*;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.util.Date;
import java.util.HashMap;

@RestController
public class LoginController {

    @Resource
    //redis工具类
    private RedisUtil redisUtil;

    @Autowired
    private getVerificationCode getVerificationCode;

    @Autowired
    private IPeopleService peopleService;

    @RequestMapping("/login")
    public AjaxResult login(@RequestBody LoginUser loginUser) {
        AjaxResult ajax = AjaxResult.success();
        String code = loginUser.getCode();
        String uuid = loginUser.getUuid();
        if (StringUtils.isEmpty(loginUser.getCode()) && StringUtils.isEmpty(loginUser.getUuid())) {
            //删除验证码
            redisUtil.del(uuid);
            return AjaxResult.error("验证码不能为空!");
        }
        //验证验证码
        if (!verifyCode(code, uuid)) {
            //删除验证码
            redisUtil.del(uuid);
            return AjaxResult.error("验证码不正确,请重新输入!");
        }
        //查询登录对象
        People people = peopleService.selectByUserName(loginUser.getUserName());
        if (StringUtils.isNull(people)) {
            //删除验证码
            redisUtil.del(uuid);
            return AjaxResult.error("登录用户不存在");
        }
        //判断密码
        if (!verifyPassword(loginUser.getPwd(), people.getPwd())) {
            //删除验证码
            redisUtil.del(uuid);
            return AjaxResult.error("对不起,您的账号密码不正确,请重新输入");
        }
        //判断状态
        if (people.getStatus().equals(Constant.DISABLED)) {
            //删除验证码
            redisUtil.del(uuid);
            return AjaxResult.error("对不起,您的账号已经停用,请联系管理员");
        }

        //生成token
        String token = JwtUtil.getToken();
        //保存redis(token,对象)
        redisUtil.set(token, people.getId(), Constant.LOGIN_USER_DETE);
        //返回token
        ajax.put("token", token);
        //删除验证码
        redisUtil.del(uuid);
        //修改当前登录对象
        updatePeople(people);
        return ajax;
    }

   

    /**
     * 获取验证码
     *
     * @return
     */
    @GetMapping("/getCode")
    public AjaxResult getCode() {
        HashMap<String, String> number = getVerificationCode.getNumber();
        number.forEach((k, v) -> {
            redisUtil.set(k, v, Constant.CODE_DETE);
        });
        return AjaxResult.success(number);
    }

  
    /**
     * 判断验证码是否一致
     *
     * @param key
     * @param code
     * @return
     */
    public boolean verifyCode(String key, String code) {
        //从redis中取出key和value进行比对
        Object o = redisUtil.get(key);
        if (o != null) {
            if (o.equals(code)) {
                return true;
            }
        }
        return false;
    }

    /**
     * 判断密码是否一致
     *
     * @param value1 前端传入的值
     * @param value2 数据库查询的值
     * @return
     */
    public boolean verifyPassword(String value1, String value2) {
        String hash = Md5Utils.hash(value1);
        if (hash.equals(value2)) {
            return true;
        } else {
            return false;
        }
    }


}

测试:

获取验证码:

登录

通过token查询全部用户

请求头中没有token

携带token访问

  • 1
    点赞
  • 26
    收藏
    觉得还不错? 一键收藏
  • 1
    评论
实现用户登录功能,可以使用Spring Boot框架中的Spring Security模块。下面是一个简单的示例代码,说明如何在Spring Boot中实现用户登录: 1. 添加依赖:在pom.xml文件中添加Spring Security的依赖。 ```xml <dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-security</artifactId> </dependency> ``` 2. 创建用户实体类:创建一个表示用户的实体类,包括用户名和密码等属性。 ```java @Entity @Table(name = "users") public class User implements Serializable { @Id @GeneratedValue(strategy = GenerationType.IDENTITY) private Long id; @Column(nullable = false, unique = true) private String username; @Column(nullable = false) private String password; // 省略getter和setter方法 } ``` 3. 创建用户仓库:创建一个用于操作数据库的用户仓库接口。 ```java @Repository public interface UserRepository extends JpaRepository<User, Long> { User findByUsername(String username); } ``` 4. 创建认证用户服务:创建一个实现了UserDetailsService接口的认证用户服务类。 ```java @Service public class UserDetailsServiceImpl implements UserDetailsService { @Autowired private UserRepository userRepository; @Override public UserDetails loadUserByUsername(String username) throws UsernameNotFoundException { User user = userRepository.findByUsername(username); if (user == null) { throw new UsernameNotFoundException("用户不存在"); } return new org.springframework.security.core.userdetails.User(user.getUsername(), user.getPassword(), new ArrayList<>()); } } ``` 5. 配置Spring Security:创建一个配置类来配置Spring Security。 ```java @Configuration @EnableWebSecurity public class SecurityConfig extends WebSecurityConfigurerAdapter { @Autowired private UserDetailsService userDetailsService; @Override protected void configure(AuthenticationManagerBuilder auth) throws Exception { auth.userDetailsService(userDetailsService).passwordEncoder(passwordEncoder()); } @Override protected void configure(HttpSecurity http) throws Exception { http.authorizeRequests() .antMatchers("/login", "/register").permitAll() .anyRequest().authenticated() .and() .formLogin().loginPage("/login").defaultSuccessUrl("/home").permitAll() .and() .logout().permitAll(); } @Bean public PasswordEncoder passwordEncoder() { return new BCryptPasswordEncoder(); } } ``` 在上述代码中,我们配置了登录页面为"/login",默认成功跳转页面为"/home",并设置了访问权限规则。 以上是使用Spring Boot实现用户登录的基本步骤,你可以根据自己的需求进行定制和扩展。

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值