dev #1

Merged
bunny merged 20 commits from dev into master 2024-05-10 09:25:15 +08:00
13 changed files with 157 additions and 93 deletions
Showing only changes of commit 33738065ea - Show all commits

View File

@ -23,5 +23,10 @@
<artifactId>httpclient</artifactId> <artifactId>httpclient</artifactId>
<version>4.5.14</version> <version>4.5.14</version>
</dependency> </dependency>
<dependency>
<groupId>javax.xml.bind</groupId>
<artifactId>jaxb-api</artifactId>
<version>2.1</version>
</dependency>
</dependencies> </dependencies>
</project> </project>

View File

@ -11,7 +11,7 @@ public class JwtHelper {
public static String createToken(Long userId, String userName) { public static String createToken(Long userId, String userName) {
return Jwts.builder() return Jwts.builder()
.setSubject("OA-USER") .setSubject("Bunny-USER")
.setExpiration(new Date(System.currentTimeMillis() + tokenExpiration)) .setExpiration(new Date(System.currentTimeMillis() + tokenExpiration))
.claim("userId", userId) .claim("userId", userId)
.claim("userName", userName) .claim("userName", userName)
@ -27,7 +27,6 @@ public class JwtHelper {
Claims claims = claimsJws.getBody(); Claims claims = claimsJws.getBody();
Integer userId = (Integer) claims.get("userId"); Integer userId = (Integer) claims.get("userId");
return userId.longValue(); return userId.longValue();
// return 1L;
} }
public static String getUserName(String token) { public static String getUserName(String token) {

View File

@ -3,6 +3,7 @@ package cn.bunny.common.service.config;
import lombok.extern.slf4j.Slf4j; import lombok.extern.slf4j.Slf4j;
import org.jetbrains.annotations.NotNull; import org.jetbrains.annotations.NotNull;
import org.springframework.context.annotation.Configuration; import org.springframework.context.annotation.Configuration;
import org.springframework.web.servlet.config.annotation.CorsRegistry;
import org.springframework.web.servlet.config.annotation.ResourceHandlerRegistry; import org.springframework.web.servlet.config.annotation.ResourceHandlerRegistry;
import org.springframework.web.servlet.config.annotation.WebMvcConfigurer; import org.springframework.web.servlet.config.annotation.WebMvcConfigurer;
@ -17,4 +18,18 @@ public class WebMvcConfiguration implements WebMvcConfigurer {
registry.addResourceHandler("/doc.html").addResourceLocations("classpath:/META-INF/resources/"); registry.addResourceHandler("/doc.html").addResourceLocations("classpath:/META-INF/resources/");
registry.addResourceHandler("/webjars/**").addResourceLocations("classpath:/META-INF/resources/webjars/"); registry.addResourceHandler("/webjars/**").addResourceLocations("classpath:/META-INF/resources/webjars/");
} }
/**
* 跨域配置
*
* @param registry 跨域注册表
*/
@Override
public void addCorsMappings(CorsRegistry registry) {
registry.addMapping("/**")
// 是否发送Cookies
.allowCredentials(true)
// 放行哪些原始域
.allowedOriginPatterns("*").allowedMethods("GET", "POST", "PUT", "DELETE").allowedHeaders("*").exposedHeaders("*");
}
} }

View File

@ -2,6 +2,7 @@ package cn.bunny.common.service.context;
public class BaseContext { public class BaseContext {
private static final ThreadLocal<Long> userId = new ThreadLocal<>(); private static final ThreadLocal<Long> userId = new ThreadLocal<>();
private static final ThreadLocal<String> username = new ThreadLocal<String>();
private static final ThreadLocal<Long> wareId = new ThreadLocal<>(); private static final ThreadLocal<Long> wareId = new ThreadLocal<>();
private static final ThreadLocal<Long> adminId = new ThreadLocal<>(); private static final ThreadLocal<Long> adminId = new ThreadLocal<>();
@ -18,6 +19,14 @@ public class BaseContext {
userId.remove(); userId.remove();
} }
public static String getUsername() {
return username.get();
}
public static void setUsername(String _username) {
username.set(_username);
}
// adminId 相关 // adminId 相关
public static Long getAdminId() { public static Long getAdminId() {
return adminId.get(); return adminId.get();

View File

@ -1,14 +1,17 @@
package cn.bunny.security.config; package cn.bunny.security.config;
import cn.bunny.security.custom.CustomPasswordEncoder; import cn.bunny.security.custom.CustomPasswordEncoder;
import cn.bunny.security.handelr.*; import cn.bunny.security.filter.TokenAuthenticationFilter;
import cn.bunny.security.handelr.SecurityAccessDeniedHandler;
import cn.bunny.security.handelr.SecurityAuthenticationEntryPoint;
import cn.bunny.security.service.MyUserDetailsService; import cn.bunny.security.service.MyUserDetailsService;
import org.jetbrains.annotations.NotNull;
import org.springframework.beans.factory.annotation.Autowired; import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Bean; import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration; import org.springframework.context.annotation.Configuration;
import org.springframework.data.redis.core.RedisTemplate; import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.security.authentication.AuthenticationManager; import org.springframework.security.authentication.AuthenticationManager;
import org.springframework.security.authentication.ProviderManager; import org.springframework.security.authentication.AuthenticationProvider;
import org.springframework.security.authentication.dao.DaoAuthenticationProvider; import org.springframework.security.authentication.dao.DaoAuthenticationProvider;
import org.springframework.security.config.annotation.authentication.configuration.AuthenticationConfiguration; import org.springframework.security.config.annotation.authentication.configuration.AuthenticationConfiguration;
import org.springframework.security.config.annotation.method.configuration.EnableMethodSecurity; import org.springframework.security.config.annotation.method.configuration.EnableMethodSecurity;
@ -19,8 +22,7 @@ import org.springframework.security.config.http.SessionCreationPolicy;
import org.springframework.security.core.session.SessionRegistry; import org.springframework.security.core.session.SessionRegistry;
import org.springframework.security.core.session.SessionRegistryImpl; import org.springframework.security.core.session.SessionRegistryImpl;
import org.springframework.security.web.SecurityFilterChain; import org.springframework.security.web.SecurityFilterChain;
import org.springframework.security.web.authentication.UsernamePasswordAuthenticationFilter;
import static org.springframework.security.config.Customizer.withDefaults;
@Configuration @Configuration
@EnableWebSecurity @EnableWebSecurity
@ -32,62 +34,52 @@ public class WebSecurityConfig {
private MyUserDetailsService myUserDetailsService; private MyUserDetailsService myUserDetailsService;
@Autowired @Autowired
private CustomPasswordEncoder customPasswordEncoder; private CustomPasswordEncoder customPasswordEncoder;
@Autowired
private AuthenticationConfiguration authenticationConfiguration;
@Bean @Bean
public SecurityFilterChain filterChain(HttpSecurity httpSecurity) throws Exception { public SecurityFilterChain filterChain(HttpSecurity httpSecurity) throws Exception {
httpSecurity.authorizeHttpRequests(authorize -> { httpSecurity.authorizeHttpRequests(authorize -> {
authorize.requestMatchers("/", "/test/**", "/diagram-viewer/**", "/editor-app/**", "/*.html", authorize.requestMatchers("/", "/test/**", "/diagram-viewer/**", "/editor-app/**", "/*.html", "/admin/system/index/login",
"/admin/system/index/login", "/favicon.ico", "/swagger-resources/**", "/webjars/**", "/v3/**", "/swagger-ui.html/**", "/doc.html").permitAll().anyRequest().authenticated();
"/favicon.ico", "/swagger-resources/**", "/webjars/**", "/v3/**", "/swagger-ui.html/**", "/doc.html").permitAll().anyRequest().authenticated();
});
// 注销登录
httpSecurity
.logout(logout -> {
logout.logoutSuccessHandler(new SecurityLogoutSuccessHandler());
}) })
// 前端段分离不需要---禁用明文验证
.httpBasic(AbstractHttpConfigurer::disable)
// 前端段分离不需要---禁用默认登录页
.formLogin(AbstractHttpConfigurer::disable)
// 前端段分离不需要---禁用退出页
.logout(AbstractHttpConfigurer::disable)
// 前端段分离不需要---csrf攻击
.csrf(AbstractHttpConfigurer::disable)
// 跨域访问权限
.cors(AbstractHttpConfigurer::disable)
// 前后端分离不需要---因为是无状态的
.sessionManagement(session -> session.sessionCreationPolicy(SessionCreationPolicy.STATELESS))
.exceptionHandling(exception -> { .exceptionHandling(exception -> {
// 请求未授权接口 // 请求未授权接口
exception.authenticationEntryPoint(new SecurityAuthenticationEntryPoint()); exception.authenticationEntryPoint(new SecurityAuthenticationEntryPoint());
// 没有权限访问 // 没有权限访问
exception.accessDeniedHandler(new SecurityAccessDeniedHandler()); exception.accessDeniedHandler(new SecurityAccessDeniedHandler());
}) })
// 后登录的账号会使先登录的账号失效 // 记住我
.sessionManagement(session -> { .rememberMe(e -> e.rememberMeParameter("rememberBunny").rememberMeCookieName("rememberBunny").key("BunnyKey"))
// 禁用session // 自定义过滤器
session.sessionCreationPolicy(SessionCreationPolicy.STATELESS); // .addFilterAt(TokenLoginFilter(), UsernamePasswordAuthenticationFilter.class)
// 最大登录数为1 // .addFilter(new TokenLoginFilter(redisTemplate))
session.maximumSessions(1) .addFilterBefore(new TokenAuthenticationFilter(redisTemplate), UsernamePasswordAuthenticationFilter.class);
// 可以获取到所有登录的用户以及登录状态设置session状态
.sessionRegistry(sessionRegistry())
// 有相同用户已登录时
.expiredSessionStrategy(new SecuritySessionInformationExpiredStrategy());
// 会话失效同时内容
session.invalidSessionStrategy(new SecurityInvalidSessionStrategy());
});
// 关闭csrf攻击
httpSecurity.csrf(AbstractHttpConfigurer::disable);
// 跨域访问权限
httpSecurity.cors(withDefaults());
// 记住我
httpSecurity.rememberMe(e -> e.rememberMeParameter("rememberBunny").rememberMeCookieName("rememberBunny").key("BunnyKey"));
// 自定义过滤器
// httpSecurity.addFilterAt(loginFilter(), UsernamePasswordAuthenticationFilter.class);
// httpSecurity.addFilterBefore(new TokenAuthenticationFilter(redisTemplate), UsernamePasswordAuthenticationFilter.class);
// httpSecurity.addFilter(new TokenLoginFilter(authenticationConfiguration, redisTemplate));
return httpSecurity.build(); return httpSecurity.build();
} }
// 自定义用户认证和密码
@Bean @Bean
public AuthenticationManager authenticationManager() { public AuthenticationProvider authenticationProvider() {
DaoAuthenticationProvider provider = new DaoAuthenticationProvider(); DaoAuthenticationProvider provider = new DaoAuthenticationProvider();
provider.setPasswordEncoder(customPasswordEncoder); provider.setPasswordEncoder(customPasswordEncoder);
provider.setUserDetailsService(myUserDetailsService); provider.setUserDetailsService(myUserDetailsService);
return new ProviderManager(provider); return provider;
}
@Bean
public AuthenticationManager authenticationManager(@NotNull AuthenticationConfiguration config) throws Exception {
return config.getAuthenticationManager();
} }
@Bean @Bean

View File

@ -14,6 +14,7 @@ import java.util.function.Supplier;
public class CustomAuthorizationManager implements AuthorizationManager<RequestAuthorizationContext> { public class CustomAuthorizationManager implements AuthorizationManager<RequestAuthorizationContext> {
@Override @Override
public AuthorizationDecision check(Supplier<Authentication> authentication, RequestAuthorizationContext object) { public AuthorizationDecision check(Supplier<Authentication> authentication, RequestAuthorizationContext object) {
String token = object.getRequest().getHeader("token");
return null; return null;
} }
} }

View File

@ -1,13 +1,13 @@
package cn.bunny.security.filter; package cn.bunny.security.filter;
import cn.bunny.common.result.Result; import cn.bunny.common.service.context.BaseContext;
import cn.bunny.common.utils.ResponseUtil; import cn.bunny.common.utils.JwtHelper;
import cn.bunny.enums.ResultCodeEnum;
import com.alibaba.fastjson2.JSON; import com.alibaba.fastjson2.JSON;
import jakarta.servlet.FilterChain; import jakarta.servlet.FilterChain;
import jakarta.servlet.ServletException; import jakarta.servlet.ServletException;
import jakarta.servlet.http.HttpServletRequest; import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse; import jakarta.servlet.http.HttpServletResponse;
import org.jetbrains.annotations.NotNull;
import org.springframework.data.redis.core.RedisTemplate; import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.security.authentication.UsernamePasswordAuthenticationToken; import org.springframework.security.authentication.UsernamePasswordAuthenticationToken;
import org.springframework.security.core.authority.SimpleGrantedAuthority; import org.springframework.security.core.authority.SimpleGrantedAuthority;
@ -28,40 +28,46 @@ public class TokenAuthenticationFilter extends OncePerRequestFilter {
} }
@Override @Override
protected void doFilterInternal(HttpServletRequest request, HttpServletResponse response, FilterChain chain) throws ServletException, IOException { protected void doFilterInternal(HttpServletRequest request, @NotNull HttpServletResponse response, @NotNull FilterChain chain) throws ServletException, IOException {
// 如果是登录接口直接放行 String token = request.getHeader("token");
if ("/admin/system/index/login".equals(request.getRequestURI())) {
chain.doFilter(request, response); // login请求就没token直接放行因为后边有其他的过滤器
if (token == null) {
doFilter(request, response, chain);
return; return;
} }
// 如果是登录接口直接放行
UsernamePasswordAuthenticationToken authentication = getAuthentication(request); UsernamePasswordAuthenticationToken authentication = getAuthentication(request);
SecurityContextHolder.getContext().setAuthentication(authentication);
if (authentication != null) { chain.doFilter(request, response);
SecurityContextHolder.getContext().setAuthentication(authentication);
chain.doFilter(request, response);
} else {
ResponseUtil.out(response, Result.error(ResultCodeEnum.LOGIN_MOBLE_ERROR));
}
} }
private UsernamePasswordAuthenticationToken getAuthentication(HttpServletRequest request) { private UsernamePasswordAuthenticationToken getAuthentication(HttpServletRequest request) {
// 请求头是否有Token // 请求头是否有token
String token = request.getHeader("token"); String token = request.getHeader("token");
if (!StringUtils.hasText(token)) { if (!StringUtils.isEmpty(token)) {
Object authObject = redisTemplate.opsForValue().get(token); String username = JwtHelper.getUserName(token);
String authString = JSON.toJSONString(authObject); if (!StringUtils.isEmpty(username)) {
if (StringUtils.hasText(authString)) { // 当前用户信息放到ThreadLocal里面
List<Map> maplist = JSON.parseArray(authString, Map.class); BaseContext.setUserId(JwtHelper.getUserId(token));
System.out.println(maplist); BaseContext.setUsername(username);
List<SimpleGrantedAuthority> authList = new ArrayList<>();
for (Map map : maplist) { // 通过username从redis获取权限数据
String authority = (String) map.get("roleList"); String authString = (String) redisTemplate.opsForValue().get(username);
authList.add(new SimpleGrantedAuthority(authority)); // 把redis获取字符串权限数据转换要求集合类型 List<SimpleGrantedAuthority>
if (!StringUtils.isEmpty(authString)) {
List<Map> maplist = JSON.parseArray(authString, Map.class);
System.out.println(maplist);
List<SimpleGrantedAuthority> authList = new ArrayList<>();
for (Map map : maplist) {
String authority = (String) map.get("authority");
authList.add(new SimpleGrantedAuthority(authority));
}
return new UsernamePasswordAuthenticationToken(username, null, authList);
} else {
return new UsernamePasswordAuthenticationToken(username, null, new ArrayList<>());
} }
return new UsernamePasswordAuthenticationToken(token, null, authList);
} else {
return new UsernamePasswordAuthenticationToken(token, null, new ArrayList<>());
} }
} }
return null; return null;

View File

@ -1,6 +1,7 @@
package cn.bunny.security.filter; package cn.bunny.security.filter;
import cn.bunny.common.result.Result; import cn.bunny.common.result.Result;
import cn.bunny.common.utils.JwtHelper;
import cn.bunny.common.utils.ResponseUtil; import cn.bunny.common.utils.ResponseUtil;
import cn.bunny.enums.ResultCodeEnum; import cn.bunny.enums.ResultCodeEnum;
import cn.bunny.security.custom.CustomUser; import cn.bunny.security.custom.CustomUser;
@ -12,7 +13,6 @@ import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse; import jakarta.servlet.http.HttpServletResponse;
import org.springframework.data.redis.core.RedisTemplate; import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.security.authentication.UsernamePasswordAuthenticationToken; import org.springframework.security.authentication.UsernamePasswordAuthenticationToken;
import org.springframework.security.config.annotation.authentication.configuration.AuthenticationConfiguration;
import org.springframework.security.core.Authentication; import org.springframework.security.core.Authentication;
import org.springframework.security.core.AuthenticationException; import org.springframework.security.core.AuthenticationException;
import org.springframework.security.web.authentication.UsernamePasswordAuthenticationFilter; import org.springframework.security.web.authentication.UsernamePasswordAuthenticationFilter;
@ -21,13 +21,12 @@ import org.springframework.security.web.util.matcher.AntPathRequestMatcher;
import java.io.IOException; import java.io.IOException;
import java.util.HashMap; import java.util.HashMap;
import java.util.Map; import java.util.Map;
import java.util.UUID;
public class TokenLoginFilter extends UsernamePasswordAuthenticationFilter { public class TokenLoginFilter extends UsernamePasswordAuthenticationFilter {
private final RedisTemplate<String, Object> redisTemplate; private final RedisTemplate<String, Object> redisTemplate;
public TokenLoginFilter(AuthenticationConfiguration authenticationConfiguration, RedisTemplate<String, Object> redisTemplate) throws Exception { // 构造方法
this.setAuthenticationManager(authenticationConfiguration.getAuthenticationManager()); public TokenLoginFilter(RedisTemplate<String, Object> redisTemplate) {
this.setPostOnly(false); this.setPostOnly(false);
// 指定登录接口及提交方式可以指定任意路径 // 指定登录接口及提交方式可以指定任意路径
this.setRequiresAuthenticationRequestMatcher(new AntPathRequestMatcher("/admin/system/index/login", "POST")); this.setRequiresAuthenticationRequestMatcher(new AntPathRequestMatcher("/admin/system/index/login", "POST"));
@ -36,7 +35,8 @@ public class TokenLoginFilter extends UsernamePasswordAuthenticationFilter {
// 登录认证 // 登录认证
// 获取输入的用户名和密码调用方法认证 // 获取输入的用户名和密码调用方法认证
public Authentication attemptAuthentication(HttpServletRequest request, HttpServletResponse response) throws AuthenticationException { public Authentication attemptAuthentication(HttpServletRequest request, HttpServletResponse response)
throws AuthenticationException {
try { try {
// 获取用户信息 // 获取用户信息
LoginVo loginVo = new ObjectMapper().readValue(request.getInputStream(), LoginVo.class); LoginVo loginVo = new ObjectMapper().readValue(request.getInputStream(), LoginVo.class);
@ -54,10 +54,10 @@ public class TokenLoginFilter extends UsernamePasswordAuthenticationFilter {
// 获取当前用户 // 获取当前用户
CustomUser customUser = (CustomUser) auth.getPrincipal(); CustomUser customUser = (CustomUser) auth.getPrincipal();
// 生成token // 生成token
String token = UUID.randomUUID().toString(); String token = JwtHelper.createToken(customUser.getSysUser().getId(), customUser.getSysUser().getUsername());
// 获取当前用户权限数据放到Redis里面 keytoken value权限数据 // 获取当前用户权限数据放到Redis里面 keyusername value权限数据
redisTemplate.opsForValue().set(token, JSON.toJSONString(customUser.getAuthorities())); redisTemplate.opsForValue().set(customUser.getUsername(), JSON.toJSONString(customUser.getAuthorities()));
// 返回 // 返回
Map<String, Object> map = new HashMap<>(); Map<String, Object> map = new HashMap<>();
@ -69,4 +69,4 @@ public class TokenLoginFilter extends UsernamePasswordAuthenticationFilter {
protected void unsuccessfulAuthentication(HttpServletRequest request, HttpServletResponse response, AuthenticationException failed) { protected void unsuccessfulAuthentication(HttpServletRequest request, HttpServletResponse response, AuthenticationException failed) {
ResponseUtil.out(response, Result.error(null, ResultCodeEnum.LOGIN_MOBLE_ERROR)); ResponseUtil.out(response, Result.error(null, ResultCodeEnum.LOGIN_MOBLE_ERROR));
} }
} }

View File

@ -4,6 +4,8 @@ import cn.bunny.common.result.Result;
import io.swagger.v3.oas.annotations.Operation; import io.swagger.v3.oas.annotations.Operation;
import io.swagger.v3.oas.annotations.tags.Tag; import io.swagger.v3.oas.annotations.tags.Tag;
import org.springframework.beans.factory.annotation.Autowired; import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.core.context.SecurityContext;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.security.core.session.SessionInformation; import org.springframework.security.core.session.SessionInformation;
import org.springframework.security.core.session.SessionRegistry; import org.springframework.security.core.session.SessionRegistry;
import org.springframework.security.core.userdetails.User; import org.springframework.security.core.userdetails.User;
@ -25,6 +27,13 @@ public class BaseController {
return "欢迎访问"; return "欢迎访问";
} }
@Operation(summary = "Security上下文对象", description = "Security上下文对象")
@GetMapping("/test/getSecurityHolder")
public Result<Object> getSecurityHolder() {
SecurityContext context = SecurityContextHolder.getContext();
return Result.success(context);
}
@Operation(summary = "当前所有登录的用户", description = "当前所有登录的用户") @Operation(summary = "当前所有登录的用户", description = "当前所有登录的用户")
@GetMapping("/test/getAllUserLogin") @GetMapping("/test/getAllUserLogin")
public Result<Object> getAllUserLogin() { public Result<Object> getAllUserLogin() {

View File

@ -5,8 +5,8 @@ import cn.bunny.common.service.exception.BunnyException;
import cn.bunny.entity.system.SysRole; import cn.bunny.entity.system.SysRole;
import cn.bunny.entity.system.SysUser; import cn.bunny.entity.system.SysUser;
import cn.bunny.security.custom.CustomUser; import cn.bunny.security.custom.CustomUser;
import cn.bunny.service.mapper.SysRoleMapper;
import cn.bunny.service.mapper.SysUserMapper; import cn.bunny.service.mapper.SysUserMapper;
import cn.bunny.service.service.SysRoleService;
import com.baomidou.mybatisplus.core.toolkit.Wrappers; import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import org.springframework.beans.factory.annotation.Autowired; import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Configuration; import org.springframework.context.annotation.Configuration;
@ -21,11 +21,12 @@ public class MyUserDetailsService implements cn.bunny.security.service.MyUserDet
@Autowired @Autowired
private SysUserMapper sysUserMapper; private SysUserMapper sysUserMapper;
@Autowired @Autowired
private SysRoleService sysRoleService; private SysRoleMapper sysRoleMapper;
@Override @Override
public UserDetails loadUserByUsername(String username) throws UsernameNotFoundException { public UserDetails loadUserByUsername(String username) throws UsernameNotFoundException {
SysUser sysUser = sysUserMapper.selectOne(Wrappers.<SysUser>lambdaQuery().eq(SysUser::getUsername, username)); SysUser sysUser = sysUserMapper.selectOne(Wrappers.<SysUser>lambdaQuery().eq(SysUser::getUsername, username));
List<SysRole> sysRoleList = sysRoleMapper.selectList(null);
if (sysUser == null) { if (sysUser == null) {
throw new UsernameNotFoundException(MessageConstant.USER_DOES_NOT_EXIST); throw new UsernameNotFoundException(MessageConstant.USER_DOES_NOT_EXIST);
} }
@ -34,7 +35,6 @@ public class MyUserDetailsService implements cn.bunny.security.service.MyUserDet
throw new BunnyException(MessageConstant.ACCOUNT_LOCKED); throw new BunnyException(MessageConstant.ACCOUNT_LOCKED);
} }
List<SysRole> sysRoleList = sysRoleService.list();
List<String> roleAuthoritieList = sysRoleList.stream().map(SysRole::getRoleCode).toList(); List<String> roleAuthoritieList = sysRoleList.stream().map(SysRole::getRoleCode).toList();
return new CustomUser(sysUser, AuthorityUtils.createAuthorityList(roleAuthoritieList)); return new CustomUser(sysUser, AuthorityUtils.createAuthorityList(roleAuthoritieList));
} }

View File

@ -2,6 +2,7 @@ package cn.bunny.service.service.impl;
import cn.bunny.common.constant.MessageConstant; import cn.bunny.common.constant.MessageConstant;
import cn.bunny.common.service.exception.BunnyException; import cn.bunny.common.service.exception.BunnyException;
import cn.bunny.common.utils.JwtHelper;
import cn.bunny.common.utils.SnowflakeIdGenerator; import cn.bunny.common.utils.SnowflakeIdGenerator;
import cn.bunny.entity.system.Login; import cn.bunny.entity.system.Login;
import cn.bunny.entity.system.SysUser; import cn.bunny.entity.system.SysUser;
@ -16,8 +17,6 @@ import jakarta.servlet.http.HttpServletRequest;
import org.springframework.beans.factory.annotation.Autowired; import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate; import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.security.authentication.AuthenticationManager; import org.springframework.security.authentication.AuthenticationManager;
import org.springframework.security.authentication.UsernamePasswordAuthenticationToken;
import org.springframework.security.core.Authentication;
import org.springframework.stereotype.Service; import org.springframework.stereotype.Service;
import org.springframework.util.DigestUtils; import org.springframework.util.DigestUtils;
@ -48,7 +47,6 @@ public class SysUserServiceImpl extends ServiceImpl<SysUserMapper, SysUser> impl
public Login login(LoginVo vo) { public Login login(LoginVo vo) {
String username = vo.getUsername(); String username = vo.getUsername();
String password = vo.getPassword(); String password = vo.getPassword();
long snowId = snowflakeIdGenerator.nextId();
// 查询用户信息 // 查询用户信息
LambdaQueryWrapper<SysUser> wrapper = new LambdaQueryWrapper<>(); LambdaQueryWrapper<SysUser> wrapper = new LambdaQueryWrapper<>();
wrapper.eq(SysUser::getUsername, username); wrapper.eq(SysUser::getUsername, username);
@ -69,12 +67,13 @@ public class SysUserServiceImpl extends ServiceImpl<SysUserMapper, SysUser> impl
if (!md5DigestAsHexPassword.equals(sysUser.getPassword())) { if (!md5DigestAsHexPassword.equals(sysUser.getPassword())) {
throw new BunnyException(MessageConstant.PASSWORD_ERROR); throw new BunnyException(MessageConstant.PASSWORD_ERROR);
} }
UsernamePasswordAuthenticationToken authentication = new UsernamePasswordAuthenticationToken(vo.getUsername(), vo.getPassword());
Authentication authenticate = authenticationManager.authenticate(authentication);
redisTemplate.opsForValue().set(String.valueOf(snowId), authenticate);
// 添加token // 添加token
return Login.builder().token(String.valueOf(snowId)).build(); String token = JwtHelper.createToken(sysUser.getId(), sysUser.getUsername());
// UsernamePasswordAuthenticationToken authentication = new UsernamePasswordAuthenticationToken(vo.getUsername(), vo.getPassword());
// Authentication authenticate = authenticationManager.authenticate(authentication);
// long snowId = snowflakeIdGenerator.nextId();
// redisTemplate.opsForValue().set(String.valueOf(snowId), authenticate);
return Login.builder().token(token).build();
} }
/** /**

View File

@ -2,11 +2,13 @@ package cn.bunny.service.task;
import lombok.extern.slf4j.Slf4j; import lombok.extern.slf4j.Slf4j;
import org.springframework.scheduling.annotation.Scheduled; import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Component;
@Component
@Slf4j @Slf4j
public class TemplateTask { public class TemplateTask {
@Scheduled(cron = "0/1 * * * * ?") @Scheduled(cron = "0/1 5 * * * ?")
public void templateTask() { public void templateTask() {
log.warn("TemplateTask..."); log.info("定时任务执行...");
} }
} }

View File

@ -0,0 +1,27 @@
package cn.bunny;
import cn.bunny.security.custom.CustomPasswordEncoder;
import org.junit.jupiter.api.Test;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.test.context.SpringBootTest;
import org.springframework.security.crypto.password.PasswordEncoder;
@SpringBootTest(classes = CustomPasswordEncoder.class)
class CustomPasswordEncoderTest {
@Autowired
private CustomPasswordEncoder customPasswordEncoder;
@Autowired
private PasswordEncoder passwordEncoder;
@Test
void testCustomPasswordEncoder() {
String encode = customPasswordEncoder.encode("111111");
System.out.println(encode);
}
@Test
void testPasswordEncoder() {
String encode = passwordEncoder.encode("111111");
System.out.println(encode);
}
}