赞
踩
使用springsecurity框架提供了加密算法,方便对密码进行加密
4、使用security中的PasswordEncoder进行加密
新建一个spring boot项目,数据库User表。
依赖:web、security、mybatisplus、mysql、lombok
- <!--web-->
- <dependency>
- <groupId>org.springframework.boot</groupId>
- <artifactId>spring-boot-starter-web</artifactId>
- </dependency>
-
- <!--mybatisplus-->
- <dependency>
- <groupId>com.baomidou</groupId>
- <artifactId>mybatis-plus-boot-starter</artifactId>
- <version>3.4.3</version>
- </dependency>
-
- <!--mysql-->
- <dependency>
- <groupId>mysql</groupId>
- <artifactId>mysql-connector-java</artifactId>
- </dependency>
-
- <!--security-->
- <dependency>
- <groupId>org.springframework.boot</groupId>
- <artifactId>spring-boot-starter-security</artifactId>
- </dependency>
-
- <!--lombok-->
- <dependency>
- <groupId>org.projectlombok</groupId>
- <artifactId>lombok</artifactId>
- </dependency>

application.yml
server: port: 8080 spring: datasource: driver-class-name: com.mysql.cj.jdbc.Driver url: jdbc:mysql://localhost:3306/forum?characterEncoding=utf-8&useSSL=false&serverTimezone=UTC username: root password: 123456 mybatis-plus: global-config: db-config: #数据库主键自增 id-type: auto #逻辑删除 logic-delete-field: delFlag #逻辑已删除 logic-delete-value: 1 #逻辑未删除 logic-not-delete-value: 0 configuration: #是否开启自动驼峰命名规则映射 map-underscore-to-camel-case: true #开启控制台 SQL 日志打印 log-impl: org.apache.ibatis.logging.stdout.StdOutImpl
生成UserService、UserServiceImpl、UserController、User实体类
UserController
- package com.example.demo.controller;
-
- import com.example.demo.entity.User;
- import com.example.demo.service.UserService;
- import org.springframework.beans.factory.annotation.Autowired;
- import org.springframework.web.bind.annotation.GetMapping;
- import org.springframework.web.bind.annotation.PostMapping;
- import org.springframework.web.bind.annotation.RequestBody;
- import org.springframework.web.bind.annotation.RestController;
-
-
- @RestController
- public class UserController {
- @Autowired
- private UserService userService;
- @PostMapping("/register")
- public String register(@RequestBody User user){
- return userService.register(user);
- }
- }

UserSercixeImpl
- package com.example.demo.service.impl;
-
- import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
- import com.example.demo.entity.User;
- import com.example.demo.mapper.UserMapper;
- import com.example.demo.service.UserService;
- import org.springframework.stereotype.Service;
-
- @Service
- public class UserServiceImpl extends ServiceImpl<UserMapper, User> implements UserService {
- @Override
- public String register(User user) {
- boolean save = save(user);
- return String.valueOf(save);
- }
- }

注释掉security依赖发送请求,我们可以看到存到数据库里的密码是明文密码,未经过加密的
取消security注释
配置SecurityConfig配置类
SecurityConfig
- package com.example.demo.config;
-
- import org.springframework.context.annotation.Bean;
- import org.springframework.context.annotation.Configuration;
- import org.springframework.security.authentication.AuthenticationManager;
- import org.springframework.security.config.annotation.web.builders.HttpSecurity;
- import org.springframework.security.config.annotation.web.configuration.WebSecurityConfigurerAdapter;
- import org.springframework.security.config.http.SessionCreationPolicy;
- import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder;
- import org.springframework.security.crypto.password.PasswordEncoder;
- import org.springframework.stereotype.Component;
-
- /**
- * @BelongsProject: SprngSecurityLogin
- * @BelongsPackage: com.example.demo.config
- * @Author: tanxudong
- * @CreateTime: 2023-04-21 18:49
- * @Description: TODO
- * @Version: 1.0
- */
- @Configuration
- public class SecurityConfig extends WebSecurityConfigurerAdapter {
-
- @Bean
- @Override
- public AuthenticationManager authenticationManagerBean() throws Exception {
- return super.authenticationManagerBean();
- }
-
- @Override
- protected void configure(HttpSecurity http) throws Exception {
- /*基于spring security,为了防止跨站提交攻击,通常会启用csrf,
- 所有http请求都被会CsrfFilter拦截,
- 而CsrfFilter中有一个私有类DefaultRequiresCsrfMatcher,
- POST方法被排除在外了,也就是说只有GET|HEAD|TRACE|OPTIONS这4类方法会被放行。*/
- http.csrf().disable()
- .authorizeRequests().mvcMatchers("/register").permitAll();
- }
-
- @Bean
- public PasswordEncoder passwordEncoder(){
- return new BCryptPasswordEncoder();
- }
-
- }

UserServiceImpl
- package com.example.demo.service.impl;
-
- import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
- import com.example.demo.entity.User;
- import com.example.demo.mapper.UserMapper;
- import com.example.demo.service.UserService;
- import org.springframework.beans.factory.annotation.Autowired;
- import org.springframework.security.crypto.password.PasswordEncoder;
- import org.springframework.stereotype.Service;
-
- /**
- * @BelongsProject: SprngSecurityLogin
- * @BelongsPackage: com.example.demo.service.impl
- * @Author: tanxudong
- * @CreateTime: 2023-04-21 17:58
- * @Description: TODO
- * @Version: 1.0
- */
- @Service
- public class UserServiceImpl extends ServiceImpl<UserMapper, User> implements UserService {
- @Autowired
- private PasswordEncoder passwordEncoder;
- @Override
- public String register(User user) {
- String encodePassword = passwordEncoder.encode(user.getPassword());
- user.setPassword(encodePassword);
- boolean save = save(user);
- return String.valueOf(save);
- }
- }

再次发起post请求
对比两次结果,没使用security前是明文密码,使用后是密文
有时候会要求用户名唯一,所以要加一次判断,判断是否重复。
同时,不仅需要前端进行某些字段的判空,后端也需要进行一次判断。
- package com.example.demo.service.impl;
-
- import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
- import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
- import com.example.demo.entity.User;
- import com.example.demo.mapper.UserMapper;
- import com.example.demo.service.UserService;
- import org.springframework.beans.factory.annotation.Autowired;
- import org.springframework.security.crypto.password.PasswordEncoder;
- import org.springframework.stereotype.Service;
- import org.springframework.util.StringUtils;
-
- /**
- * @BelongsProject: SprngSecurityLogin
- * @BelongsPackage: com.example.demo.service.impl
- * @Author: tanxudong
- * @CreateTime: 2023-04-21 17:58
- * @Description: TODO
- * @Version: 1.0
- */
- @Service
- public class UserServiceImpl extends ServiceImpl<UserMapper, User> implements UserService {
- @Autowired
- private PasswordEncoder passwordEncoder;
- @Override
- public String register(User user) {
-
- /*对用户名是否重复进行判断,同理其他的也可以这样判断*/
- if (ExistUsername(user.getUsername())){
- throw new RuntimeException("用户名重复");
- }
-
- /*判断用户名是否为空*/
- if (!StringUtils.hasText(user.getUsername())){
- throw new RuntimeException("用户名不能为空");
- }
-
- String encodePassword = passwordEncoder.encode(user.getPassword());
- user.setPassword(encodePassword);
- boolean save = save(user);
- return String.valueOf(save);
- }
-
- /*对用户名是否重复进行判断*/
- private boolean ExistUsername(String username) {
- LambdaQueryWrapper<User> queryWrapper = new LambdaQueryWrapper<>();
- queryWrapper.eq(User::getUsername,username);
- //如果查询的条数大于0,说明重复,返回true
- return count(queryWrapper)>0;
- }
- }

Copyright © 2003-2013 www.wpsshop.cn 版权所有,并保留所有权利。