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