实现JWT认证与授权的Spring Boot项目详解

我们将详细介绍如何使用JWT(JSON Web Tokens)结合Spring Boot框架实现用户认证和授权系统。此方案将包括用户注册、登录以及通过JWT令牌进行后续请求的身份验证过程。我们将从引入必要的依赖开始,然后逐步构建项目的各个部分,包括JWT生成类、Controller、Service、ServiceImpl、Mapper以及异常处理机制。

引入依赖坐标

首先,确保你的pom.xml文件包含了以下依赖,这些依赖涵盖了Web启动、MyBatis集成、数据库连接、Lombok、测试、数据校验以及JWT库。

<dependencies>
  <dependency>
    <groupId>org.springframework.boot</groupId>
    <artifactId>spring-boot-starter-web</artifactId>
  </dependency>
  <dependency>
    <groupId>org.mybatis.spring.boot</groupId>
    <artifactId>mybatis-spring-boot-starter</artifactId>
    <version>3.0.3</version>
  </dependency>

  <dependency>
    <groupId>com.mysql</groupId>
    <artifactId>mysql-connector-j</artifactId>
    <scope>runtime</scope>
  </dependency>
  <dependency>
    <groupId>org.projectlombok</groupId>
    <artifactId>lombok</artifactId>
    <optional>true</optional>
  </dependency>
  <dependency>
    <groupId>org.springframework.boot</groupId>
    <artifactId>spring-boot-starter-test</artifactId>
    <scope>test</scope>
  </dependency>
  <dependency>
    <groupId>org.mybatis.spring.boot</groupId>
    <artifactId>mybatis-spring-boot-starter-test</artifactId>
    <version>3.0.3</version>
    <scope>test</scope>
  </dependency>
  <!--校验注解-->
  <dependency>
    <groupId>org.springframework.boot</groupId>
    <artifactId>spring-boot-starter-validation</artifactId>
  </dependency>
  <dependency>
    <groupId>com.auth0</groupId>
    <artifactId>java-jwt</artifactId>
    <version>3.14.0</version>
  </dependency>

</dependencies>

JWT生成类

接下来定义一个JWT工具类,用于生成和解析JWT令牌。

package com.leo.utils;

import com.auth0.jwt.JWT;
import com.auth0.jwt.algorithms.Algorithm;

import java.util.Date;
import java.util.Map;

public class JwtUtil {

    private static final String KEY = "jiongjiong";

    //接收业务数据,生成token并返回
    public static String genToken(Map<String, Object> claims) {
        return JWT.create()
        .withClaim("claims", claims)
        .withExpiresAt(new Date(System.currentTimeMillis() + 1000 * 60 * 60 * 12))
        .sign(Algorithm.HMAC256(KEY));
    }

    //接收token,验证token,并返回业务数据
    public static Map<String, Object> parseToken(String token) {
        return JWT.require(Algorithm.HMAC256(KEY))
        .build()
        .verify(token)
        .getClaim("claims")
        .asMap();
    }

}

Controller层

定义UserController,处理用户注册和登录请求。

package com.leo.controller;

import com.leo.pojo.Result;
import com.leo.service.UserService;
import org.hibernate.validator.constraints.Length;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

/**
 * @author leijiong
 * @version 1.0
 */
@RestController
@RequestMapping("/user")
@Validated
public class UserController {

    @Autowired
    private UserService userService;

    @PostMapping("/register")
    public Result register(@Length(min = 5, max = 16) String username, @Length(min = 5, max = 16)String password) {
        return  userService.register(username, password);
    }

    @PostMapping("/login")
    public Result<String> login(@Length(min = 5, max = 16) String username, @Length(min = 5, max = 16)String password) {
        return userService.login(username, password);
    }
}

Service层

定义UserService接口和其实现类UserServiceImpl,处理用户的注册和登录逻辑。

package com.leo.service;

import com.leo.pojo.Result;
import com.leo.pojo.User;

/**
 * @author leijiong
 * @version 1.0
 */
public interface UserService {

    Result register(String username, String password);

    Result<String> login(String username, String password);
}

Mapper层

定义UserMapper接口,用于执行SQL操作。

package com.leo.service;

import com.leo.pojo.Result;
import com.leo.pojo.User;

/**
 * @author leijiong
 * @version 1.0
 */
public interface UserService {

    Result register(String username, String password);

    Result<String> login(String username, String password);
}

异常处理

最后,添加全局异常处理类,以便在出现异常时统一返回错误信息。

package com.leo.mapper;

import com.leo.pojo.User;
import org.apache.ibatis.annotations.Insert;
import org.apache.ibatis.annotations.Mapper;
import org.apache.ibatis.annotations.Select;

/**
 * @author leijiong
 * @version 1.0
 */
@Mapper
public interface UserMapper {

    @Select("select * from user where username = #{username};")
    User findUsername(String username);

    @Insert("insert into user (username, password, create_time, update_time) values" +
            "(#{username}, #{password}, now(), now())")
    void add(String username, String password);
}

补充:数据校验框架

1.引入依赖坐标

<!--校验注解-->
<dependency>
  <groupId>org.springframework.boot</groupId>
  <artifactId>spring-boot-starter-validation</artifactId>
</dependency>

2.使用方式
在这里插入图片描述

总结

通过以上步骤,我们已经建立了一个基本的JWT认证与授权系统,可以用于Spring Boot应用中,实现安全的用户管理功能。在实际部署时,还需要考虑更多细节,例如配置跨域请求、实现JWT拦截器等。

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

爱跑步的程序员~

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值