Compare commits
13 Commits
4a0c392ce6
...
dev
Author | SHA1 | Date | |
---|---|---|---|
ed65fd0b36 | |||
aab93e0141 | |||
dbf5e8760f | |||
3295a33aac | |||
14e3eda3a9 | |||
7c6116f2c5 | |||
85709591e1 | |||
1dda90a1c8 | |||
21fe0db209 | |||
fbaee8aa4c | |||
af0213bb4e | |||
![]() |
f82ed5c415 | ||
![]() |
b100acd9e3 |
@@ -1,16 +0,0 @@
|
|||||||
package com.example.springdemo.config;
|
|
||||||
|
|
||||||
import lombok.Data;
|
|
||||||
import org.springframework.boot.context.properties.ConfigurationProperties;
|
|
||||||
import org.springframework.stereotype.Component;
|
|
||||||
|
|
||||||
@Data
|
|
||||||
@Component
|
|
||||||
@ConfigurationProperties(prefix = "spring.datasource")
|
|
||||||
public class DataBaseProperties {
|
|
||||||
private String driverClassName;
|
|
||||||
private String url;
|
|
||||||
private String username;
|
|
||||||
private String password;
|
|
||||||
}
|
|
||||||
|
|
@@ -0,0 +1,71 @@
|
|||||||
|
package com.example.springdemo.controller;
|
||||||
|
|
||||||
|
import com.example.springdemo.security.dto.JwtAuthResponse;
|
||||||
|
import com.example.springdemo.security.dto.LoginDto;
|
||||||
|
import com.example.springdemo.service.AuthService;
|
||||||
|
import com.example.springdemo.utils.Result;
|
||||||
|
import jakarta.annotation.Resource;
|
||||||
|
import jakarta.servlet.http.HttpServletRequest;
|
||||||
|
import org.jetbrains.annotations.NotNull;
|
||||||
|
import org.springframework.http.ResponseEntity;
|
||||||
|
import org.springframework.security.authentication.UsernamePasswordAuthenticationToken;
|
||||||
|
import org.springframework.security.core.userdetails.UserDetails;
|
||||||
|
import org.springframework.security.core.userdetails.UserDetailsService;
|
||||||
|
import org.springframework.util.StringUtils;
|
||||||
|
import org.springframework.web.bind.annotation.PostMapping;
|
||||||
|
import org.springframework.web.bind.annotation.RequestBody;
|
||||||
|
import org.springframework.web.bind.annotation.RequestMapping;
|
||||||
|
import org.springframework.web.bind.annotation.RestController;
|
||||||
|
|
||||||
|
@RestController
|
||||||
|
@RequestMapping("/auth")
|
||||||
|
public class AuthController {
|
||||||
|
@Resource
|
||||||
|
private AuthService authService;
|
||||||
|
|
||||||
|
@Resource
|
||||||
|
private UserDetailsService userDetailsService;
|
||||||
|
|
||||||
|
// Login REST API
|
||||||
|
@PostMapping("/login")
|
||||||
|
public ResponseEntity<JwtAuthResponse> authenticate(@RequestBody LoginDto loginDto) {
|
||||||
|
String token = authService.login(loginDto);
|
||||||
|
|
||||||
|
JwtAuthResponse jwtAuthResponse = new JwtAuthResponse(token);
|
||||||
|
|
||||||
|
return ResponseEntity.ok(jwtAuthResponse);
|
||||||
|
}
|
||||||
|
|
||||||
|
@PostMapping("/profile")
|
||||||
|
public Result<Object> profile(@NotNull HttpServletRequest request) {
|
||||||
|
String token;
|
||||||
|
String bearerToken = request.getHeader("Authorization");
|
||||||
|
Result<Object> result = new Result<>();
|
||||||
|
// 从 request 获取 JWT token
|
||||||
|
if (StringUtils.hasText(bearerToken) && bearerToken.startsWith("Bearer ")) {
|
||||||
|
token = bearerToken.substring(7);
|
||||||
|
} else {
|
||||||
|
token = "";
|
||||||
|
}
|
||||||
|
// 校验 token
|
||||||
|
if (StringUtils.hasText(token) && authService.getJwtTokenProvider().validateToken(token)) {
|
||||||
|
// 从 token 获取 username
|
||||||
|
String username = authService.getJwtTokenProvider().getUsername(token);
|
||||||
|
// 加载与 token 关联的用户
|
||||||
|
UserDetails userDetails = userDetailsService.loadUserByUsername(username);
|
||||||
|
UsernamePasswordAuthenticationToken authenticationToken = new UsernamePasswordAuthenticationToken(
|
||||||
|
userDetails,
|
||||||
|
null,
|
||||||
|
userDetails.getAuthorities()
|
||||||
|
);
|
||||||
|
result.setStatus(200);
|
||||||
|
result.setMessage("success");
|
||||||
|
result.setData(authenticationToken);
|
||||||
|
} else {
|
||||||
|
result.setStatus(401);
|
||||||
|
result.setMessage("fail");
|
||||||
|
}
|
||||||
|
return result;
|
||||||
|
}
|
||||||
|
|
||||||
|
}
|
@@ -2,7 +2,6 @@ package com.example.springdemo.controller;
|
|||||||
|
|
||||||
import com.example.springdemo.entities.RBAC.Permissions;
|
import com.example.springdemo.entities.RBAC.Permissions;
|
||||||
import com.example.springdemo.service.PermissionsService;
|
import com.example.springdemo.service.PermissionsService;
|
||||||
import com.example.springdemo.utils.RoleVerificationAnnotation;
|
|
||||||
import jakarta.annotation.Resource;
|
import jakarta.annotation.Resource;
|
||||||
import org.springframework.web.bind.annotation.*;
|
import org.springframework.web.bind.annotation.*;
|
||||||
|
|
||||||
@@ -11,7 +10,6 @@ import java.util.Optional;
|
|||||||
|
|
||||||
@RestController
|
@RestController
|
||||||
@RequestMapping("/permissions")
|
@RequestMapping("/permissions")
|
||||||
@RoleVerificationAnnotation(UserIDList = {1})
|
|
||||||
public class PermissionsController {
|
public class PermissionsController {
|
||||||
@Resource
|
@Resource
|
||||||
private PermissionsService permissionsService;
|
private PermissionsService permissionsService;
|
||||||
|
@@ -2,14 +2,12 @@ package com.example.springdemo.controller;
|
|||||||
|
|
||||||
import com.example.springdemo.entities.RBAC.Roles;
|
import com.example.springdemo.entities.RBAC.Roles;
|
||||||
import com.example.springdemo.service.RolesService;
|
import com.example.springdemo.service.RolesService;
|
||||||
import com.example.springdemo.utils.RoleVerificationAnnotation;
|
|
||||||
import jakarta.annotation.Resource;
|
import jakarta.annotation.Resource;
|
||||||
import org.springframework.web.bind.annotation.*;
|
import org.springframework.web.bind.annotation.*;
|
||||||
|
|
||||||
import java.util.List;
|
import java.util.List;
|
||||||
import java.util.Optional;
|
import java.util.Optional;
|
||||||
|
|
||||||
@RoleVerificationAnnotation(UserIDList = {1})
|
|
||||||
@RestController
|
@RestController
|
||||||
@RequestMapping("/roles")
|
@RequestMapping("/roles")
|
||||||
public class RolesController {
|
public class RolesController {
|
||||||
|
@@ -2,14 +2,13 @@ package com.example.springdemo.controller;
|
|||||||
|
|
||||||
import com.example.springdemo.entities.RBAC.RolesPermissions;
|
import com.example.springdemo.entities.RBAC.RolesPermissions;
|
||||||
import com.example.springdemo.service.RolesPermissionsService;
|
import com.example.springdemo.service.RolesPermissionsService;
|
||||||
import com.example.springdemo.utils.RoleVerificationAnnotation;
|
|
||||||
import jakarta.annotation.Resource;
|
import jakarta.annotation.Resource;
|
||||||
import org.springframework.web.bind.annotation.*;
|
import org.springframework.web.bind.annotation.*;
|
||||||
|
|
||||||
import java.util.List;
|
import java.util.List;
|
||||||
import java.util.Optional;
|
import java.util.Optional;
|
||||||
|
|
||||||
@RoleVerificationAnnotation(UserIDList = {1})
|
|
||||||
@RestController
|
@RestController
|
||||||
@RequestMapping("/rolesPermissions")
|
@RequestMapping("/rolesPermissions")
|
||||||
public class RolesPermissionsController {
|
public class RolesPermissionsController {
|
||||||
|
@@ -22,10 +22,9 @@ public class UsersController {
|
|||||||
//添加新用户
|
//添加新用户
|
||||||
@PreAuthorize("hasRole('管理员') or hasAuthority('添加用户')")
|
@PreAuthorize("hasRole('管理员') or hasAuthority('添加用户')")
|
||||||
@PostMapping("/add")
|
@PostMapping("/add")
|
||||||
public Users addUsers(@RequestBody @NotNull wrapperUserAndPassword wrapperUserAndPassword) {
|
public Users addUsers(@RequestBody @NotNull Users user,
|
||||||
return usersService.addUser(
|
@RequestParam(name = "password") @NotNull String password) {
|
||||||
wrapperUserAndPassword.user,
|
return usersService.addUser(user, password);
|
||||||
wrapperUserAndPassword.userPassword);
|
|
||||||
}
|
}
|
||||||
|
|
||||||
@Data
|
@Data
|
||||||
|
@@ -10,15 +10,15 @@ public interface UsersPasswordRepository
|
|||||||
extends JpaRepository<UsersPassword, Long> {
|
extends JpaRepository<UsersPassword, Long> {
|
||||||
|
|
||||||
//修改密码
|
//修改密码
|
||||||
@Query("update UsersPassword UsersPwd set UsersPwd.password = ?1 where UsersPwd.users.id = ?2")
|
@Query("update UsersPassword UsersPwd set UsersPwd.password = ?1 where UsersPwd.user.id = ?2")
|
||||||
int updatePassword(String password, Long userID);
|
int updatePassword(String password, Long userID);
|
||||||
|
|
||||||
//删除账户时删除密码
|
//删除账户时删除密码
|
||||||
void deleteByUsersId(Long userID);
|
void deleteByUserId(Long userID);
|
||||||
|
|
||||||
//根据用户ID查找密码
|
//根据用户ID查找密码
|
||||||
UsersPassword findByUsersId(Long userID);
|
UsersPassword findByUserId(Long userID);
|
||||||
|
|
||||||
//根据用户名查找密码
|
//根据用户名查找密码
|
||||||
UsersPassword findByUsersName(String userName);
|
UsersPassword findByUserName(String userName);
|
||||||
}
|
}
|
||||||
|
@@ -18,7 +18,12 @@ public class UsersPassword {
|
|||||||
|
|
||||||
@OneToOne(cascade = CascadeType.ALL, fetch = FetchType.LAZY)
|
@OneToOne(cascade = CascadeType.ALL, fetch = FetchType.LAZY)
|
||||||
@JoinColumn(name = "usersId", referencedColumnName = "id")
|
@JoinColumn(name = "usersId", referencedColumnName = "id")
|
||||||
private Users users;
|
private Users user;
|
||||||
|
|
||||||
private String password;
|
private String password;
|
||||||
|
|
||||||
|
public UsersPassword(Users user, String password) {
|
||||||
|
this.user = user;
|
||||||
|
this.password = password;
|
||||||
|
}
|
||||||
}
|
}
|
||||||
|
@@ -1,36 +0,0 @@
|
|||||||
package com.example.springdemo.security;
|
|
||||||
|
|
||||||
import org.jetbrains.annotations.NotNull;
|
|
||||||
import org.springframework.context.annotation.Bean;
|
|
||||||
import org.springframework.context.annotation.Configuration;
|
|
||||||
import org.springframework.security.config.Customizer;
|
|
||||||
import org.springframework.security.config.annotation.authentication.configuration.EnableGlobalAuthentication;
|
|
||||||
import org.springframework.security.config.annotation.method.configuration.EnableMethodSecurity;
|
|
||||||
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.configurers.AbstractHttpConfigurer;
|
|
||||||
import org.springframework.security.config.annotation.web.configurers.LogoutConfigurer;
|
|
||||||
import org.springframework.security.web.SecurityFilterChain;
|
|
||||||
|
|
||||||
@Configuration
|
|
||||||
@EnableWebSecurity // Enable Spring Security
|
|
||||||
@EnableGlobalAuthentication // Enable Spring Security's global authentication configuration
|
|
||||||
@EnableMethodSecurity(prePostEnabled = true) // Enable Spring Security's method security
|
|
||||||
public class SecurityConfig {
|
|
||||||
@Bean
|
|
||||||
public SecurityFilterChain SecurityFilterChain(@NotNull HttpSecurity http) throws Exception {
|
|
||||||
var ignoreUrls = new String[]{"/login", "/logout", "/error"};
|
|
||||||
var authedUrls = new String[]{"/users/*/**"};
|
|
||||||
http
|
|
||||||
.authorizeHttpRequests(
|
|
||||||
(request) -> request
|
|
||||||
.requestMatchers(authedUrls).authenticated() // authenticate all requests to authedUrls
|
|
||||||
.requestMatchers(ignoreUrls).permitAll() // permit all requests to ignoreUrls
|
|
||||||
)
|
|
||||||
.formLogin(Customizer.withDefaults())
|
|
||||||
.httpBasic(Customizer.withDefaults())
|
|
||||||
.csrf(AbstractHttpConfigurer::disable)
|
|
||||||
.logout(LogoutConfigurer::permitAll);
|
|
||||||
return http.build();
|
|
||||||
}
|
|
||||||
}
|
|
@@ -0,0 +1,56 @@
|
|||||||
|
package com.example.springdemo.security.config;
|
||||||
|
|
||||||
|
import com.example.springdemo.security.jwt.JwtAuthenticationFilter;
|
||||||
|
import org.jetbrains.annotations.NotNull;
|
||||||
|
import org.springframework.beans.factory.InitializingBean;
|
||||||
|
import org.springframework.context.annotation.Bean;
|
||||||
|
import org.springframework.context.annotation.Configuration;
|
||||||
|
import org.springframework.security.authentication.AuthenticationManager;
|
||||||
|
import org.springframework.security.config.Customizer;
|
||||||
|
import org.springframework.security.config.annotation.authentication.configuration.AuthenticationConfiguration;
|
||||||
|
import org.springframework.security.config.annotation.authentication.configuration.EnableGlobalAuthentication;
|
||||||
|
import org.springframework.security.config.annotation.method.configuration.EnableMethodSecurity;
|
||||||
|
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.configurers.AbstractHttpConfigurer;
|
||||||
|
import org.springframework.security.config.http.SessionCreationPolicy;
|
||||||
|
import org.springframework.security.web.SecurityFilterChain;
|
||||||
|
import org.springframework.security.web.authentication.AnonymousAuthenticationFilter;
|
||||||
|
|
||||||
|
@Configuration
|
||||||
|
@EnableWebSecurity // Enable Spring Security
|
||||||
|
@EnableGlobalAuthentication // Enable Spring Security's global authentication configuration
|
||||||
|
@EnableMethodSecurity(prePostEnabled = true, securedEnabled = false) // Enable Spring Security's method security
|
||||||
|
public class SecurityFilterChainConfig implements InitializingBean {
|
||||||
|
@Bean
|
||||||
|
public SecurityFilterChain SecurityFilterChain(@NotNull HttpSecurity http,
|
||||||
|
JwtAuthenticationFilter jwtAuthenticationFilter) throws Exception {
|
||||||
|
var ignoreUrls = new String[]{"/auth/**"};
|
||||||
|
var authedUrls = new String[]{"/users/*/**"};
|
||||||
|
http
|
||||||
|
.authorizeHttpRequests(
|
||||||
|
(request) -> request
|
||||||
|
.requestMatchers(authedUrls).authenticated() // authenticate all requests to authedUrls
|
||||||
|
.requestMatchers(ignoreUrls).permitAll() // permit all requests to ignoreUrls
|
||||||
|
.anyRequest().authenticated() // authenticate all other requests
|
||||||
|
)
|
||||||
|
.httpBasic(Customizer.withDefaults())
|
||||||
|
.csrf(AbstractHttpConfigurer::disable)
|
||||||
|
.sessionManagement(session -> session.sessionCreationPolicy(SessionCreationPolicy.STATELESS))
|
||||||
|
.formLogin(AbstractHttpConfigurer::disable)
|
||||||
|
.logout(AbstractHttpConfigurer::disable)
|
||||||
|
.addFilterBefore(jwtAuthenticationFilter, AnonymousAuthenticationFilter.class); // jwt filter;
|
||||||
|
return http.build();
|
||||||
|
}
|
||||||
|
|
||||||
|
@Bean
|
||||||
|
public AuthenticationManager authenticationManager
|
||||||
|
(@NotNull AuthenticationConfiguration configuration) throws Exception {
|
||||||
|
return configuration.getAuthenticationManager();
|
||||||
|
}
|
||||||
|
|
||||||
|
@Override
|
||||||
|
public void afterPropertiesSet() throws Exception {
|
||||||
|
|
||||||
|
}
|
||||||
|
}
|
@@ -0,0 +1,20 @@
|
|||||||
|
package com.example.springdemo.security.dto;
|
||||||
|
|
||||||
|
import lombok.Getter;
|
||||||
|
import lombok.NoArgsConstructor;
|
||||||
|
import lombok.Setter;
|
||||||
|
|
||||||
|
@Setter
|
||||||
|
@Getter
|
||||||
|
@NoArgsConstructor
|
||||||
|
public class JwtAuthResponse {
|
||||||
|
private String accessToken;
|
||||||
|
private String tokenType;
|
||||||
|
|
||||||
|
public JwtAuthResponse(String accessToken) {
|
||||||
|
this.accessToken = accessToken;
|
||||||
|
this.tokenType = "Bearer ";
|
||||||
|
}
|
||||||
|
|
||||||
|
}
|
||||||
|
|
@@ -0,0 +1,11 @@
|
|||||||
|
package com.example.springdemo.security.dto;
|
||||||
|
|
||||||
|
import lombok.Getter;
|
||||||
|
import lombok.Setter;
|
||||||
|
|
||||||
|
@Getter
|
||||||
|
@Setter
|
||||||
|
public class LoginDto {
|
||||||
|
private String username;
|
||||||
|
private String password;
|
||||||
|
}
|
@@ -0,0 +1,40 @@
|
|||||||
|
package com.example.springdemo.security.events;
|
||||||
|
|
||||||
|
import com.example.springdemo.security.utils.JwtTokenProvider;
|
||||||
|
import com.example.springdemo.utils.Result;
|
||||||
|
import jakarta.annotation.Resource;
|
||||||
|
import jakarta.servlet.ServletException;
|
||||||
|
import jakarta.servlet.http.HttpServletRequest;
|
||||||
|
import jakarta.servlet.http.HttpServletResponse;
|
||||||
|
import lombok.extern.slf4j.Slf4j;
|
||||||
|
import org.jetbrains.annotations.NotNull;
|
||||||
|
import org.springframework.security.core.Authentication;
|
||||||
|
import org.springframework.stereotype.Component;
|
||||||
|
|
||||||
|
import java.io.IOException;
|
||||||
|
|
||||||
|
@Slf4j
|
||||||
|
@Component
|
||||||
|
public class AuthSuccess {
|
||||||
|
@Resource
|
||||||
|
private JwtTokenProvider JwtTokenProvider;
|
||||||
|
|
||||||
|
public void onAuthSuccess(HttpServletRequest request,
|
||||||
|
@NotNull HttpServletResponse response,
|
||||||
|
@NotNull Authentication authentication) throws IOException, ServletException {
|
||||||
|
Result<Object> result = Result.of(200, "Login success");
|
||||||
|
|
||||||
|
log.info("User {} login success", authentication.getName());
|
||||||
|
|
||||||
|
String token = JwtTokenProvider.generateToken(authentication);
|
||||||
|
|
||||||
|
result.setData(token);
|
||||||
|
|
||||||
|
String responseJson = result.toString();
|
||||||
|
|
||||||
|
response.setCharacterEncoding("UTF-8");
|
||||||
|
response.setContentType("application/json; charset=utf-8");
|
||||||
|
response.getWriter().println(responseJson);
|
||||||
|
response.getWriter().flush();
|
||||||
|
}
|
||||||
|
}
|
@@ -0,0 +1,21 @@
|
|||||||
|
package com.example.springdemo.security.jwt;
|
||||||
|
|
||||||
|
import jakarta.servlet.ServletException;
|
||||||
|
import jakarta.servlet.http.HttpServletRequest;
|
||||||
|
import jakarta.servlet.http.HttpServletResponse;
|
||||||
|
import org.jetbrains.annotations.NotNull;
|
||||||
|
import org.springframework.security.core.AuthenticationException;
|
||||||
|
import org.springframework.security.web.AuthenticationEntryPoint;
|
||||||
|
import org.springframework.stereotype.Component;
|
||||||
|
|
||||||
|
import java.io.IOException;
|
||||||
|
|
||||||
|
@Component("JwtAuthenticationEntryPoint")
|
||||||
|
public class JwtAuthenticationEntryPoint implements AuthenticationEntryPoint {
|
||||||
|
@Override
|
||||||
|
public void commence(HttpServletRequest request,
|
||||||
|
@NotNull HttpServletResponse response,
|
||||||
|
@NotNull AuthenticationException authException) throws IOException, ServletException {
|
||||||
|
response.sendError(HttpServletResponse.SC_UNAUTHORIZED, authException.getMessage());
|
||||||
|
}
|
||||||
|
}
|
@@ -0,0 +1,65 @@
|
|||||||
|
package com.example.springdemo.security.jwt;
|
||||||
|
|
||||||
|
import com.example.springdemo.security.utils.JwtTokenProvider;
|
||||||
|
import jakarta.servlet.FilterChain;
|
||||||
|
import jakarta.servlet.ServletException;
|
||||||
|
import jakarta.servlet.http.HttpServletRequest;
|
||||||
|
import jakarta.servlet.http.HttpServletResponse;
|
||||||
|
import org.jetbrains.annotations.NotNull;
|
||||||
|
import org.springframework.security.authentication.UsernamePasswordAuthenticationToken;
|
||||||
|
import org.springframework.security.core.context.SecurityContextHolder;
|
||||||
|
import org.springframework.security.core.userdetails.UserDetails;
|
||||||
|
import org.springframework.security.core.userdetails.UserDetailsService;
|
||||||
|
import org.springframework.security.web.authentication.WebAuthenticationDetailsSource;
|
||||||
|
import org.springframework.stereotype.Component;
|
||||||
|
import org.springframework.util.StringUtils;
|
||||||
|
import org.springframework.web.filter.OncePerRequestFilter;
|
||||||
|
|
||||||
|
import java.io.IOException;
|
||||||
|
|
||||||
|
@Component
|
||||||
|
public class JwtAuthenticationFilter extends OncePerRequestFilter {
|
||||||
|
private final JwtTokenProvider jwtTokenProvider;
|
||||||
|
private final UserDetailsService userDetailsService;
|
||||||
|
|
||||||
|
public JwtAuthenticationFilter(JwtTokenProvider jwtTokenProvider, UserDetailsService userDetailsService) {
|
||||||
|
this.jwtTokenProvider = jwtTokenProvider;
|
||||||
|
this.userDetailsService = userDetailsService;
|
||||||
|
}
|
||||||
|
|
||||||
|
@Override
|
||||||
|
protected void doFilterInternal(@NotNull HttpServletRequest request,
|
||||||
|
@NotNull HttpServletResponse response,
|
||||||
|
@NotNull FilterChain filterChain) throws ServletException, IOException {
|
||||||
|
// 从 request 获取 JWT token
|
||||||
|
String token = getTokenFromRequest(request);
|
||||||
|
// 校验 token
|
||||||
|
if (StringUtils.hasText(token) && jwtTokenProvider.validateToken(token)) {
|
||||||
|
// 从 token 获取 username
|
||||||
|
String username = jwtTokenProvider.getUsername(token);
|
||||||
|
// 加载与 token 关联的用户
|
||||||
|
UserDetails userDetails = userDetailsService.loadUserByUsername(username);
|
||||||
|
UsernamePasswordAuthenticationToken authenticationToken = new UsernamePasswordAuthenticationToken(
|
||||||
|
userDetails,
|
||||||
|
null,
|
||||||
|
userDetails.getAuthorities()
|
||||||
|
);
|
||||||
|
authenticationToken.setDetails(new WebAuthenticationDetailsSource().buildDetails(request));
|
||||||
|
// 获取安全上下文
|
||||||
|
SecurityContextHolder.getContext().setAuthentication(authenticationToken);
|
||||||
|
|
||||||
|
}
|
||||||
|
filterChain.doFilter(request, response);
|
||||||
|
}
|
||||||
|
|
||||||
|
private @NotNull String getTokenFromRequest(@NotNull HttpServletRequest request) {
|
||||||
|
|
||||||
|
String bearerToken = request.getHeader("Authorization");
|
||||||
|
|
||||||
|
if (StringUtils.hasText(bearerToken) && bearerToken.startsWith("Bearer ")) {
|
||||||
|
return bearerToken.substring(7);
|
||||||
|
} else {
|
||||||
|
return "";
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
@@ -0,0 +1,88 @@
|
|||||||
|
package com.example.springdemo.security.utils;
|
||||||
|
|
||||||
|
import io.jsonwebtoken.*;
|
||||||
|
import io.jsonwebtoken.io.Decoders;
|
||||||
|
import io.jsonwebtoken.security.Keys;
|
||||||
|
import lombok.extern.slf4j.Slf4j;
|
||||||
|
import org.jetbrains.annotations.Contract;
|
||||||
|
import org.jetbrains.annotations.NotNull;
|
||||||
|
import org.slf4j.Logger;
|
||||||
|
import org.slf4j.LoggerFactory;
|
||||||
|
import org.springframework.beans.factory.annotation.Value;
|
||||||
|
import org.springframework.security.core.Authentication;
|
||||||
|
import org.springframework.stereotype.Component;
|
||||||
|
|
||||||
|
import java.security.Key;
|
||||||
|
import java.util.Date;
|
||||||
|
|
||||||
|
@Component
|
||||||
|
@Slf4j
|
||||||
|
public class JwtTokenProvider {
|
||||||
|
private static final Logger logger = LoggerFactory.getLogger(JwtTokenProvider.class);
|
||||||
|
|
||||||
|
private String jwtSecret;
|
||||||
|
|
||||||
|
@Value("${app.jwt-expiration-milliseconds}")
|
||||||
|
private long jwtExpirationDate;
|
||||||
|
|
||||||
|
private void setJwtSecret() {
|
||||||
|
this.jwtSecret = Keys.secretKeyFor(SignatureAlgorithm.HS512).toString();
|
||||||
|
}
|
||||||
|
|
||||||
|
// 生成 JWT token
|
||||||
|
public String generateToken(@NotNull Authentication authentication) {
|
||||||
|
// 用户名
|
||||||
|
String username = authentication.getName();
|
||||||
|
|
||||||
|
// 当前时间
|
||||||
|
Date currentDate = new Date();
|
||||||
|
|
||||||
|
// 过期时间
|
||||||
|
Date expireDate = new Date(currentDate.getTime() + jwtExpirationDate);
|
||||||
|
|
||||||
|
return Jwts.builder()
|
||||||
|
.setSubject(username)
|
||||||
|
.setIssuedAt(new Date())
|
||||||
|
.setExpiration(expireDate)
|
||||||
|
.signWith(key())
|
||||||
|
.compact();
|
||||||
|
}
|
||||||
|
|
||||||
|
@Contract(" -> new")
|
||||||
|
private @NotNull Key key() {
|
||||||
|
if (jwtSecret == null) {
|
||||||
|
this.setJwtSecret();
|
||||||
|
}
|
||||||
|
return Keys.hmacShaKeyFor(jwtSecret.getBytes());
|
||||||
|
}
|
||||||
|
|
||||||
|
// 从 Jwt token 获取用户名
|
||||||
|
public String getUsername(String token) {
|
||||||
|
Claims claims = Jwts.parserBuilder()
|
||||||
|
.setSigningKey(key())
|
||||||
|
.build()
|
||||||
|
.parseClaimsJws(token)
|
||||||
|
.getBody();
|
||||||
|
return claims.getSubject();
|
||||||
|
}
|
||||||
|
|
||||||
|
// 验证 Jwt token
|
||||||
|
public boolean validateToken(String token) {
|
||||||
|
try {
|
||||||
|
Jwts.parserBuilder()
|
||||||
|
.setSigningKey(key())
|
||||||
|
.build()
|
||||||
|
.parse(token);
|
||||||
|
return true;
|
||||||
|
} catch (MalformedJwtException e) {
|
||||||
|
logger.error("Invalid JWT token: {}", e.getMessage());
|
||||||
|
} catch (ExpiredJwtException e) {
|
||||||
|
logger.error("JWT token is expired: {}", e.getMessage());
|
||||||
|
} catch (UnsupportedJwtException e) {
|
||||||
|
logger.error("JWT token is unsupported: {}", e.getMessage());
|
||||||
|
} catch (IllegalArgumentException e) {
|
||||||
|
logger.error("JWT claims string is empty: {}", e.getMessage());
|
||||||
|
}
|
||||||
|
return false;
|
||||||
|
}
|
||||||
|
}
|
@@ -0,0 +1,10 @@
|
|||||||
|
package com.example.springdemo.service;
|
||||||
|
|
||||||
|
import com.example.springdemo.security.dto.LoginDto;
|
||||||
|
import com.example.springdemo.security.utils.JwtTokenProvider;
|
||||||
|
|
||||||
|
public interface AuthService {
|
||||||
|
String login(LoginDto loginDto);
|
||||||
|
|
||||||
|
JwtTokenProvider getJwtTokenProvider();
|
||||||
|
}
|
@@ -9,7 +9,7 @@ import java.util.Optional;
|
|||||||
|
|
||||||
public interface UsersService extends UserDetailsService {
|
public interface UsersService extends UserDetailsService {
|
||||||
|
|
||||||
Users addUser(Users user, UsersPassword userPassword);
|
Users addUser(Users user, String password);
|
||||||
|
|
||||||
void deleteUserById(Long userId);
|
void deleteUserById(Long userId);
|
||||||
|
|
||||||
|
@@ -0,0 +1,34 @@
|
|||||||
|
package com.example.springdemo.serviceImpl;
|
||||||
|
|
||||||
|
import com.example.springdemo.security.dto.LoginDto;
|
||||||
|
import com.example.springdemo.security.utils.JwtTokenProvider;
|
||||||
|
import com.example.springdemo.service.AuthService;
|
||||||
|
import jakarta.annotation.Resource;
|
||||||
|
import org.jetbrains.annotations.NotNull;
|
||||||
|
import org.springframework.security.authentication.AuthenticationManager;
|
||||||
|
import org.springframework.security.authentication.UsernamePasswordAuthenticationToken;
|
||||||
|
import org.springframework.security.core.Authentication;
|
||||||
|
import org.springframework.security.core.context.SecurityContextHolder;
|
||||||
|
import org.springframework.stereotype.Service;
|
||||||
|
|
||||||
|
@Service
|
||||||
|
public class AuthServiceImpl implements AuthService {
|
||||||
|
@Resource
|
||||||
|
private AuthenticationManager authenticationManager;
|
||||||
|
@Resource
|
||||||
|
private JwtTokenProvider jwtTokenProvider;
|
||||||
|
|
||||||
|
@Override
|
||||||
|
public String login(@NotNull LoginDto loginDto) {
|
||||||
|
Authentication authentication = authenticationManager.authenticate(
|
||||||
|
new UsernamePasswordAuthenticationToken(loginDto.getUsername(), loginDto.getPassword())
|
||||||
|
);
|
||||||
|
SecurityContextHolder.getContext().setAuthentication(authentication);
|
||||||
|
return jwtTokenProvider.generateToken(authentication);
|
||||||
|
}
|
||||||
|
|
||||||
|
@Override
|
||||||
|
public JwtTokenProvider getJwtTokenProvider() {
|
||||||
|
return jwtTokenProvider;
|
||||||
|
}
|
||||||
|
}
|
@@ -15,7 +15,6 @@ import org.springframework.security.core.authority.SimpleGrantedAuthority;
|
|||||||
import org.springframework.security.core.userdetails.User;
|
import org.springframework.security.core.userdetails.User;
|
||||||
import org.springframework.security.core.userdetails.UserDetails;
|
import org.springframework.security.core.userdetails.UserDetails;
|
||||||
import org.springframework.security.core.userdetails.UsernameNotFoundException;
|
import org.springframework.security.core.userdetails.UsernameNotFoundException;
|
||||||
import org.springframework.stereotype.Component;
|
|
||||||
import org.springframework.stereotype.Service;
|
import org.springframework.stereotype.Service;
|
||||||
import org.springframework.transaction.annotation.Transactional;
|
import org.springframework.transaction.annotation.Transactional;
|
||||||
|
|
||||||
@@ -25,7 +24,6 @@ import java.util.List;
|
|||||||
import java.util.Optional;
|
import java.util.Optional;
|
||||||
|
|
||||||
@Service
|
@Service
|
||||||
@Component
|
|
||||||
public class UsersServiceImpl implements UsersService {
|
public class UsersServiceImpl implements UsersService {
|
||||||
@Resource
|
@Resource
|
||||||
private UsersRepository usersRepository;
|
private UsersRepository usersRepository;
|
||||||
@@ -39,8 +37,9 @@ public class UsersServiceImpl implements UsersService {
|
|||||||
@Override
|
@Override
|
||||||
@Transactional(rollbackFor = Exception.class)
|
@Transactional(rollbackFor = Exception.class)
|
||||||
//添加用户时同步添加密码
|
//添加用户时同步添加密码
|
||||||
public Users addUser(Users user, UsersPassword userPassword) {
|
public Users addUser(Users user, String password) {
|
||||||
Users u = usersRepository.save(user);
|
Users u = usersRepository.save(user);
|
||||||
|
UsersPassword userPassword = new UsersPassword(u, password);
|
||||||
usersPasswordRepository.save(userPassword);
|
usersPasswordRepository.save(userPassword);
|
||||||
return u;
|
return u;
|
||||||
}
|
}
|
||||||
@@ -49,8 +48,8 @@ public class UsersServiceImpl implements UsersService {
|
|||||||
@Transactional(rollbackFor = Exception.class)
|
@Transactional(rollbackFor = Exception.class)
|
||||||
//删除用户时同步删除密码
|
//删除用户时同步删除密码
|
||||||
public void deleteUserById(Long userId) {
|
public void deleteUserById(Long userId) {
|
||||||
|
usersPasswordRepository.deleteByUserId(userId);
|
||||||
usersRepository.deleteById(userId);
|
usersRepository.deleteById(userId);
|
||||||
usersPasswordRepository.deleteByUsersId(userId);
|
|
||||||
}
|
}
|
||||||
|
|
||||||
@Override
|
@Override
|
||||||
@@ -64,7 +63,7 @@ public class UsersServiceImpl implements UsersService {
|
|||||||
//获取用户ID
|
//获取用户ID
|
||||||
userId = usersRepository.findByName(name).get().getId();
|
userId = usersRepository.findByName(name).get().getId();
|
||||||
//删除密码
|
//删除密码
|
||||||
usersPasswordRepository.deleteByUsersId(userId);
|
usersPasswordRepository.deleteByUserId(userId);
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -109,7 +108,7 @@ public class UsersServiceImpl implements UsersService {
|
|||||||
throw new UsernameNotFoundException("用户名不存在");
|
throw new UsernameNotFoundException("用户名不存在");
|
||||||
}
|
}
|
||||||
// 取出密码
|
// 取出密码
|
||||||
String password = usersPasswordRepository.findByUsersId(user.getId()).getPassword();
|
String password = usersPasswordRepository.findByUserId(user.getId()).getPassword();
|
||||||
|
|
||||||
// 用户角色
|
// 用户角色
|
||||||
Roles role = user.getRoles();
|
Roles role = user.getRoles();
|
||||||
|
@@ -0,0 +1,4 @@
|
|||||||
|
package com.example.springdemo.utils;
|
||||||
|
|
||||||
|
public class UtilsClass {
|
||||||
|
}
|
@@ -1,4 +1,4 @@
|
|||||||
package com.example.springdemo.utils;
|
package com.example.springdemo.utils.verificationAnnotation;
|
||||||
|
|
||||||
import jakarta.servlet.http.HttpServletRequest;
|
import jakarta.servlet.http.HttpServletRequest;
|
||||||
import jakarta.servlet.http.HttpServletResponse;
|
import jakarta.servlet.http.HttpServletResponse;
|
@@ -1,4 +1,4 @@
|
|||||||
package com.example.springdemo.utils;
|
package com.example.springdemo.utils.verificationAnnotation;
|
||||||
|
|
||||||
// 在Controller中使用该注解,可以实现权限验证
|
// 在Controller中使用该注解,可以实现权限验证
|
||||||
|
|
@@ -1,6 +1,7 @@
|
|||||||
package com.example.springdemo.utils;
|
package com.example.springdemo.utils.verificationAnnotation;
|
||||||
|
|
||||||
import com.example.springdemo.entities.Users;
|
import com.example.springdemo.entities.Users;
|
||||||
|
import com.example.springdemo.utils.Result;
|
||||||
import jakarta.servlet.http.HttpServletRequest;
|
import jakarta.servlet.http.HttpServletRequest;
|
||||||
import org.aspectj.lang.ProceedingJoinPoint;
|
import org.aspectj.lang.ProceedingJoinPoint;
|
||||||
import org.aspectj.lang.Signature;
|
import org.aspectj.lang.Signature;
|
||||||
@@ -20,7 +21,7 @@ import java.lang.reflect.Method;
|
|||||||
@Component
|
@Component
|
||||||
@Aspect
|
@Aspect
|
||||||
public class RoleVerificationAspect {
|
public class RoleVerificationAspect {
|
||||||
@Pointcut("@annotation(com.example.springdemo.utils.RoleVerificationAnnotation)")
|
@Pointcut("@annotation(com.example.springdemo.utils.verificationAnnotation.RoleVerificationAnnotation)")
|
||||||
public void roleVerification() {
|
public void roleVerification() {
|
||||||
}
|
}
|
||||||
|
|
@@ -8,6 +8,7 @@ spring.datasource.url=jdbc:sqlserver://106.54.219.245:1433;\
|
|||||||
loginTimeout=30;
|
loginTimeout=30;
|
||||||
spring.datasource.username=myh
|
spring.datasource.username=myh
|
||||||
spring.datasource.password=20231103#MS_Sql
|
spring.datasource.password=20231103#MS_Sql
|
||||||
|
|
||||||
# JPA config
|
# JPA config
|
||||||
spring.jpa.hibernate.ddl-auto=none
|
spring.jpa.hibernate.ddl-auto=none
|
||||||
spring.jpa.show-sql=true
|
spring.jpa.show-sql=true
|
||||||
@@ -15,6 +16,11 @@ spring.jpa.properties.hibernate.format_sql=true
|
|||||||
spring.jpa.properties.hibernate.dialect=org.hibernate.dialect.SQLServerDialect
|
spring.jpa.properties.hibernate.dialect=org.hibernate.dialect.SQLServerDialect
|
||||||
spring.jpa.hibernate.naming.physical-strategy=org.hibernate.boot.model.naming.PhysicalNamingStrategyStandardImpl
|
spring.jpa.hibernate.naming.physical-strategy=org.hibernate.boot.model.naming.PhysicalNamingStrategyStandardImpl
|
||||||
spring.jpa.properties.hibernate.enable_lazy_load_no_trans=true
|
spring.jpa.properties.hibernate.enable_lazy_load_no_trans=true
|
||||||
|
spring.jpa.open-in-view=false
|
||||||
|
|
||||||
# spring security config
|
# spring security config
|
||||||
spring.security.user.name=anchor
|
# spring.security.user.name=anchor
|
||||||
spring.security.user.password=20172
|
# spring.security.user.password=20172
|
||||||
|
|
||||||
|
# Jwt default expiration time is 15 minutes
|
||||||
|
app.jwt-expiration-milliseconds = 900000
|
@@ -1,51 +0,0 @@
|
|||||||
<?xml version="1.0" encoding="UTF-8"?>
|
|
||||||
<!DOCTYPE hibernate-configuration PUBLIC
|
|
||||||
"-//Hibernate/Hibernate Configuration DTD 3.0//EN"
|
|
||||||
"http://www.hibernate.org/dtd/hibernate-configuration-3.0.dtd">
|
|
||||||
<hibernate-configuration>
|
|
||||||
<session-factory>
|
|
||||||
<!-- 连接数据库的基本参数 -->
|
|
||||||
<property name="hibernate.connection.driver_class">com.microsoft.sqlserver.jdbc.SQLServerDriver</property>
|
|
||||||
<property name="hibernate.connection.url">jdbc:sqlserver://intpointer.com:1433;\
|
|
||||||
databaseName=Elm;\
|
|
||||||
encrypt=true;\
|
|
||||||
trustServerCertificate=true;\
|
|
||||||
loginTimeout=30;
|
|
||||||
</property>
|
|
||||||
<property name="hibernate.connection.username">myh</property>
|
|
||||||
<property name="hibernate.connection.password">20231103#MS_Sql</property>
|
|
||||||
<!-- 配置Hibernate的方言 -->
|
|
||||||
<property name="hibernate.dialect">org.hibernate.dialect.SQLServerDialect</property>
|
|
||||||
|
|
||||||
<!-- 可选配置================ -->
|
|
||||||
<!-- 打印SQL -->
|
|
||||||
<property name="hibernate.show_sql">true</property>
|
|
||||||
<!-- 格式化SQL -->
|
|
||||||
<property name="hibernate.format_sql">true</property>
|
|
||||||
<!-- 自动创建表 -->
|
|
||||||
<property name="hibernate.hbm2ddl.auto">update</property>
|
|
||||||
|
|
||||||
<!-- <!– 配置C3P0连接池 –>-->
|
|
||||||
<!-- <property name="connection.provider_class">org.hibernate.connection.C3P0ConnectionProvider</property>-->
|
|
||||||
<!-- <!–在连接池中可用的数据库连接的最少数目 –>-->
|
|
||||||
<!-- <property name="c3p0.min_size">5</property>-->
|
|
||||||
<!-- <!–在连接池中所有数据库连接的最大数目 –>-->
|
|
||||||
<!-- <property name="c3p0.max_size">20</property>-->
|
|
||||||
<!-- <!–设定数据库连接的过期时间,以秒为单位,-->
|
|
||||||
<!-- 如果连接池中的某个数据库连接处于空闲状态的时间超过了timeout时间,就会从连接池中清除 –>-->
|
|
||||||
<!-- <property name="c3p0.timeout">120</property>-->
|
|
||||||
<!-- <!–每3000秒检查所有连接池中的空闲连接 以秒为单位–>-->
|
|
||||||
<!-- <property name="c3p0.idle_test_period">3000</property>-->
|
|
||||||
|
|
||||||
<!-- <!– 设置事务隔离级别 –>-->
|
|
||||||
<!-- <property name="hibernate.connection.isolation">4</property>-->
|
|
||||||
<!-- <!– 配置当前线程绑定的Session –>-->
|
|
||||||
<!-- <property name="hibernate.current_session_context_class">thread</property>-->
|
|
||||||
|
|
||||||
<!-- 引入映射 -->
|
|
||||||
<!-- <mapping resource="com/itheima/hibernate/domain/Customer.hbm.xml"/>
|
|
||||||
<mapping resource="com/itheima/hibernate/domain/LinkMan.hbm.xml"/> -->
|
|
||||||
<!-- <mapping resource="./"/>-->
|
|
||||||
<!-- <mapping resource="./"/>-->
|
|
||||||
</session-factory>
|
|
||||||
</hibernate-configuration>
|
|
@@ -9,16 +9,12 @@ import jakarta.annotation.Resource;
|
|||||||
import org.jetbrains.annotations.NotNull;
|
import org.jetbrains.annotations.NotNull;
|
||||||
import org.junit.jupiter.api.BeforeEach;
|
import org.junit.jupiter.api.BeforeEach;
|
||||||
import org.junit.jupiter.api.Test;
|
import org.junit.jupiter.api.Test;
|
||||||
import org.junit.runner.RunWith;
|
|
||||||
import org.springframework.boot.test.autoconfigure.web.servlet.AutoConfigureMockMvc;
|
import org.springframework.boot.test.autoconfigure.web.servlet.AutoConfigureMockMvc;
|
||||||
import org.springframework.boot.test.autoconfigure.web.servlet.WebMvcTest;
|
import org.springframework.boot.test.autoconfigure.web.servlet.WebMvcTest;
|
||||||
import org.springframework.boot.test.context.SpringBootTest;
|
|
||||||
import org.springframework.boot.test.mock.mockito.MockBean;
|
import org.springframework.boot.test.mock.mockito.MockBean;
|
||||||
import org.springframework.http.MediaType;
|
import org.springframework.http.MediaType;
|
||||||
import org.springframework.security.test.context.support.WithMockUser;
|
import org.springframework.security.test.context.support.WithMockUser;
|
||||||
import org.springframework.security.test.context.support.WithUserDetails;
|
|
||||||
import org.springframework.test.annotation.Rollback;
|
import org.springframework.test.annotation.Rollback;
|
||||||
import org.springframework.test.context.junit4.SpringRunner;
|
|
||||||
import org.springframework.test.web.servlet.MockMvc;
|
import org.springframework.test.web.servlet.MockMvc;
|
||||||
import org.springframework.test.web.servlet.MvcResult;
|
import org.springframework.test.web.servlet.MvcResult;
|
||||||
import org.springframework.test.web.servlet.request.MockMvcRequestBuilders;
|
import org.springframework.test.web.servlet.request.MockMvcRequestBuilders;
|
||||||
@@ -107,7 +103,7 @@ class UsersControllerTests {
|
|||||||
user.setAddress("test address");
|
user.setAddress("test address");
|
||||||
UsersPassword userPassword = new UsersPassword();
|
UsersPassword userPassword = new UsersPassword();
|
||||||
userPassword.setPassword("test1234567");
|
userPassword.setPassword("test1234567");
|
||||||
userPassword.setUsers(user);
|
userPassword.setUser(user);
|
||||||
|
|
||||||
UsersController.wrapperUserAndPassword usersAndPassword = new UsersController.wrapperUserAndPassword();
|
UsersController.wrapperUserAndPassword usersAndPassword = new UsersController.wrapperUserAndPassword();
|
||||||
usersAndPassword.setUser(user);
|
usersAndPassword.setUser(user);
|
||||||
@@ -143,7 +139,7 @@ class UsersControllerTests {
|
|||||||
user.setAddress("test address");
|
user.setAddress("test address");
|
||||||
UsersPassword userPassword = new UsersPassword();
|
UsersPassword userPassword = new UsersPassword();
|
||||||
userPassword.setPassword("test1234567");
|
userPassword.setPassword("test1234567");
|
||||||
userPassword.setUsers(user);
|
userPassword.setUser(user);
|
||||||
|
|
||||||
// Convert to JSON
|
// Convert to JSON
|
||||||
ObjectMapper mapper = new ObjectMapper();
|
ObjectMapper mapper = new ObjectMapper();
|
||||||
|
@@ -61,7 +61,7 @@ class UsersServiceTests {
|
|||||||
user1.setAddress("test address user1");
|
user1.setAddress("test address user1");
|
||||||
|
|
||||||
user1Password = new UsersPassword();
|
user1Password = new UsersPassword();
|
||||||
user1Password.setUsers(user1);
|
user1Password.setUser(user1);
|
||||||
user1Password.setPassword("TestPassword1");
|
user1Password.setPassword("TestPassword1");
|
||||||
|
|
||||||
user2 = new Users();
|
user2 = new Users();
|
||||||
@@ -71,7 +71,7 @@ class UsersServiceTests {
|
|||||||
user2.setAddress("test address user2");
|
user2.setAddress("test address user2");
|
||||||
|
|
||||||
user2Password = new UsersPassword();
|
user2Password = new UsersPassword();
|
||||||
user2Password.setUsers(user2);
|
user2Password.setUser(user2);
|
||||||
user2Password.setPassword("TestPassword2");
|
user2Password.setPassword("TestPassword2");
|
||||||
|
|
||||||
usersList.add(user1);
|
usersList.add(user1);
|
||||||
@@ -99,14 +99,14 @@ class UsersServiceTests {
|
|||||||
@Rollback(value = true)
|
@Rollback(value = true)
|
||||||
void testSaveUser() {
|
void testSaveUser() {
|
||||||
when(usersRepository.save(any())).thenReturn(user1);
|
when(usersRepository.save(any())).thenReturn(user1);
|
||||||
usersService.addUser(user1, user1Password);
|
usersService.addUser(user1, user1Password.getPassword());
|
||||||
verify(usersRepository, times(1)).save(any());
|
verify(usersRepository, times(1)).save(any());
|
||||||
}
|
}
|
||||||
|
|
||||||
@Test
|
@Test
|
||||||
@Rollback(value = true)
|
@Rollback(value = true)
|
||||||
void testGetAllUsers() {
|
void testGetAllUsers() {
|
||||||
usersService.addUser(user1, user1Password);
|
usersService.addUser(user1, user1Password.getPassword());
|
||||||
when(usersRepository.findAll()).thenReturn(usersList);
|
when(usersRepository.findAll()).thenReturn(usersList);
|
||||||
List<Users> usersList1 = usersService.findAllUsers();
|
List<Users> usersList1 = usersService.findAllUsers();
|
||||||
Assertions.assertEquals(usersList1, usersList);
|
Assertions.assertEquals(usersList1, usersList);
|
||||||
|
Reference in New Issue
Block a user