密码加密与微服务鉴权JWT

博客学习目标

1、用户注册时候,对数据库中用户的密码进行加密存储(使用 SpringSecurity)。

2、使用 JWT 鉴权认证。

一、BCrypt 密码加密

1、常见的加密方式

任何应用考虑到安全,绝不能明文的方式保存密码。密码应该通过哈希算法进行加密。
有很多标准的算法比如SHA或者MD5,结合salt(盐)是一个不错的选择。 Spring Security
提供了BCryptPasswordEncoder类,实现Spring的PasswordEncoder接口使用BCrypt强哈希方法来加密数据库中用户的密码。BCrypt强哈希方法 每次加密的结果都不一样。

2、是骡子是马拉出来遛遛(代码案例演示)

技术栈:SpringBoot 2.1.6.RELEASE(数据访问层使用 JPA)

开发工具:IDEA、Java8、Postman

引入依赖

<dependency>
    <groupId>org.springframework.boot</groupId>
    <artifactId>spring-boot-starter-web</artifactId>
</dependency>
<dependency>
    <groupId>org.springframework.boot</groupId>
    <artifactId>spring-boot-starter</artifactId>
</dependency>
<dependency>
    <groupId>org.springframework.boot</groupId>
    <artifactId>spring-boot-starter-data-jpa</artifactId>
</dependency>
<dependency>
    <groupId>mysql</groupId>
    <artifactId>mysql-connector-java</artifactId>
</dependency>
<!-- 引入 SpringSecurity --> 
<dependency>
    <groupId>org.springframework.boot</groupId>
    <artifactId>spring-boot-starter-security</artifactId>
</dependency>
<!-- lombok工具 -->
<dependency>
    <groupId>org.projectlombok</groupId>
    <artifactId>lombok</artifactId>
    <scope>provided</scope>
</dependency>
<dependency>
    <groupId>org.springframework.boot</groupId>
    <artifactId>spring-boot-starter-test</artifactId>
    <scope>test</scope>
</dependency>

控制层 controller

@RestController
@CrossOrigin
@RequestMapping("/user")
public class UserController {
   

    @Autowired
    private UserService userService;

    // 用户注册
    @RequestMapping(value = "/register", method = RequestMethod.POST)
    public Result register(@RequestBody User user) {
   

        boolean isRegister = userService.register(user);

        if (!isRegister) {
   
            return new Result(false, StatusCode.ERROR, "手机号码已经被注册,请直接登陆!");
        }

        return new Result(true, StatusCode.OK, "注册成功!");
    }

    // 用户登陆(限定使用手机号和密码登录)
    @RequestMapping(value = "/login", method = RequestMethod.POST)
    public Result login(@RequestBody User user) {
   

        User loginUser = userService.login(user.getMobile(), user.getPassword());

        if (null == loginUser) {
   
            return new Result(false, StatusCode.LOGINERROR, 
评论 2
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值