From 2c8c6c2d877a8c54c961efb31a5dd02d87523b89 Mon Sep 17 00:00:00 2001 From: barney <15270405776@163.com> Date: Thu, 9 Mar 2023 00:30:51 +0800 Subject: [PATCH] =?UTF-8?q?=E6=B7=BB=E5=8A=A0=E4=BA=86SpringSecurity?= =?UTF-8?q?=E9=83=A8=E5=88=86=E4=BB=A3=E7=A0=81?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- SpringDataJPA/pom.xml | 25 ++++ .../springdatajpa/config/SecurityConfig.java | 51 +++++++ .../filter/JwtAuthenticationTokenFilter.java | 61 ++++++++ .../controller/UserController.java | 140 ++++++++++++------ .../springdatajpa/mapper/UserMapper.java | 8 +- .../cc/bnblogs/springdatajpa/pojo/User.java | 15 +- .../springdatajpa/pojo/model/UserModel.java | 9 -- .../impl/security/UserDetailServiceImpl.java | 30 ++++ .../impl/security/UserDetailsImpl.java | 56 +++++++ .../service/impl/user/LoginServiceImpl.java | 39 +++++ .../impl/user/RegisterServiceImpl.java | 87 +++++++++++ .../impl/user/UserInfoServiceImpl.java | 36 +++++ .../bnblogs/springdatajpa/utils/JwtUtil.java | 68 +++++++++ .../config/SecurityConfigTest.java | 35 +++++ .../springdatajpa/mapper/UserMapperTest.java | 2 +- 15 files changed, 594 insertions(+), 68 deletions(-) create mode 100644 SpringDataJPA/src/main/java/cc/bnblogs/springdatajpa/config/SecurityConfig.java create mode 100644 SpringDataJPA/src/main/java/cc/bnblogs/springdatajpa/config/filter/JwtAuthenticationTokenFilter.java create mode 100644 SpringDataJPA/src/main/java/cc/bnblogs/springdatajpa/service/impl/security/UserDetailServiceImpl.java create mode 100644 SpringDataJPA/src/main/java/cc/bnblogs/springdatajpa/service/impl/security/UserDetailsImpl.java create mode 100644 SpringDataJPA/src/main/java/cc/bnblogs/springdatajpa/service/impl/user/LoginServiceImpl.java create mode 100644 SpringDataJPA/src/main/java/cc/bnblogs/springdatajpa/service/impl/user/RegisterServiceImpl.java create mode 100644 SpringDataJPA/src/main/java/cc/bnblogs/springdatajpa/service/impl/user/UserInfoServiceImpl.java create mode 100644 SpringDataJPA/src/main/java/cc/bnblogs/springdatajpa/utils/JwtUtil.java create mode 100644 SpringDataJPA/src/test/java/cc/bnblogs/springdatajpa/config/SecurityConfigTest.java diff --git a/SpringDataJPA/pom.xml b/SpringDataJPA/pom.xml index d036861..1963562 100644 --- a/SpringDataJPA/pom.xml +++ b/SpringDataJPA/pom.xml @@ -22,6 +22,11 @@ spring-boot-starter-data-jpa + + org.springframework.boot + spring-boot-starter-security + + org.springframework.boot spring-boot-starter-web @@ -40,6 +45,26 @@ runtime + + io.jsonwebtoken + jjwt-api + 0.11.5 + + + + io.jsonwebtoken + jjwt-impl + 0.11.5 + runtime + + + + io.jsonwebtoken + jjwt-jackson + 0.11.5 + runtime + + org.projectlombok lombok diff --git a/SpringDataJPA/src/main/java/cc/bnblogs/springdatajpa/config/SecurityConfig.java b/SpringDataJPA/src/main/java/cc/bnblogs/springdatajpa/config/SecurityConfig.java new file mode 100644 index 0000000..62f78b1 --- /dev/null +++ b/SpringDataJPA/src/main/java/cc/bnblogs/springdatajpa/config/SecurityConfig.java @@ -0,0 +1,51 @@ +package cc.bnblogs.springdatajpa.config; + +import cc.bnblogs.springdatajpa.config.filter.JwtAuthenticationTokenFilter; +import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.context.annotation.Bean; +import org.springframework.context.annotation.Configuration; +import org.springframework.http.HttpMethod; +import org.springframework.security.authentication.AuthenticationManager; +import org.springframework.security.config.annotation.web.builders.HttpSecurity; +import org.springframework.security.config.annotation.web.configuration.EnableWebSecurity; +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.security.web.authentication.UsernamePasswordAuthenticationFilter; + +/** + * @description: + * @author: zfp@bnblogs.cc + * @date: 2023/3/8 17:06 + */ +@Configuration +@EnableWebSecurity +public class SecurityConfig extends WebSecurityConfigurerAdapter { + @Autowired + private JwtAuthenticationTokenFilter jwtAuthenticationTokenFilter; + + @Bean + public PasswordEncoder passwordEncoder() { + return new BCryptPasswordEncoder(); + } + + @Bean + @Override + public AuthenticationManager authenticationManagerBean() throws Exception { + return super.authenticationManagerBean(); + } + + @Override + protected void configure(HttpSecurity http) throws Exception { + http.csrf().disable() + .sessionManagement().sessionCreationPolicy(SessionCreationPolicy.STATELESS) + .and() + .authorizeRequests() + .antMatchers("/user/account/token/", "/user/account/register/").permitAll() + .antMatchers(HttpMethod.OPTIONS).permitAll() + .anyRequest().authenticated(); + + http.addFilterBefore(jwtAuthenticationTokenFilter, UsernamePasswordAuthenticationFilter.class); + } +} diff --git a/SpringDataJPA/src/main/java/cc/bnblogs/springdatajpa/config/filter/JwtAuthenticationTokenFilter.java b/SpringDataJPA/src/main/java/cc/bnblogs/springdatajpa/config/filter/JwtAuthenticationTokenFilter.java new file mode 100644 index 0000000..233a8e6 --- /dev/null +++ b/SpringDataJPA/src/main/java/cc/bnblogs/springdatajpa/config/filter/JwtAuthenticationTokenFilter.java @@ -0,0 +1,61 @@ +package cc.bnblogs.springdatajpa.config.filter; + +import cc.bnblogs.springdatajpa.mapper.UserMapper; +import cc.bnblogs.springdatajpa.pojo.User; +import cc.bnblogs.springdatajpa.service.impl.security.UserDetailsImpl; +import cc.bnblogs.springdatajpa.utils.JwtUtil; +import com.sun.istack.internal.NotNull; +import io.jsonwebtoken.Claims; +import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.security.authentication.UsernamePasswordAuthenticationToken; +import org.springframework.security.core.context.SecurityContextHolder; +import org.springframework.stereotype.Component; +import org.springframework.util.StringUtils; +import org.springframework.web.filter.OncePerRequestFilter; + +import javax.servlet.FilterChain; +import javax.servlet.ServletException; +import javax.servlet.http.HttpServletRequest; +import javax.servlet.http.HttpServletResponse; +import java.io.IOException; + +@Component +public class JwtAuthenticationTokenFilter extends OncePerRequestFilter { + @Autowired + private UserMapper userMapper; + + @Override + protected void doFilterInternal(HttpServletRequest request, @NotNull HttpServletResponse response, @NotNull FilterChain filterChain) throws ServletException, IOException { + String token = request.getHeader("Authorization"); + + if (!StringUtils.hasText(token) || !token.startsWith("Bearer ")) { + filterChain.doFilter(request, response); + return; + } + + token = token.substring(7); + + String userid; + try { + Claims claims = JwtUtil.parseJWT(token); + userid = claims.getSubject(); + } catch (Exception e) { + throw new RuntimeException(e); + } + // 这里不同的ORM实现可能不同,这里用的是JPA + // 就是根据用户id获取user + User user = userMapper.findUserById(Integer.parseInt(userid)); + + if (user == null) { + throw new RuntimeException("用户名未登录"); + } + + UserDetailsImpl loginUser = new UserDetailsImpl(user); + UsernamePasswordAuthenticationToken authenticationToken = + new UsernamePasswordAuthenticationToken(loginUser, null, null); + + SecurityContextHolder.getContext().setAuthentication(authenticationToken); + + filterChain.doFilter(request, response); + } +} \ No newline at end of file diff --git a/SpringDataJPA/src/main/java/cc/bnblogs/springdatajpa/controller/UserController.java b/SpringDataJPA/src/main/java/cc/bnblogs/springdatajpa/controller/UserController.java index d11a662..1516b12 100644 --- a/SpringDataJPA/src/main/java/cc/bnblogs/springdatajpa/controller/UserController.java +++ b/SpringDataJPA/src/main/java/cc/bnblogs/springdatajpa/controller/UserController.java @@ -3,8 +3,11 @@ package cc.bnblogs.springdatajpa.controller; import cc.bnblogs.springdatajpa.mapper.UserMapper; import cc.bnblogs.springdatajpa.pojo.User; import cc.bnblogs.springdatajpa.pojo.model.UserModel; -import jdk.nashorn.internal.runtime.logging.Logger; -import lombok.Data; +import cc.bnblogs.springdatajpa.service.impl.user.LoginServiceImpl; +import cc.bnblogs.springdatajpa.service.impl.user.RegisterServiceImpl; +import cc.bnblogs.springdatajpa.service.impl.user.UserInfoServiceImpl; +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.web.bind.annotation.*; @@ -17,65 +20,106 @@ import java.util.Map; * @date: 2023/3/7 23:21 */ @RestController +//@Slf4j @RequestMapping("/user") public class UserController { @Autowired - private UserMapper userMapper; - @GetMapping("/all/age/") - public List getAllAge() { - return userMapper.getAge(); - } + private LoginServiceImpl loginService; + @Autowired + private UserInfoServiceImpl infoService; + @Autowired + private RegisterServiceImpl registerService; - @GetMapping("/all/") - public List getAllUser() { - return userMapper.getInfo(); - } + @PostMapping("/account/token/") + public Map getToken(@RequestParam Map map) { + String username = map.get("username"); + String password = map.get("password"); - @GetMapping("/all/name/") - public List getAllName() { - return userMapper.getAllName(); + System.out.println(username + ' ' + password); + return loginService.getToken(username, password); } - @GetMapping("/") - public List getUserByAge(@RequestParam Integer age){ - return userMapper.getUserByAge(age); + @GetMapping("/account/info/") + public Map getInfo() { + return infoService.getInfo(); } - @GetMapping("/custom/1/") - public List> getCustomField1(){ - return userMapper.getCustomFields1(); - } - @GetMapping("/custom/2/") - public List> getCustomField2() { - return userMapper.getCustomFields2(); + @PostMapping("/account/register/") + public Map register(@RequestParam Map map) { + String username = map.get("username"); + String password = map.get("password"); + String confirmedPassword = map.get("confirmedPassword"); + return registerService.register(username, password, confirmedPassword); } - @GetMapping("/custom/3/") - public List getCustomField3() { - return userMapper.getCustomFields3(); - } - @GetMapping("/count/") - public Integer getUserCountByAge(@RequestParam Integer age) { - return userMapper.getUserCountByAge(age); - } +// private static final Logger log = LoggerFactory.getLogger(UserController.class); +// private final UserMapper userMapper; +// +// public UserController(UserMapper userMapper) { +// this.userMapper = userMapper; +// } +// +// @GetMapping("/all/age/") +// public List getAllAge() { +// log.info("get all age"); +// return userMapper.getAge(); +// } +// +// @GetMapping("/all/") +// public List getAllUser() { +// log.info("get all user"); +// return userMapper.getInfo(); +// } +// +// @GetMapping("/all/name/") +// public List getAllName() { +// return userMapper.getAllName(); +// } +// +// @GetMapping("/") +// public List getUserByAge(@RequestParam Integer age){ +// return userMapper.getUserByAge(age); +// } +// +// @GetMapping("/custom/1/") +// public List> getCustomField1(){ +// return userMapper.getCustomFields1(); +// } +// +// @GetMapping("/custom/2/") +// public List> getCustomField2() { +// return userMapper.getCustomFields2(); +// } +// +// @GetMapping("/custom/3/") +// public List getCustomField3() { +// return userMapper.getCustomFields3(); +// } +// +// @GetMapping("/count/") +// public Integer getUserCountByAge(@RequestParam Integer age) { +// return userMapper.getUserCountByAge(age); +// } +// +// @PutMapping("/name/1/") +// public Integer updateNameById(@RequestParam Integer id, +// @RequestParam String name) { +// return userMapper.updateUserNameById(id,name); +// } +// +// @PutMapping("/name/2/") +// public Integer updateNameByIdAndAge(@RequestParam Integer id, +// @RequestParam Integer age, +// @RequestParam String name) { +// return userMapper.updateUserNameByIdAndAge(id,age,name); +// } +// @DeleteMapping("/delete/") +// public Integer deleteUserByIdOrAge(@RequestParam Integer id, +// @RequestParam Integer age) { +// return userMapper.deleteUserByIdOrAge(id,age); +// } - @PutMapping("/name/1/") - public Integer updateNameById(@RequestParam Integer id, - @RequestParam String name) { - return userMapper.updateUserNameById(id,name); - } - @PutMapping("/name/2/") - public Integer updateNameByIdAndAge(@RequestParam Integer id, - @RequestParam Integer age, - @RequestParam String name) { - return userMapper.updateUserNameByIdAndAge(id,age,name); - } - @DeleteMapping("/delete/") - public Integer deleteUserByIdOrAge(@RequestParam Integer id, - @RequestParam Integer age) { - return userMapper.deleteUserByIdOrAge(id,age); - } } diff --git a/SpringDataJPA/src/main/java/cc/bnblogs/springdatajpa/mapper/UserMapper.java b/SpringDataJPA/src/main/java/cc/bnblogs/springdatajpa/mapper/UserMapper.java index cab6138..8785be3 100644 --- a/SpringDataJPA/src/main/java/cc/bnblogs/springdatajpa/mapper/UserMapper.java +++ b/SpringDataJPA/src/main/java/cc/bnblogs/springdatajpa/mapper/UserMapper.java @@ -6,7 +6,6 @@ import org.springframework.data.jpa.repository.JpaRepository; import org.springframework.data.jpa.repository.Modifying; import org.springframework.data.jpa.repository.Query; import org.springframework.data.repository.query.Param; -import org.springframework.stereotype.Repository; import org.springframework.transaction.annotation.Transactional; import java.util.List; @@ -18,7 +17,6 @@ import java.util.Map; * @author: zfp@bnblogs.cc * @date: 2023/3/7 15:29 */ -@Repository public interface UserMapper extends JpaRepository { @Query(value = "SELECT * FROM user", nativeQuery = true) List getInfo(); @@ -45,7 +43,7 @@ public interface UserMapper extends JpaRepository { @Modifying @Transactional - @Query(value = "update user u set u.name = ?3 where u.id > ?1 and u.age > ?2",nativeQuery = true) + @Query(value = "update user u set u.name = ?3 where u.id >= ?1 and u.age >= ?2",nativeQuery = true) int updateUserNameByIdAndAge(Integer id,Integer age, String name); @Modifying @@ -61,4 +59,8 @@ public interface UserMapper extends JpaRepository { @Query(value = "select new cc.bnblogs.springdatajpa.pojo.model.UserModel(u.id,u.name,u.age) from User u") List getCustomFields3(); + + User getUserByName(String name); + + User findUserById(int parseInt); } diff --git a/SpringDataJPA/src/main/java/cc/bnblogs/springdatajpa/pojo/User.java b/SpringDataJPA/src/main/java/cc/bnblogs/springdatajpa/pojo/User.java index 6e1147c..76a446d 100644 --- a/SpringDataJPA/src/main/java/cc/bnblogs/springdatajpa/pojo/User.java +++ b/SpringDataJPA/src/main/java/cc/bnblogs/springdatajpa/pojo/User.java @@ -1,20 +1,16 @@ package cc.bnblogs.springdatajpa.pojo; -import lombok.AllArgsConstructor; -import lombok.Builder; -import lombok.Data; -import lombok.NoArgsConstructor; - +import lombok.*; import javax.persistence.*; -import java.io.Serializable; + /** * @description: * @author: zfp@bnblogs.cc * @date: 2023/3/7 15:24 */ -@Data @Entity +@Data @AllArgsConstructor @NoArgsConstructor @Table(name = "user") @@ -22,9 +18,14 @@ public class User{ @Id @GeneratedValue(strategy = GenerationType.IDENTITY) private Integer id; + + @Column(name = "name") private String name; private Integer age; private String email; + + private String password; + } diff --git a/SpringDataJPA/src/main/java/cc/bnblogs/springdatajpa/pojo/model/UserModel.java b/SpringDataJPA/src/main/java/cc/bnblogs/springdatajpa/pojo/model/UserModel.java index b4d845e..2a16d71 100644 --- a/SpringDataJPA/src/main/java/cc/bnblogs/springdatajpa/pojo/model/UserModel.java +++ b/SpringDataJPA/src/main/java/cc/bnblogs/springdatajpa/pojo/model/UserModel.java @@ -1,19 +1,10 @@ package cc.bnblogs.springdatajpa.pojo.model; -import lombok.AllArgsConstructor; -import lombok.Data; -import lombok.Getter; -import lombok.NoArgsConstructor; - -import javax.persistence.Entity; - /** * @description: * @author: zfp@bnblogs.cc * @date: 2023/3/8 0:13 */ -@Data -@Getter public class UserModel { private Integer id; private String name; diff --git a/SpringDataJPA/src/main/java/cc/bnblogs/springdatajpa/service/impl/security/UserDetailServiceImpl.java b/SpringDataJPA/src/main/java/cc/bnblogs/springdatajpa/service/impl/security/UserDetailServiceImpl.java new file mode 100644 index 0000000..0255fdd --- /dev/null +++ b/SpringDataJPA/src/main/java/cc/bnblogs/springdatajpa/service/impl/security/UserDetailServiceImpl.java @@ -0,0 +1,30 @@ +package cc.bnblogs.springdatajpa.service.impl.security; + +import cc.bnblogs.springdatajpa.mapper.UserMapper; +import cc.bnblogs.springdatajpa.pojo.User; +import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.security.core.userdetails.UserDetails; +import org.springframework.security.core.userdetails.UserDetailsService; +import org.springframework.security.core.userdetails.UsernameNotFoundException; +import org.springframework.stereotype.Service; + +/** + * @description: + * @author: zfp@bnblogs.cc + * @date: 2023/3/8 17:42 + */ + +@Service +public class UserDetailServiceImpl implements UserDetailsService { + + @Autowired + private UserMapper userMapper; + @Override + public UserDetails loadUserByUsername(String username) throws UsernameNotFoundException { + User user = userMapper.getUserByName(username); + if (user==null) { + throw new RuntimeException("用户不存在"); + } + return new UserDetailsImpl(user); + } +} diff --git a/SpringDataJPA/src/main/java/cc/bnblogs/springdatajpa/service/impl/security/UserDetailsImpl.java b/SpringDataJPA/src/main/java/cc/bnblogs/springdatajpa/service/impl/security/UserDetailsImpl.java new file mode 100644 index 0000000..400c4d8 --- /dev/null +++ b/SpringDataJPA/src/main/java/cc/bnblogs/springdatajpa/service/impl/security/UserDetailsImpl.java @@ -0,0 +1,56 @@ +package cc.bnblogs.springdatajpa.service.impl.security; + +import cc.bnblogs.springdatajpa.pojo.User; +import lombok.AllArgsConstructor; +import lombok.Data; +import org.springframework.security.core.GrantedAuthority; +import org.springframework.security.core.userdetails.UserDetails; + +import java.util.Collection; + +/** + * @description: + * @author: zfp@bnblogs.cc + * @date: 2023/3/8 17:51 + */ +@Data +@AllArgsConstructor +public class UserDetailsImpl implements UserDetails { + + private User user; + @Override + public Collection getAuthorities() { + return null; + } + + @Override + public String getPassword() { + return user.getPassword(); + } + + @Override + public String getUsername() { + return user.getName(); + } + + @Override + public boolean isAccountNonExpired() { + return true; + } + + @Override + public boolean isAccountNonLocked() { + return true; + } + + @Override + public boolean isCredentialsNonExpired() { + return true; + } + + @Override + public boolean isEnabled() { + return true; + } + +} diff --git a/SpringDataJPA/src/main/java/cc/bnblogs/springdatajpa/service/impl/user/LoginServiceImpl.java b/SpringDataJPA/src/main/java/cc/bnblogs/springdatajpa/service/impl/user/LoginServiceImpl.java new file mode 100644 index 0000000..8324bd6 --- /dev/null +++ b/SpringDataJPA/src/main/java/cc/bnblogs/springdatajpa/service/impl/user/LoginServiceImpl.java @@ -0,0 +1,39 @@ +package cc.bnblogs.springdatajpa.service.impl.user; + +import cc.bnblogs.springdatajpa.pojo.User; +import cc.bnblogs.springdatajpa.service.impl.security.UserDetailsImpl; +import cc.bnblogs.springdatajpa.utils.JwtUtil; +import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.security.authentication.AuthenticationManager; +import org.springframework.security.authentication.UsernamePasswordAuthenticationToken; +import org.springframework.security.core.Authentication; +import org.springframework.stereotype.Service; + +import java.util.HashMap; +import java.util.Map; + +/** + * @description: 根据用户名和密码返回一个jwt_token + * @author: zfp@bnblogs.cc + * @date: 2023/3/8 21:34 + */ +@Service +public class LoginServiceImpl { + @Autowired + private AuthenticationManager authenticationManager; + + public Map getToken(String username, String password) { + UsernamePasswordAuthenticationToken authenticationToken = new UsernamePasswordAuthenticationToken(username, password); + + Authentication authenticate = authenticationManager.authenticate(authenticationToken); + UserDetailsImpl loginUser = (UserDetailsImpl) authenticate.getPrincipal(); + User user = loginUser.getUser(); + String jwt = JwtUtil.createJWT(user.getId().toString()); + + Map map = new HashMap<>(); + map.put("error_message", "success"); + map.put("token", jwt); + + return map; + } +} diff --git a/SpringDataJPA/src/main/java/cc/bnblogs/springdatajpa/service/impl/user/RegisterServiceImpl.java b/SpringDataJPA/src/main/java/cc/bnblogs/springdatajpa/service/impl/user/RegisterServiceImpl.java new file mode 100644 index 0000000..2385620 --- /dev/null +++ b/SpringDataJPA/src/main/java/cc/bnblogs/springdatajpa/service/impl/user/RegisterServiceImpl.java @@ -0,0 +1,87 @@ +package cc.bnblogs.springdatajpa.service.impl.user; + +import cc.bnblogs.springdatajpa.mapper.UserMapper; +import cc.bnblogs.springdatajpa.pojo.User; +import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.security.crypto.password.PasswordEncoder; +import org.springframework.stereotype.Service; + +import java.util.HashMap; +import java.util.Map; + +/** + * @description: 用户注册 + * @author: zfp@bnblogs.cc + * @date: 2023/3/8 22:12 + */ +@Service +public class RegisterServiceImpl { + + @Autowired + private UserMapper userMapper; + + @Autowired + private PasswordEncoder passwordEncoder; + + public Map register(String username, String password, String confirmedPassword) { + Map map = new HashMap<>(); + if (username == null) { + map.put("error_message", "用户名不能为空"); + return map; + } + + if (password == null || confirmedPassword == null) { + map.put("error_message", "密码不能为空"); + return map; + } + //删除首尾的空白字符 + username = username.trim(); + if (username.length() == 0) { + map.put("error_message", "用户名不能为空"); + return map; + } + + if (password.length() == 0 || confirmedPassword.length() == 0) { + map.put("error_message", "密码不能为空"); + return map; + } + + if (username.length() > 100) { + map.put("error_message", "用户名长度不能大于100"); + return map; + } + + if (password.length() > 100 || confirmedPassword.length() > 100) { + map.put("error_message", "密码不能大于100"); + return map; + } + + if (!password.equals(confirmedPassword)) { + map.put("error_message", "两次输入的密码不一致"); + return map; + } + + //查询用户名是否重复 + + User user = userMapper.getUserByName(username); + + if (user != null) { + map.put("error_message", "用户名已存在"); + return map; + } + + // 添加一个新用户 + String encodedPassword = passwordEncoder.encode(password); + + User u = new User(); + u.setName(username); + u.setAge(18); + u.setEmail("xxxxx"); + u.setPassword(encodedPassword); + userMapper.save(u); + + map.put("error_message", "success"); + return map; + } + } + diff --git a/SpringDataJPA/src/main/java/cc/bnblogs/springdatajpa/service/impl/user/UserInfoServiceImpl.java b/SpringDataJPA/src/main/java/cc/bnblogs/springdatajpa/service/impl/user/UserInfoServiceImpl.java new file mode 100644 index 0000000..d0cdd80 --- /dev/null +++ b/SpringDataJPA/src/main/java/cc/bnblogs/springdatajpa/service/impl/user/UserInfoServiceImpl.java @@ -0,0 +1,36 @@ +package cc.bnblogs.springdatajpa.service.impl.user; + +import cc.bnblogs.springdatajpa.pojo.User; +import cc.bnblogs.springdatajpa.service.impl.security.UserDetailsImpl; +import org.springframework.security.authentication.UsernamePasswordAuthenticationToken; +import org.springframework.security.core.context.SecurityContextHolder; +import org.springframework.stereotype.Service; + +import java.util.HashMap; +import java.util.Map; + +/** + * @description: 用户信息 + * @author: zfp@bnblogs.cc + * @date: 2023/3/8 22:12 + */ +@Service +public class UserInfoServiceImpl { + + /** + * 根据token返回用户信息 + * @return map存储的信息 + */ + public Map getInfo() { + UsernamePasswordAuthenticationToken authentication = (UsernamePasswordAuthenticationToken) SecurityContextHolder.getContext().getAuthentication(); + + UserDetailsImpl loginUser = (UserDetailsImpl) authentication.getPrincipal(); + User user = loginUser.getUser(); + + Map map = new HashMap<>(); + map.put("error_message", "success"); + map.put("id", user.getId().toString()); + map.put("name", user.getName()); + return map; + } +} diff --git a/SpringDataJPA/src/main/java/cc/bnblogs/springdatajpa/utils/JwtUtil.java b/SpringDataJPA/src/main/java/cc/bnblogs/springdatajpa/utils/JwtUtil.java new file mode 100644 index 0000000..383bd4a --- /dev/null +++ b/SpringDataJPA/src/main/java/cc/bnblogs/springdatajpa/utils/JwtUtil.java @@ -0,0 +1,68 @@ +package cc.bnblogs.springdatajpa.utils; + +/** + * @description: + * @author: zfp@bnblogs.cc + * @date: 2023/3/8 20:33 + */ + +import io.jsonwebtoken.Claims; +import io.jsonwebtoken.JwtBuilder; +import io.jsonwebtoken.Jwts; +import io.jsonwebtoken.SignatureAlgorithm; +import org.springframework.stereotype.Component; + +import javax.crypto.SecretKey; +import javax.crypto.spec.SecretKeySpec; +import java.util.Base64; +import java.util.Date; +import java.util.UUID; + +@Component +public class JwtUtil { + public static final long JWT_TTL = 60 * 60 * 1000L * 24 * 14; // 有效期14天 + public static final String JWT_KEY = "SDFGjhdsfalshdfHFdsjkdsfds121232131afasdfac"; + + public static String getUUID() { + return UUID.randomUUID().toString().replaceAll("-", ""); + } + + public static String createJWT(String subject) { + JwtBuilder builder = getJwtBuilder(subject, null, getUUID()); + return builder.compact(); + } + + private static JwtBuilder getJwtBuilder(String subject, Long ttlMillis, String uuid) { + SignatureAlgorithm signatureAlgorithm = SignatureAlgorithm.HS256; + SecretKey secretKey = generalKey(); + long nowMillis = System.currentTimeMillis(); + Date now = new Date(nowMillis); + if (ttlMillis == null) { + ttlMillis = JwtUtil.JWT_TTL; + } + + long expMillis = nowMillis + ttlMillis; + Date expDate = new Date(expMillis); + return Jwts.builder() + .setId(uuid) + .setSubject(subject) + .setIssuer("sg") + .setIssuedAt(now) + .signWith(signatureAlgorithm, secretKey) + .setExpiration(expDate); + } + + public static SecretKey generalKey() { + byte[] encodeKey = Base64.getDecoder().decode(JwtUtil.JWT_KEY); + return new SecretKeySpec(encodeKey, 0, encodeKey.length, "HmacSHA256"); + } + + public static Claims parseJWT(String jwt) throws Exception { + SecretKey secretKey = generalKey(); + return Jwts.parserBuilder() + .setSigningKey(secretKey) + .build() + .parseClaimsJws(jwt) + .getBody(); + } +} \ No newline at end of file diff --git a/SpringDataJPA/src/test/java/cc/bnblogs/springdatajpa/config/SecurityConfigTest.java b/SpringDataJPA/src/test/java/cc/bnblogs/springdatajpa/config/SecurityConfigTest.java new file mode 100644 index 0000000..20f63fc --- /dev/null +++ b/SpringDataJPA/src/test/java/cc/bnblogs/springdatajpa/config/SecurityConfigTest.java @@ -0,0 +1,35 @@ +package cc.bnblogs.springdatajpa.config; + +import org.junit.jupiter.api.Test; +import org.springframework.boot.test.context.SpringBootTest; +import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder; +import org.springframework.security.crypto.password.PasswordEncoder; +import sun.security.util.Password; + +import static org.junit.jupiter.api.Assertions.*; + +/** + * @description: + * @author: zfp@bnblogs.cc + * @date: 2023/3/8 17:13 + */ +@SpringBootTest +class SecurityConfigTest { + + @Test + void passwordEncoder() { + PasswordEncoder passwordEncoder = new BCryptPasswordEncoder(); + // 对明文加密 + System.out.println(passwordEncoder.encode("123456")); + System.out.println(passwordEncoder.encode("123456")); + System.out.println(passwordEncoder.encode("123456")); + System.out.println(passwordEncoder.encode("123456")); + System.out.println(passwordEncoder.encode("123456")); + + // 明文和密文匹配 + // true + System.out.println(passwordEncoder.matches("123456","$2a$10$8ew9orusgSjo4fRBODHgBug6aOkJwaq3ikAOVRAtwPkCqVMVLJI.O")); + // false + System.out.println(passwordEncoder.matches("1234567","$2a$10$8ew9orusgSjo4fRBODHgBug6aOkJwaq3ikAOVRAtwPkCqVMVLJI.O")); + } +} \ No newline at end of file diff --git a/SpringDataJPA/src/test/java/cc/bnblogs/springdatajpa/mapper/UserMapperTest.java b/SpringDataJPA/src/test/java/cc/bnblogs/springdatajpa/mapper/UserMapperTest.java index 27baba1..c02107e 100644 --- a/SpringDataJPA/src/test/java/cc/bnblogs/springdatajpa/mapper/UserMapperTest.java +++ b/SpringDataJPA/src/test/java/cc/bnblogs/springdatajpa/mapper/UserMapperTest.java @@ -19,7 +19,7 @@ class UserMapperTest { private UserMapper userMapper; @Test void save() { - User user = new User(null,"lyl",20,"xxx@qq.com"); + User user = new User(null,"lyl",20,"xxx@qq.com","1111"); userMapper.save(user); }