SpringSecurity前后端分离代码

news2024/11/15 13:41:58

1. 搭建 SpringBoot工程

 1) 新建 boot 项目

 只要一个 web 依赖

 创建好的初始目录,直接将 demos 包删除。

导入依赖

<!-- security  -->
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-security</artifactId>
        </dependency>

        <!-- redis依赖-->
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-data-redis</artifactId>
        </dependency>

        <!-- fastjson依赖-->
        <dependency>
            <groupId>com.alibaba</groupId>
            <artifactId>fastjson</artifactId>
            <version>1.2.83</version>
        </dependency>

        <!-- jwt依赖-->
        <dependency>
            <groupId>io.jsonwebtoken</groupId>
            <artifactId>jjwt</artifactId>
            <version>0.9.0</version>
        </dependency>

        <!-- MybatisPlus -->
        <dependency>
            <groupId>com.baomidou</groupId>
            <artifactId>mybatis-plus-boot-starter</artifactId>
            <version>3.4.3</version>
        </dependency>

        <!-- 数据库  -->
        <dependency>
            <groupId>mysql</groupId>
            <artifactId>mysql-connector-java</artifactId>
        </dependency>

 在application.properties里面写

配置类

server.port=8088
//连接数据库

spring.datasource.url=jdbc:mysql://localhost:3306/库名?useUnicode=true&characterEncoding=utf-8&useSSL=false
spring.datasource.username=数据库的用户名
spring.datasource.password=数据库的密码

//redis
spring.redis.host=服务器的id
spring.redis.port=6379
spring.redis.database=0
spring.redis.password=服务器上的密码
spring.redis.timeout=10s

spring.redis.lettuce.pool.min-idle=0
spring.redis.lettuce.pool.max-idle=8
spring.redis.lettuce.pool.max-active=8
spring.redis.lettuce.pool.max-wait=-1ms
#???
kaptcha.border=no
kaptcha.border.color=105,179,90
kaptcha.image.width=100
kaptcha.image.height=45
kaptcha.session.key=code
kaptcha.textproducer.font.color=blue
kaptcha.textproducer.font.size=35
kaptcha.textproducer.char.length=4
kaptcha.textproducer.font.names=??,??,????

创建表

用户表  角色表 权限表  俩个中间表

用户表

CREATE TABLE `sys_user` (
  `user_id` int(11) NOT NULL AUTO_INCREMENT COMMENT '用户id',
  `user_account` varchar(50) COLLATE utf8mb4_unicode_ci DEFAULT NULL COMMENT '用户名',
  `password` varchar(255) COLLATE utf8mb4_unicode_ci DEFAULT NULL COMMENT '账号密码',
  `user_status` char(1) COLLATE utf8mb4_unicode_ci DEFAULT '0' COMMENT '用户状态(0正常,1停用)',
  `del_flag` char(1) COLLATE utf8mb4_unicode_ci DEFAULT '0' COMMENT '删除字段(0正常,1删除)',
  `user_full_name` varchar(255) COLLATE utf8mb4_unicode_ci DEFAULT NULL COMMENT '用户姓名',
  `user_phone` varchar(255) COLLATE utf8mb4_unicode_ci DEFAULT NULL COMMENT '用户手机号',
  `user_id_card` varchar(255) COLLATE utf8mb4_unicode_ci DEFAULT NULL COMMENT '用户身份证',
  `user_sex` char(10) COLLATE utf8mb4_unicode_ci DEFAULT NULL COMMENT '用户性别',
  `user_email` varchar(50) COLLATE utf8mb4_unicode_ci DEFAULT NULL COMMENT '用户邮箱',
  PRIMARY KEY (`user_id`) USING BTREE
) ENGINE=InnoDB AUTO_INCREMENT=9 DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_unicode_ci ROW_FORMAT=DYNAMIC;

角色表

CREATE TABLE `sys_role` (
  `role_id` int(11) NOT NULL AUTO_INCREMENT COMMENT '角色id',
  `role_name` varchar(255) COLLATE utf8mb4_unicode_ci NOT NULL COMMENT '角色名字',
  `status` char(10) COLLATE utf8mb4_unicode_ci NOT NULL DEFAULT '0' COMMENT '状态(0正常 1停用)',
  `del_status` char(10) COLLATE utf8mb4_unicode_ci NOT NULL DEFAULT '0' COMMENT '删除状态(0正常 1删除)',
  `remark` varchar(10) COLLATE utf8mb4_unicode_ci DEFAULT NULL COMMENT '备注',
  PRIMARY KEY (`role_id`) USING BTREE
) ENGINE=InnoDB AUTO_INCREMENT=3 DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_unicode_ci ROW_FORMAT=DYNAMIC;

权限表

CREATE TABLE `sys_menu` (
  `menu_id` int(11) NOT NULL AUTO_INCREMENT COMMENT '权限id',
  `path` varchar(255) COLLATE utf8mb4_unicode_ci DEFAULT NULL COMMENT '页面路径',
  `explain` varchar(255) COLLATE utf8mb4_unicode_ci DEFAULT NULL COMMENT '路径说明',
  `status` char(1) COLLATE utf8mb4_unicode_ci DEFAULT '0' COMMENT '权限状态(0正常,1停用)',
  `perms` varchar(50) COLLATE utf8mb4_unicode_ci DEFAULT NULL COMMENT '权限',
  PRIMARY KEY (`menu_id`) USING BTREE
) ENGINE=InnoDB AUTO_INCREMENT=5 DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_unicode_ci ROW_FORMAT=DYNAMIC;

解决跨域的

package com.fei.config;

import org.springframework.context.annotation.Configuration;
import org.springframework.web.servlet.config.annotation.CorsRegistry;
import org.springframework.web.servlet.config.annotation.WebMvcConfigurer;

/**
 * 跨域
 */
@Configuration
public class CorsConfig implements WebMvcConfigurer {

    @Override
    public void addCorsMappings(CorsRegistry registry) {
      // 设置允许跨域的路径
        registry.addMapping("/**")
                // 设置允许跨域请求的域名
                .allowedOriginPatterns("*")
                // 是否允许cookie
                .allowCredentials(true)
                // 设置允许的请求方式
                .allowedMethods("GET", "POST", "DELETE", "PUT")
                // 设置允许的header属性
                .allowedHeaders("*")
                // 跨域允许时间
                .maxAge(3600);
    }
}

构建 Redis 交互

package com.fei.config;

import com.alibaba.fastjson.support.spring.FastJsonRedisSerializer;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.data.redis.connection.RedisConnectionFactory;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.data.redis.serializer.StringRedisSerializer;

/**
 * 构建 Redis 交互
 */

@Configuration
public class RedisConfig {

    @Bean
    @SuppressWarnings(value = { "unchecked", "rawtypes" })  // unchecked 用于抑制未经检查的类型转换警告。 rawtypes 警告被抑制
    public RedisTemplate<Object, Object> redisTemplate(RedisConnectionFactory connectionFactory) {
        RedisTemplate<Object, Object> template = new RedisTemplate<>();
        template.setConnectionFactory(connectionFactory);

        FastJsonRedisSerializer serializer = new FastJsonRedisSerializer(Object.class);

        // 使用StringRedisSerializer来序列化和反序列化redis的key值
        template.setKeySerializer(new StringRedisSerializer());
        template.setValueSerializer(serializer);

        // Hash的key也采用StringRedisSerializer的序列化方式
        template.setHashKeySerializer(new StringRedisSerializer());
        template.setHashValueSerializer(serializer);

        template.afterPropertiesSet();
        return template;
    }
}




securityconfig核心内容

package com.fei.config;

import com.fei.filter.JwtAuthenticationTokenFilter;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.security.authentication.AuthenticationManager;
import org.springframework.security.config.annotation.web.builders.HttpSecurity;
import org.springframework.security.config.annotation.web.configuration.WebSecurityConfigurerAdapter;
import org.springframework.security.config.http.SessionCreationPolicy;
import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder;
import org.springframework.security.crypto.password.PasswordEncoder;
import org.springframework.security.web.AuthenticationEntryPoint;
import org.springframework.security.web.access.AccessDeniedHandler;
import org.springframework.security.web.authentication.UsernamePasswordAuthenticationFilter;

@Configuration
public class SecurityConfig extends WebSecurityConfigurerAdapter {
  /**密码加密**/
    @Bean
    public PasswordEncoder passwordEncoder() {
        return new BCryptPasswordEncoder();
    }
    /**认证**/
    @Bean
    @Override
    public AuthenticationManager authenticationManagerBean() throws Exception {
        return super.authenticationManagerBean();
    }
    /**jwt过滤**/
    @Autowired
    private JwtAuthenticationTokenFilter jwtAuthenticationTokenFilter;
/**认证失败**/
    @Autowired
    private AuthenticationEntryPoint authenticationEntryPoint;
/**授权失败**/
    @Autowired
    private AccessDeniedHandler accessDeniedHandler;
/**授权**/
    @Override
    protected void configure(HttpSecurity http) throws Exception {
        http
                .csrf().disable()
                .sessionManagement().sessionCreationPolicy(SessionCreationPolicy.STATELESS)
                .and()
                .authorizeRequests()
                .antMatchers("/user_login/login").permitAll()
                .anyRequest().authenticated()
                .and()
                .addFilterBefore(jwtAuthenticationTokenFilter, UsernamePasswordAuthenticationFilter.class)
                .exceptionHandling()
                .authenticationEntryPoint(authenticationEntryPoint)
                .accessDeniedHandler(accessDeniedHandler);

        http.cors();
    }
}

controller

登陆的接口

package com.fei.controller;

import org.springframework.beans.factory.annotation.Autowired;
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;
import com.fei.service.loginService;
import com.fei.pojo.User;
import com.fei.domain.ResponseResult;

@RestController
@RequestMapping("/user_login")
public class loginController {
    @Autowired
    private loginService loginService;

    /**
     * 登录接口
     * @param user
     * @return
     */

    @PostMapping("/login")
    public ResponseResult login(@RequestBody User user) {
        System.out.println("Login request received: " + user);
        return loginService.login(user);
    }
    /**
     * 退出登录接口
     */
    @RequestMapping("/logout")
    public  ResponseResult logout() {
        return loginService.logout();
    }
}

授权的接口

package com.fei.controller;

import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

@RestController
public class HelloController {
    @RequestMapping("/hello")
    hasRole 方法是用来检查角色的,hasAnyAuthority是检查权限标识符
//    @PreAuthorize("hasAnyAuthority('jx:edit:list')")
    public String hello(){
        return "hello";
    }
}

创建一个包

响应类

package com.fei.domain;

import com.fasterxml.jackson.annotation.JsonInclude;

/**
* 响应类
* @param <T>
*/
// @JsonInclude 控制JSON序列化时哪些属性会被包含在输出的JSON字符串中
// JsonInclude.Include.NON_NULL 的意义是只有当属性的值不为 null 时,该属性才会被包含在生成的JSON对象中。
// 如果你的Java对象有一些字段值为 null,在将这个对象转换为JSON字符串时,这些 null 的字段将不会出现在最终的JSON输出里。
@JsonInclude(JsonInclude.Include.NON_NULL)
public class ResponseResult<T> {
/**
* 状态码
*/
private Integer code;
/**
* 提示信息,如果有错误时,前端可以获取该字段进行提示
*/
private String msg;
/**
* 查询到的结果数据,
*/
private T data;

public ResponseResult(Integer code, String msg) {
this.code = code;
this.msg = msg;
}

public ResponseResult(Integer code, T data) {
this.code = code;
this.data = data;
}

public Integer getCode() {
return code;
}

public void setCode(Integer code) {
this.code = code;
}

public String getMsg() {
return msg;
}

public void setMsg(String msg) {
this.msg = msg;
}

public T getData() {
return data;
}

public void setData(T data) {
this.data = data;
}

public ResponseResult(Integer code, String msg, T data) {
this.code = code;
this.msg = msg;
this.data = data;
}
}
 

在filter包里写jwt

package com.fei.filter;

import com.alibaba.fastjson.JSONObject;
import com.fei.pojo.LoginUser;
import com.fei.utlis.JwtUtil;
import com.fei.utlis.RedisCache;
import io.jsonwebtoken.Claims;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.authentication.UsernamePasswordAuthenticationToken;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.stereotype.Component;
import org.springframework.util.StringUtils;
import org.springframework.web.filter.OncePerRequestFilter;

import javax.servlet.FilterChain;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.util.Objects;

@Component
public class JwtAuthenticationTokenFilter extends OncePerRequestFilter {

    @Autowired
    private RedisCache redisCache;

    @Override
    protected void doFilterInternal(HttpServletRequest request, HttpServletResponse response, FilterChain filterChain) throws ServletException, IOException {
//        获取token
        String token = request.getHeader("token");
//判断topken
        if (!StringUtils.hasText(token)) {
            filterChain.doFilter(request, response);
            return;
        }
//解析token
        String userAccount;
        try {
            Claims claims = JwtUtil.parseJWT(token);
            userAccount = claims.getSubject();
        } catch (Exception e) {
            e.printStackTrace();
            throw new RuntimeException("token非法");
        }
//获取用户信息
        String redisKey = "login:" + userAccount;
        Object cacheObject = redisCache.getCacheObject(redisKey);
        if (cacheObject instanceof JSONObject) {
            LoginUser loginUser = ((JSONObject) cacheObject).toJavaObject(LoginUser.class);
            if (Objects.isNull(loginUser)) {
                throw new RuntimeException("用户未登录");
            }

            UsernamePasswordAuthenticationToken authenticationToken =
                    new UsernamePasswordAuthenticationToken(loginUser, null, loginUser.getAuthorities());
            SecurityContextHolder.getContext().setAuthentication(authenticationToken);
        }

        filterChain.doFilter(request, response);
    }
}

权限异常处理

package com.fei.handler;

import com.alibaba.fastjson.JSON;
import com.fei.domain.ResponseResult;
import com.fei.utlis.WebUtils;
import org.springframework.http.HttpStatus;
import org.springframework.security.access.AccessDeniedException;
import org.springframework.security.web.access.AccessDeniedHandler;
import org.springframework.stereotype.Component;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;

/**
 * 权限异常处理
 */
@Component
public class AccessDeniedHandlerImpl implements AccessDeniedHandler {
    @Override
    public void handle(HttpServletRequest request, HttpServletResponse response,
                       AccessDeniedException accessDeniedException) throws IOException, ServletException {
        ResponseResult result = new ResponseResult(HttpStatus.FORBIDDEN.value(), "没有权限访问哦");
        String jsonString = JSON.toJSONString(result);
        WebUtils.renderString(response, jsonString);
    }
}

认证异常

package com.fei.handler;

import com.alibaba.fastjson.JSON;
import com.fei.domain.ResponseResult;
import com.fei.utlis.WebUtils;
import org.springframework.http.HttpStatus;
import org.springframework.security.core.AuthenticationException;
import org.springframework.security.web.AuthenticationEntryPoint;
import org.springframework.stereotype.Component;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
/**
 * 认证异常
 */
@Component
public class AuthenticationEntryPointImpl implements AuthenticationEntryPoint {
    @Override
    public void commence(HttpServletRequest request, HttpServletResponse response, AuthenticationException authException) throws IOException, ServletException {
        ResponseResult result = new ResponseResult(HttpStatus.UNAUTHORIZED.value(), "认证失败请重新登录");
        String json = JSON.toJSONString(result);
        WebUtils.renderString(response,json);
    }
}

mapper层

package com.fei.mapper;

import org.apache.ibatis.annotations.Mapper;

import java.util.List;

/**
 * 权限
 */
@Mapper
public interface MenuMapper {

    /** 查询用户权限 用户ID 通过角色表查询权限 */
    List<String> selectUserMenu(Integer menuId);

}
package com.fei.mapper;

import com.fei.pojo.User;
import org.apache.ibatis.annotations.Mapper;
import org.apache.ibatis.annotations.Param;

@Mapper
public interface UserMapper {
    User selectUserByUserAccount(@Param("userAccount") String userAccount);
}

pojo层

新建的实体类

package com.fei.pojo;

import com.alibaba.fastjson.annotation.JSONField;
import lombok.Data;
import lombok.NoArgsConstructor;
import org.springframework.security.core.GrantedAuthority;
import org.springframework.security.core.authority.SimpleGrantedAuthority;
import org.springframework.security.core.userdetails.UserDetails;

import java.util.Collection;
import java.util.List;
import java.util.Objects;
import java.util.stream.Collectors;

@Data
@NoArgsConstructor
public class LoginUser implements UserDetails {
    private User user;
    private List<String> permissions;

    public LoginUser(User user, List<String> permissions) {
        this.user = user;
        this.permissions = permissions;
    }

    @JSONField(serialize = false)
    private List<SimpleGrantedAuthority> authorities;

    @Override
    public Collection<? extends GrantedAuthority> getAuthorities() {
        if (authorities != null) {
            return authorities;
        }
        authorities = permissions.stream()
                .map(SimpleGrantedAuthority::new)
                .collect(Collectors.toList());
        return authorities;
    }

    @Override
    public String getPassword() {
        return user.getPassword();
    }

    @Override
    public String getUsername() {
        return user.getUserAccount();
    }

    @Override
    public boolean isAccountNonExpired() {
        return true;
    }

    @Override
    public boolean isAccountNonLocked() {
        return true;
    }

    @Override
    public boolean isCredentialsNonExpired() {
        return true;
    }

    @Override
    public boolean isEnabled() {
        return true;
    }
}

权限表

package com.fei.pojo;

import com.baomidou.mybatisplus.annotation.TableId;
import com.baomidou.mybatisplus.annotation.TableName;
import com.fasterxml.jackson.annotation.JsonInclude;
import lombok.AllArgsConstructor;
import lombok.Builder;
import lombok.Data;
import lombok.NoArgsConstructor;

/**
 * 权限表
 */
@Data
@AllArgsConstructor
@NoArgsConstructor
@Builder
@JsonInclude(JsonInclude.Include.NON_NULL)  // Java 对象序列化为 JSON 字符串时,控制哪些属性应该被包含在生成的 JSON 中。
@TableName(value = "sys_menu")
public class Menu {

    /** 权限ID */
    @TableId
    private Integer menuId;
    /** 页面路径 */
    private Integer path;
    /** 路径说明 */
    private Integer explain;
    /** 权限状态(0正常,1停用) */
    private String status;
    /** 权限标识 */
    private String perms;

}

角色权限中间表

package com.fei.pojo;

import com.baomidou.mybatisplus.annotation.TableName;
import lombok.AllArgsConstructor;
import lombok.Data;
import lombok.NoArgsConstructor;

/**
 * 角色权限中间表
 */
@Data
@AllArgsConstructor
@NoArgsConstructor
@TableName(value = "sys_menu_role")
public class MenuRole {

    /** 权限ID */
    private Integer menuId;
    /** 角色ID */
    private Integer roleId;

}

权限表

package com.fei.pojo;

import com.baomidou.mybatisplus.annotation.TableName;
import lombok.AllArgsConstructor;
import lombok.Builder;
import lombok.Data;
import lombok.NoArgsConstructor;

/**
 * 权限表
 */
@Data
@NoArgsConstructor
@AllArgsConstructor
@Builder
@TableName(value = "sys_role")
public class Role {

    /** 角色id */
    private Integer roleId;
    /** 角色名字 */
    private String roleName;
    /** 删除状态(0正常 1删除) */
    private String delStatus;
    /** 状态(0正常 1停用) */
    private String status;
    /** 备注 */
    private String remark;

}

用户表(User)实体类

package com.fei.pojo;

import com.baomidou.mybatisplus.annotation.IdType;
import com.baomidou.mybatisplus.annotation.TableId;
import com.baomidou.mybatisplus.annotation.TableName;
import lombok.AllArgsConstructor;
import lombok.Builder;
import lombok.Data;
import lombok.NoArgsConstructor;

import java.io.Serializable;

/**
 * 用户表(User)实体类
 */
@Data
@AllArgsConstructor
@NoArgsConstructor
@Builder
@TableName(value = "sys_user")
public class User implements Serializable {

    /** 主键 */
    @TableId(value = "userId", type = IdType.AUTO)
    private Integer userId;
    /** 用户名 */
    private String userAccount;
    /** 密码 */
    private String password;
    /** 账号状态(0正常 1停用) */
    private String userStatus;
    /** 删除字段(0正常,1删除) */
    private String delFlag;
    /** 用户姓名 */
    private String userFullName; // 改名以避免与 UserDetails 的 getUsername 冲突
    /** 用户邮箱 */
    private String userEmail;
    /** 用户手机号 */
    private String userPhone;
    /** 用户身份证号 */
    private String userIdCard;
    /** 用户性别(0男,1女) */
    private String userSex;
}

用户角色中间表

package com.fei.pojo;

import com.baomidou.mybatisplus.annotation.TableName;
import lombok.AllArgsConstructor;
import lombok.Data;
import lombok.NoArgsConstructor;

/**
 * 用户角色中间表
 */
@Data
@AllArgsConstructor
@NoArgsConstructor
@TableName(value = "sys_user_role")
public class UserRole {

    /** 用户ID */
    private Integer userId;
    /** 角色ID */
    private Integer roleId;

}

生成token令牌

package com.fei.pojo;

import io.jsonwebtoken.Claims;
import io.jsonwebtoken.Jwts;
import io.jsonwebtoken.SignatureAlgorithm;
import lombok.Data;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.stereotype.Component;

import java.util.Date;
import java.util.HashMap;
import java.util.Map;

@Data
@Component
public class JwtTokenUtil {
    private String secret="xinzhi";
    private Long expiration=3600000L;
    private String header="JWTHeaderName";


    /**
     * 生成token令牌
     *
     * @param userDetails 用户
     * @return 令token牌
     */
    public String generateToken(UserDetails userDetails) {
        Map<String, Object> claims = new HashMap<>(2);
        //获取用户名
        claims.put("sub", userDetails.getUsername());
        // 创建时间
        claims.put("created", new Date());
        return generateToken(claims);
    }

    /**
     * 从令牌中获取用户名
     *
     * @param token 令牌
     * @return 用户名
     */
    public String getUsernameFromToken(String token) {
        String username;
        try {
            Claims claims = getClaimsFromToken(token);
            username = claims.getSubject();
        } catch (Exception e) {
            username = null;
        }
        return username;
    }

    /**
     * 判断令牌是否过期
     *
     * @param token 令牌
     * @return 是否过期
     */
    public Boolean isTokenExpired(String token) {
        try {
            Claims claims = getClaimsFromToken(token);
            Date expiration = claims.getExpiration();
            return expiration.before(new Date());
        } catch (Exception e) {
            return false;
        }
    }

    /**
     * 刷新令牌
     *
     * @param token 原令牌
     * @return 新令牌
     */
    public String refreshToken(String token) {
        String refreshedToken;
        try {
            Claims claims = getClaimsFromToken(token);
            claims.put("created", new Date());
            refreshedToken = generateToken(claims);
        } catch (Exception e) {
            refreshedToken = null;
        }
        return refreshedToken;
    }

    /**
     * 验证令牌
     *
     * @param token       令牌
     * @param userDetails 用户
     * @return 是否有效
     */
    public Boolean validateToken(String token, UserDetails userDetails) {
        String username = getUsernameFromToken(token);
        return (username.equals(userDetails.getUsername()) && !isTokenExpired(token));
    }


    /**
     * 从claims生成令牌
     *
     * @param claims 数据声明
     * @return 令牌
     */
    private String generateToken(Map<String, Object> claims) {
        Date expirationDate = new Date(System.currentTimeMillis() + expiration);
        return Jwts.builder().setClaims(claims)
                .setExpiration(expirationDate)
                .signWith(SignatureAlgorithm.HS512, secret)
                .compact();
    }

    /**
     * 从令牌中获取数据声明
     *
     * @param token 令牌
     * @return 数据声明
     */
    private Claims getClaimsFromToken(String token) {
        Claims claims;
        try {
            claims = Jwts.parser().setSigningKey(secret).parseClaimsJws(token).getBody();
        } catch (Exception e) {
            claims = null;
        }
        return claims;
    }

}

service层

登录

package com.fei.service.impl;

import com.fei.domain.ResponseResult;
import com.fei.pojo.LoginUser;
import com.fei.pojo.User;
import com.fei.service.loginService;
import com.fei.utlis.JwtUtil;
import com.fei.utlis.RedisCache;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.authentication.AuthenticationManager;
import org.springframework.security.authentication.UsernamePasswordAuthenticationToken;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.stereotype.Service;

import java.util.HashMap;
import java.util.Objects;

@Service
public class  loginServiceImpl implements loginService {

    @Autowired
    private AuthenticationManager authenticationManager;

    @Autowired
    private RedisCache redisCache;

    @Override
    public ResponseResult login(User user) {
        UsernamePasswordAuthenticationToken authenticationToken =
                new UsernamePasswordAuthenticationToken(user.getUserAccount(), user.getPassword());
        Authentication authenticate = authenticationManager.authenticate(authenticationToken);

        if (Objects.isNull(authenticate)) {
            throw new RuntimeException("用户名或密码有误");
        }

        LoginUser loginUser = (LoginUser) authenticate.getPrincipal();
        String users = loginUser.getUser().getUserAccount();

        String jwt = JwtUtil.createJWT(users);
        redisCache.setCacheObject("login:" + users, loginUser);

        HashMap<String, Object> map = new HashMap<>();
        map.put("token", jwt);

        return new ResponseResult(200, "登录成功", map);
    }

    @Override
    public ResponseResult logout() {
        UsernamePasswordAuthenticationToken authentication =
                (UsernamePasswordAuthenticationToken) SecurityContextHolder.getContext().getAuthentication();
        LoginUser loginUser = (LoginUser) authentication.getPrincipal();
        String userAccount = loginUser.getUser().getUserAccount();
        redisCache.deleteObject("login:" + userAccount);
        return new ResponseResult(200, "退出成功");
    }
}

核心代码

package com.fei.service;

import com.fei.mapper.MenuMapper;
import com.fei.mapper.UserMapper;
import com.fei.pojo.LoginUser;
import com.fei.pojo.User;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.core.userdetails.UsernameNotFoundException;
import org.springframework.stereotype.Service;

import java.util.List;
import java.util.Objects;

@Service
public class CustomUserDetailsService implements UserDetailsService {

    @Autowired
    private UserMapper userMapper;
    @Autowired
    private MenuMapper menuMapper;

    @Override
    public UserDetails loadUserByUsername(String username) throws UsernameNotFoundException {
        User user = userMapper.selectUserByUserAccount(username);
        if (Objects.isNull(user)) {
            throw new UsernameNotFoundException("用户不存在");
        }

        List<String> list = menuMapper.selectUserMenu(user.getUserId());
        return new LoginUser(user, list);
    }
}

登陆在servixe的接口

package com.fei.service;

import com.fei.domain.ResponseResult;
import com.fei.pojo.User;

public interface loginService {
    //登录
    ResponseResult login(User user);
//    //注销
    ResponseResult logout();


}

工具类

Redis使用 FastJson 序列化

package com.fei.utlis;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.parser.ParserConfig;
import com.alibaba.fastjson.serializer.SerializerFeature;
import com.fasterxml.jackson.databind.JavaType;
import com.fasterxml.jackson.databind.type.TypeFactory;
import org.springframework.data.redis.serializer.RedisSerializer;
import org.springframework.data.redis.serializer.SerializationException;

import java.nio.charset.Charset;

/**
 * Redis使用 FastJson 序列化
 */
public class FastJsonRedisSerializer<T> implements RedisSerializer<T>
{

    public static final Charset DEFAULT_CHARSET = Charset.forName("UTF-8");

    private Class<T> clazz;

    static
    {
        ParserConfig.getGlobalInstance().setAutoTypeSupport(true);
    }

    public FastJsonRedisSerializer(Class<T> clazz)
    {
        super();
        this.clazz = clazz;
    }

    @Override
    public byte[] serialize(T t) throws SerializationException
    {
        if (t == null)
        {
            return new byte[0];
        }
        return JSON.toJSONString(t, SerializerFeature.WriteClassName).getBytes(DEFAULT_CHARSET);
    }

    @Override
    public T deserialize(byte[] bytes) throws SerializationException
    {
        if (bytes == null || bytes.length <= 0)
        {
            return null;
        }
        String str = new String(bytes, DEFAULT_CHARSET);

        return JSON.parseObject(str, clazz);
    }


    protected JavaType getJavaType(Class<?> clazz)
    {
        return TypeFactory.defaultInstance().constructType(clazz);
    }
}

jwt工具类

package com.fei.utlis;

import io.jsonwebtoken.Claims;
import io.jsonwebtoken.JwtBuilder;
import io.jsonwebtoken.Jwts;
import io.jsonwebtoken.SignatureAlgorithm;

import javax.crypto.SecretKey;
import javax.crypto.spec.SecretKeySpec;
import java.util.Base64;
import java.util.Date;
import java.util.UUID;

/**
 * JWT工具类
 */
public class JwtUtil {

    //有效期为
    public static final Long JWT_TTL = 7 * 12 * 60 * 3600L; // 7天
    //设置秘钥明文
    public static final String JWT_KEY = "jx";

    public static String getUUID(){
        String token = UUID.randomUUID().toString().replaceAll("-", "");
        return token;
    }

    /**
     * 生成jtw
     * @param subject token中要存放的数据(json格式)
     * @return
     */
    public static String createJWT(String subject) {
        JwtBuilder builder = getJwtBuilder(subject, null, getUUID());// 设置过期时间
        return builder.compact();
    }

    /**
     * 生成jtw
     * @param subject token中要存放的数据(json格式)
     * @param ttlMillis token超时时间
     * @return
     */
    public static String createJWT(String subject, Long ttlMillis) {
        JwtBuilder builder = getJwtBuilder(subject, ttlMillis, getUUID());// 设置过期时间
        return builder.compact();
    }

    private static JwtBuilder getJwtBuilder(String subject, Long ttlMillis, String uuid) {
        SignatureAlgorithm signatureAlgorithm = SignatureAlgorithm.HS256;
        SecretKey secretKey = generalKey();
        long nowMillis = System.currentTimeMillis();
        Date now = new Date(nowMillis);
        if(ttlMillis==null){
            ttlMillis=JwtUtil.JWT_TTL;
        }
        long expMillis = nowMillis + ttlMillis;
        Date expDate = new Date(expMillis);
        return Jwts.builder()
                .setId(uuid)              //唯一的ID
                .setSubject(subject)   // 主题  可以是JSON数据
                .setIssuer("javabei")     // 签发者
                .setIssuedAt(now)      // 签发时间
                .signWith(signatureAlgorithm, secretKey) //使用HS256对称加密算法签名, 第二个参数为秘钥
                .setExpiration(expDate);
    }

    /**
     * 创建token
     * @param id
     * @param subject
     * @param ttlMillis
     * @return
     */
    public static String createJWT(String id, String subject, Long ttlMillis) {
        JwtBuilder builder = getJwtBuilder(subject, ttlMillis, id);// 设置过期时间
        return builder.compact();
    }

    public static void main(String[] args) throws Exception {
        String token = "eyJhbGciOiJIUzI1NiJ9.eyJqdGkiOiJjYWM2ZDVhZi1mNjVlLTQ0MDAtYjcxMi0zYWEwOGIyOTIwYjQiLCJzdWIiOiJzZyIsImlzcyI6InNnIiwiaWF0IjoxNjM4MTA2NzEyLCJleHAiOjE2MzgxMTAzMTJ9.JVsSbkP94wuczb4QryQbAke3ysBDIL5ou8fWsbt_ebg";
        Claims claims = parseJWT(token);
        System.out.println(claims);
    }

    /**
     * 生成加密后的秘钥 secretKey
     * @return
     */
    public static SecretKey generalKey() {
        byte[] encodedKey = Base64.getDecoder().decode(JwtUtil.JWT_KEY);
        SecretKey key = new SecretKeySpec(encodedKey, 0, encodedKey.length, "AES");
        return key;
    }

    /**
     * 解析
     *
     * @param jwt
     * @return
     * @throws Exception
     */
    public static Claims parseJWT(String jwt) throws Exception {
        SecretKey secretKey = generalKey();
        return Jwts.parser()
                .setSigningKey(secretKey)
                .parseClaimsJws(jwt)
                .getBody();
    }
}

redis的工具类

package com.fei.utlis;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.BoundSetOperations;
import org.springframework.data.redis.core.HashOperations;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.data.redis.core.ValueOperations;
import org.springframework.stereotype.Component;

import java.util.*;
import java.util.concurrent.TimeUnit;

@SuppressWarnings(value = { "unchecked", "rawtypes" })
@Component
public class RedisCache {
    @Autowired
    public RedisTemplate redisTemplate;

    /**
     * 缓存基本的对象,Integer、String、实体类等
     *
     * @param key 缓存的键值
     * @param value 缓存的值
     */
    public <T> void setCacheObject(final String key, final T value)
    {
        redisTemplate.opsForValue().set(key, value);
    }

    /**
     * 缓存基本的对象,Integer、String、实体类等
     *
     * @param key 缓存的键值
     * @param value 缓存的值
     * @param timeout 时间
     * @param timeUnit 时间颗粒度
     */
    public <T> void setCacheObject(final String key, final T value, final Integer timeout, final TimeUnit timeUnit)
    {
        redisTemplate.opsForValue().set(key, value, timeout, timeUnit);
    }

    /**
     * 设置有效时间
     *
     * @param key Redis键
     * @param timeout 超时时间
     * @return true=设置成功;false=设置失败
     */
    public boolean expire(final String key, final long timeout)
    {
        return expire(key, timeout, TimeUnit.SECONDS);
    }

    /**
     * 设置有效时间
     *
     * @param key Redis键
     * @param timeout 超时时间
     * @param unit 时间单位
     * @return true=设置成功;false=设置失败
     */
    public boolean expire(final String key, final long timeout, final TimeUnit unit)
    {
        return redisTemplate.expire(key, timeout, unit);
    }

    /**
     * 获得缓存的基本对象。
     *
     * @param key 缓存键值
     * @return 缓存键值对应的数据
     */
    public <T> T getCacheObject(final String key)
    {
        ValueOperations<String, T> operation = redisTemplate.opsForValue();
        return operation.get(key);
    }

    /**
     * 删除单个对象
     *
     * @param key
     */
    public boolean deleteObject(final String key)
    {
        return redisTemplate.delete(key);
    }

    /**
     * 删除集合对象
     *
     * @param collection 多个对象
     * @return
     */
    public long deleteObject(final Collection collection)
    {
        return redisTemplate.delete(collection);
    }

    /**
     * 缓存List数据
     *
     * @param key 缓存的键值
     * @param dataList 待缓存的List数据
     * @return 缓存的对象
     */
    public <T> long setCacheList(final String key, final List<T> dataList)
    {
        Long count = redisTemplate.opsForList().rightPushAll(key, dataList);
        return count == null ? 0 : count;
    }

    /**
     * 获得缓存的list对象
     *
     * @param key 缓存的键值
     * @return 缓存键值对应的数据
     */
    public <T> List<T> getCacheList(final String key)
    {
        return redisTemplate.opsForList().range(key, 0, -1);
    }

    /**
     * 缓存Set
     *
     * @param key 缓存键值
     * @param dataSet 缓存的数据
     * @return 缓存数据的对象
     */
    public <T> BoundSetOperations<String, T> setCacheSet(final String key, final Set<T> dataSet)
    {
        BoundSetOperations<String, T> setOperation = redisTemplate.boundSetOps(key);
        Iterator<T> it = dataSet.iterator();
        while (it.hasNext())
        {
            setOperation.add(it.next());
        }
        return setOperation;
    }

    /**
     * 获得缓存的set
     *
     * @param key
     * @return
     */
    public <T> Set<T> getCacheSet(final String key)
    {
        return redisTemplate.opsForSet().members(key);
    }

    /**
     * 缓存Map
     *
     * @param key
     * @param dataMap
     */
    public <T> void setCacheMap(final String key, final Map<String, T> dataMap)
    {
        if (dataMap != null) {
            redisTemplate.opsForHash().putAll(key, dataMap);
        }
    }

    /**
     * 获得缓存的Map
     *
     * @param key
     * @return
     */
    public <T> Map<String, T> getCacheMap(final String key)
    {
        return redisTemplate.opsForHash().entries(key);
    }

    /**
     * 往Hash中存入数据
     *
     * @param key Redis键
     * @param hKey Hash键
     * @param value 值
     */
    public <T> void setCacheMapValue(final String key, final String hKey, final T value)
    {
        redisTemplate.opsForHash().put(key, hKey, value);
    }

    /**
     * 获取Hash中的数据
     *
     * @param key Redis键
     * @param hKey Hash键
     * @return Hash中的对象
     */
    public <T> T getCacheMapValue(final String key, final String hKey)
    {
        HashOperations<String, String, T> opsForHash = redisTemplate.opsForHash();
        return opsForHash.get(key, hKey);
    }

    /**
     * 删除Hash中的数据
     * 
     * @param key
     * @param hkey
     */
    public void delCacheMapValue(final String key, final String hkey)
    {
        HashOperations hashOperations = redisTemplate.opsForHash();
        hashOperations.delete(key, hkey);
    }

    /**
     * 获取多个Hash中的数据
     *
     * @param key Redis键
     * @param hKeys Hash键集合
     * @return Hash对象集合
     */
    public <T> List<T> getMultiCacheMapValue(final String key, final Collection<Object> hKeys)
    {
        return redisTemplate.opsForHash().multiGet(key, hKeys);
    }

    /**
     * 获得缓存的基本对象列表
     *
     * @param pattern 字符串前缀
     * @return 对象列表
     */
    public Collection<String> keys(final String pattern)
    {
        return redisTemplate.keys(pattern);
    }
}

webutils的工具类

package com.fei.utlis;

import javax.servlet.http.HttpServletResponse;
import java.io.IOException;

public class WebUtils
{
    /**
     * 将字符串渲染到客户端
     * @param response 渲染对象
     * @param string 待渲染的字符串
     * @return null
     */
    public static String renderString(HttpServletResponse response, String string) {
        try
        {
            response.setStatus(200);
            response.setContentType("application/json");
            response.setCharacterEncoding("utf-8");
            response.getWriter().print(string);
        }
        catch (IOException e)
        {
            e.printStackTrace();
        }
        return null;
    }
}

mapper

权限的sql语句

<?xml version="1.0" encoding="UTF-8" ?>
<!DOCTYPE mapper
        PUBLIC "-//mybatis.org//DTD Mapper 3.0//EN"
        "http://mybatis.org/dtd/mybatis-3-mapper.dtd">
<mapper namespace="com.fei.mapper.MenuMapper">

    <!--  查询用户权限 用户ID 通过角色表查询权限-->
    <select id="selectUserMenu" resultType="java.lang.String">
        select DISTINCT m.perms
        from sys_user_role ur
                 LEFT JOIN sys_role r on ur.role_id = r.role_id
                 LEFT JOIN sys_menu_role mr on r.role_id = mr.role_id
                 LEFT JOIN sys_menu m on mr.menu_id = m.menu_id
        where user_id = #{userId} and r.`status` = '0' and m.`status` = '0';
    </select>
</mapper>

登录退出的sql语句

<?xml version="1.0" encoding="UTF-8" ?>
<!DOCTYPE mapper
        PUBLIC "-//mybatis.org//DTD Mapper 3.0//EN"
        "http://mybatis.org/dtd/mybatis-3-mapper.dtd">
<mapper namespace="com.fei.mapper.UserMapper">
    <sql id="user">
        user_id, user_account, password, user_status, del_flag, user_full_name, user_phone, user_id_card, user_sex, user_email
    </sql>
    <select id="selectUserByUserAccount" resultType="com.fei.pojo.User">
        select <include refid="user"/> from sys_user where user_account = #{userAccount}
    </select>
</mapper>

本文来自互联网用户投稿,该文观点仅代表作者本人,不代表本站立场。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如若转载,请注明出处:http://www.coloradmin.cn/o/2073788.html

如若内容造成侵权/违法违规/事实不符,请联系多彩编程网进行投诉反馈,一经查实,立即删除!

相关文章

redis | 认识非关系数据库Redis的字符串数据类型及过期时间expire的作用

Redis 非关 kv型 数据类型字符串数值操作 应用场景 ⭐字符串命令练习⭐⭐过期时间设定 expire ⭐⭐⭐检查过期时间 ttl key删除过期key机制惰性删除定期删除 数据类型 数据类型丰富&#xff0c;字符串strings,散列hashes,列表lists&#xff0c;集合sets,有序集合sorted sets等等…

MySQL Order By 工作原理探究以及索引优化手段

背景 这篇文章出发的契机&#xff0c;主要是看到京东定时任务优化里面有使用到「游标」这种策略去完成查询优化 https://mp.weixin.qq.com/s/aYJV3Z-1MZ_a6tUjoHa_9g 刚好之前自己在开发业务的时候&#xff0c;也碰到类似的场景&#xff0c;需要在每个季度末将被申诉的卡片更…

流媒体协议之RTMP

一、RTMP 协议概述 今天我们要一起了解的这个协议叫 RTMP 协议&#xff0c;它并不复杂&#xff0c;对于拉流相关的协议&#xff0c;我们可以先思考一下拉流一般要交互什么&#xff0c;我理解有以下几项&#xff0c; 连接信息&#xff1a;包括服务器的地址、端口号等&#xff…

每日Attention学习16——Multi-layer Multi-scale Dilated Convolution

模块出处 [CBM 22] [link] [code] Do You Need Sharpened Details? Asking MMDC-Net: Multi-layer Multi-scale Dilated Convolution Network For Retinal Vessel Segmentation 模块名称 Multi-layer Multi-scale Dilated Convolution (MMDC) 模块作用 多尺度特征提取与融合…

一家物流装备企业终止,业绩下滑严重,恐不符合创业板新上市标准

鸿安机械终止的原因如下&#xff1a;首先&#xff0c;报告期内鸿安机械的营业收入和净利润出现下滑趋势&#xff0c;公司最近一年净利润恐不达标&#xff0c;或许不能满足创业板更新的第一套上市标准&#xff1b;其次&#xff0c;鸿安机械经营业绩对比同行业可比公司&#xff0…

笔记整理—uboot启动过程(5)BL2板级初始化

上一章说到了uboot在BL2阶段大概都要干什么&#xff0c;也说到了为了实现这些要先进行内存排布&#xff0c;实现了这些后便可实现BL2部分的板级初始化。首先先来看一下init_fnc_ptr函数指针。 for(init_fnc_ptrinit_sequence;*init_fnc_ptr;init_fnc_ptr){if((*init_fnc_ptr)(…

一文带你了解html标签

一、文档结构标签 <html>&#xff1a;网页的根标签 &#xff0c;嵌套包含所有标签。 <head>&#xff1a;头标签&#xff0c;包含文档的元数据用于编写网页的修饰内容&#xff0c;附加信息。 <body>&#xff1a;身体标签&#xff0c;用于编写展示内容&…

精益工程师资格证书:2024年CLMP报名指南

随着全球对精益管理的需求日益增长&#xff0c;精益管理专业人士资格认证&#xff08;CLMP&#xff09;正成为越来越多精益工程师和精益管理人员提升职业竞争力的首选。作为一种注重管理而非生产的认证&#xff0c;CLMP不仅适用于制造业的专业人士&#xff0c;也吸引了各行业的…

Qt之窗口

目录 Qt窗口简介: 菜单栏 ⼯具栏 状态栏 浮动窗⼝ 对话框 Qt内置对话框 1.消息对话框QMessageBox 2.颜⾊对话框QColorDialog 3.⽂件对话框QFileDialog 4.字体对话框QFontDialog 5.输⼊对话框QInputDialog 总结 接下来的日子会顺顺利利&#xff0c;万事胜…

Android Studio:模拟器页面闪烁,手机模拟器输入画面闪烁 android studio闪屏

主要解决&#xff0c;android studio 启动app测试&#xff0c;输入数据时&#xff0c;手机画面就会闪烁&#xff0c;闪屏 1. 如图所示&#xff0c;依照顺序找到Edit &#xff0c;并点击Edit 2. 找到Graphics 选择为SoftWare &#xff0c;并保存修改即可 3. 如果此处不能选择S…

奇安信渗透测试岗位三面经验分享

吉祥知识星球http://mp.weixin.qq.com/s?__bizMzkwNjY1Mzc0Nw&mid2247485367&idx1&sn837891059c360ad60db7e9ac980a3321&chksmc0e47eebf793f7fdb8fcd7eed8ce29160cf79ba303b59858ba3a6660c6dac536774afb2a6330#rd 《网安面试指南》http://mp.weixin.qq.com/s?…

算法的学习笔记—二叉搜索树与双向链表(牛客JZ36)

&#x1f600;前言 在数据结构的学习过程中&#xff0c;二叉搜索树&#xff08;Binary Search Tree, BST&#xff09;是一个常见的主题。它不仅具有排序的特性&#xff0c;还为各类算法的实现提供了基础。然而&#xff0c;在某些特定的应用场景中&#xff0c;我们可能需要将二叉…

Web安全:SQL注入实战测试.(扫描 + 测试)

Web安全&#xff1a;SQL注入实战测试. SQL注入就是 有些恶意用户在提交查询请求的过程中 将SQL语句插入到请求内容中&#xff0c;同时程序的本身对用户输入的内容过于相信&#xff0c;没有对用户插入的SQL语句进行任何的过滤&#xff0c;从而直接被SQL语句直接被服务端执行&am…

Docker绑定挂载使用手册

目录 目标 官方文档 绑定挂挂载&#xff08;Bind mounts&#xff09; 简介 基本创建方法 控制读写权限&#xff08;默认有读写权限&#xff09; 为什么绑定挂载不适合做数据库持久化 为什么绑定挂载更适合做热部署 临时挂载&#xff08;tmpfs mounts&#xff09; 简介…

CSS中的元素布局与定位详细说明

1、前言 在CSS开发中&#xff0c;很重要的一个工作就是根据UI设计稿&#xff0c;进行元素的布局与定位&#xff0c;使得元素&#xff08;比如某一段文本、按钮、图片等&#xff09;显示在页面正确的位置。本文就元素的布局与定位方面&#xff0c;做一些讲解和说明。 2、元素的…

PHP易支付系统,支付系统源码下载,已测试,带多个支付接口

易支付系统源码&#xff0c;已测试&#xff0c;功能齐全&#xff0c;带有多支付接口&#xff0c;站内有对应的视频教程&#xff0c;详细教程 搭建出来的网站前端和后台还是比较美观的 PHP全开源易支付系统源码&#xff0c;一键安装版 搭建环境&#xff1a;PHP 5.4 以上 推荐7…

数学基础(九)

一、相关分析 相关分析&#xff1a; 衡量事物之间或称变量之间线性相关的强弱&#xff0c;并适当的统计指标表示出来的过程 相关系数&#xff1a; 连续变量的相关分析&#xff1a; 连续变量即数据变量&#xff0c;它的取值之间可以比较大小&#xff0c;可以用加减法计算出差…

Google Colab快速使用

Google Colab快速使用 1. 引言2. Jupyter笔记本的创建3. 上传代码和数据集4. Colab常规指令 1. 引言 Google Colab是谷歌提供的免费Jupyter&#xff0c;很类似于Linux系统这些在终端界面操纵的感觉&#xff0c;不需要深度学习环境配置就可以使用&#xff0c;完全基于云端运行。…

【celery-2】python-Django发送邮件-短信-钉钉通知

一 Python发送邮件 1.1 使用SMTP模块发送邮件 import smtplib from email.mime.text import MIMEText from email.header import Headermsg_from xxxqq.com # 发送方邮箱 passwd xxx # 填入发送方邮箱的授权码(填入自己的授权码&#xff0c;相当于邮箱密码) msg_to [xxx…

两种方式实现图片标记

效果图 第一种&#xff1a;通过动态添加dom元素实现标记 代码如下 // index.tsx import React from "react"; import "./index.less";export default function index() {const parentRef React.useRef<any>(null);const ulRef React.useRef<a…