Compare commits
No commits in common. "3295a33aacbaf0f84554996c4ce72444ba6eced2" and "4a0c392ce697a59ab5a51de761d8b7a7b1cfea5d" have entirely different histories.
3295a33aac
...
4a0c392ce6
@ -0,0 +1,16 @@
|
|||||||
|
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;
|
||||||
|
}
|
||||||
|
|
@ -1,71 +0,0 @@
|
|||||||
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,6 +2,7 @@ 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.*;
|
||||||
|
|
||||||
@ -10,6 +11,7 @@ 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,12 +2,14 @@ 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,13 +2,14 @@ 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 {
|
||||||
|
@ -0,0 +1,36 @@
|
|||||||
|
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();
|
||||||
|
}
|
||||||
|
}
|
@ -1,56 +0,0 @@
|
|||||||
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 {
|
|
||||||
|
|
||||||
}
|
|
||||||
}
|
|
@ -1,20 +0,0 @@
|
|||||||
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 ";
|
|
||||||
}
|
|
||||||
|
|
||||||
}
|
|
||||||
|
|
@ -1,11 +0,0 @@
|
|||||||
package com.example.springdemo.security.dto;
|
|
||||||
|
|
||||||
import lombok.Getter;
|
|
||||||
import lombok.Setter;
|
|
||||||
|
|
||||||
@Getter
|
|
||||||
@Setter
|
|
||||||
public class LoginDto {
|
|
||||||
private String username;
|
|
||||||
private String password;
|
|
||||||
}
|
|
@ -1,40 +0,0 @@
|
|||||||
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();
|
|
||||||
}
|
|
||||||
}
|
|
@ -1,21 +0,0 @@
|
|||||||
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());
|
|
||||||
}
|
|
||||||
}
|
|
@ -1,65 +0,0 @@
|
|||||||
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 "";
|
|
||||||
}
|
|
||||||
}
|
|
||||||
}
|
|
@ -1,88 +0,0 @@
|
|||||||
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;
|
|
||||||
}
|
|
||||||
}
|
|
@ -1,10 +0,0 @@
|
|||||||
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();
|
|
||||||
}
|
|
@ -1,34 +0,0 @@
|
|||||||
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;
|
|
||||||
}
|
|
||||||
}
|
|
@ -1,4 +1,4 @@
|
|||||||
package com.example.springdemo.utils.verificationAnnotation;
|
package com.example.springdemo.utils;
|
||||||
|
|
||||||
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.verificationAnnotation;
|
package com.example.springdemo.utils;
|
||||||
|
|
||||||
// 在Controller中使用该注解,可以实现权限验证
|
// 在Controller中使用该注解,可以实现权限验证
|
||||||
|
|
@ -1,7 +1,6 @@
|
|||||||
package com.example.springdemo.utils.verificationAnnotation;
|
package com.example.springdemo.utils;
|
||||||
|
|
||||||
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;
|
||||||
@ -21,7 +20,7 @@ import java.lang.reflect.Method;
|
|||||||
@Component
|
@Component
|
||||||
@Aspect
|
@Aspect
|
||||||
public class RoleVerificationAspect {
|
public class RoleVerificationAspect {
|
||||||
@Pointcut("@annotation(com.example.springdemo.utils.verificationAnnotation.RoleVerificationAnnotation)")
|
@Pointcut("@annotation(com.example.springdemo.utils.RoleVerificationAnnotation)")
|
||||||
public void roleVerification() {
|
public void roleVerification() {
|
||||||
}
|
}
|
||||||
|
|
@ -1,4 +0,0 @@
|
|||||||
package com.example.springdemo.utils;
|
|
||||||
|
|
||||||
public class UtilsClass {
|
|
||||||
}
|
|
@ -8,7 +8,6 @@ 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
|
||||||
@ -16,11 +15,6 @@ 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
|
|
@ -4,26 +4,26 @@
|
|||||||
"http://www.hibernate.org/dtd/hibernate-configuration-3.0.dtd">
|
"http://www.hibernate.org/dtd/hibernate-configuration-3.0.dtd">
|
||||||
<hibernate-configuration>
|
<hibernate-configuration>
|
||||||
<session-factory>
|
<session-factory>
|
||||||
<!-- <!– 连接数据库的基本参数 –>-->
|
<!-- 连接数据库的基本参数 -->
|
||||||
<!-- <property name="hibernate.connection.driver_class">com.microsoft.sqlserver.jdbc.SQLServerDriver</property>-->
|
<property name="hibernate.connection.driver_class">com.microsoft.sqlserver.jdbc.SQLServerDriver</property>
|
||||||
<!-- <property name="hibernate.connection.url">jdbc:sqlserver://intpointer.com:1433;\-->
|
<property name="hibernate.connection.url">jdbc:sqlserver://intpointer.com:1433;\
|
||||||
<!-- databaseName=Elm;\-->
|
databaseName=Elm;\
|
||||||
<!-- encrypt=true;\-->
|
encrypt=true;\
|
||||||
<!-- trustServerCertificate=true;\-->
|
trustServerCertificate=true;\
|
||||||
<!-- loginTimeout=30;-->
|
loginTimeout=30;
|
||||||
<!-- </property>-->
|
</property>
|
||||||
<!-- <property name="hibernate.connection.username">myh</property>-->
|
<property name="hibernate.connection.username">myh</property>
|
||||||
<!-- <property name="hibernate.connection.password">20231103#MS_Sql</property>-->
|
<property name="hibernate.connection.password">20231103#MS_Sql</property>
|
||||||
<!-- <!– 配置Hibernate的方言 –>-->
|
<!-- 配置Hibernate的方言 -->
|
||||||
<!-- <property name="hibernate.dialect">org.hibernate.dialect.SQLServerDialect</property>-->
|
<property name="hibernate.dialect">org.hibernate.dialect.SQLServerDialect</property>
|
||||||
|
|
||||||
<!-- <!– 可选配置================ –>-->
|
<!-- 可选配置================ -->
|
||||||
<!-- <!– 打印SQL –>-->
|
<!-- 打印SQL -->
|
||||||
<!-- <property name="hibernate.show_sql">true</property>-->
|
<property name="hibernate.show_sql">true</property>
|
||||||
<!-- <!– 格式化SQL –>-->
|
<!-- 格式化SQL -->
|
||||||
<!-- <property name="hibernate.format_sql">true</property>-->
|
<property name="hibernate.format_sql">true</property>
|
||||||
<!-- <!– 自动创建表 –>-->
|
<!-- 自动创建表 -->
|
||||||
<!-- <property name="hibernate.hbm2ddl.auto">update</property>-->
|
<property name="hibernate.hbm2ddl.auto">update</property>
|
||||||
|
|
||||||
<!-- <!– 配置C3P0连接池 –>-->
|
<!-- <!– 配置C3P0连接池 –>-->
|
||||||
<!-- <property name="connection.provider_class">org.hibernate.connection.C3P0ConnectionProvider</property>-->
|
<!-- <property name="connection.provider_class">org.hibernate.connection.C3P0ConnectionProvider</property>-->
|
||||||
@ -45,7 +45,7 @@
|
|||||||
<!-- 引入映射 -->
|
<!-- 引入映射 -->
|
||||||
<!-- <mapping resource="com/itheima/hibernate/domain/Customer.hbm.xml"/>
|
<!-- <mapping resource="com/itheima/hibernate/domain/Customer.hbm.xml"/>
|
||||||
<mapping resource="com/itheima/hibernate/domain/LinkMan.hbm.xml"/> -->
|
<mapping resource="com/itheima/hibernate/domain/LinkMan.hbm.xml"/> -->
|
||||||
<!-- <mapping resource="./"/>-->
|
<!-- <mapping resource="./"/>-->
|
||||||
<!-- <mapping resource="./"/>-->
|
<!-- <mapping resource="./"/>-->
|
||||||
</session-factory>
|
</session-factory>
|
||||||
</hibernate-configuration>
|
</hibernate-configuration>
|
@ -9,12 +9,16 @@ 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;
|
||||||
|
Loading…
Reference in New Issue
Block a user