【Random】十、SpringBoot整合Spring Security&JWT(一)


前言

  SpringSecurity是一个强大的可高度定制的认证和授权框架,对于Spring应用来说它是一套Web安全标准。SpringSecurity注重于为Java应用提供认证和授权功能,像所有的Spring项目一样,它对自定义需求具有强大的扩展性。
  JWT是JSON WEB TOKEN的缩写,它是基于 RFC 7519 标准定义的一种可以安全传输的的JSON对象,由于使用了数字签名,所以是可信任和安全的。
  JWT token的格式:header.payload.signature

  • header中用于存放签名的生成算法
	{"alg": "HS512"}
  • payload中用于存放用户名、token的生成时间和过期时间
	{"sub":"admin","created":1489079981393,"exp":1489684781}
  • signature为以header和payload生成的签名,一旦header和payload被篡改,验证将失败
	//secret为加密算法的密钥
	String signature = HMACSHA512(base64UrlEncode(header) + "." +base64UrlEncode(payload),secret)

  JWT实现认证和授权的原理

  • 用户调用登录接口,登录成功后获取到JWT的token;
  • 之后用户每次调用接口都在http的header中添加一个叫Authorization的头,值为JWT的token;
  • 后台程序通过对Authorization头中信息的解码及数字签名校验来获取其中的用户信息,从而实现认证和授权。

random项目结构:
在这里插入图片描述

1. 依赖

在security模块下的pom.xml中导入SpringSecurity与JWT的相关依赖(其他的依赖不再标明,可以去文末的链接上查看):

		<!--SpringSecurity依赖配置-->
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-security</artifactId>
        </dependency>
        <!--JWT(Json Web Token)登录支持-->
        <dependency>
            <groupId>io.jsonwebtoken</groupId>
            <artifactId>jjwt</artifactId>
            <version>0.9.0</version>
        </dependency>
2. application.yml配置

在api模块下的application.yml中加入jwt的配置信息以及不需要安全保护的资源路径。(使用的多模块工程,security单拎出来作为了一个公共模块,所以application.yml配置文件是放在了api模块下,如果是单工程请相应修改)

jwt:
  # JWT存储的请求头
  header: Authorization
  # JWT加解密使用的密钥
  secret: Stranger
  # JWT令牌过期时间 此处单位/秒 (60*60*24*1)(1天)
  expiration: 86400
  # JWT令牌前缀
  tokenHead: 'Bearer '

secure:
  ignored:
    # 安全路径白名单
    urls:
      - /swagger-ui.html
      - /swagger-resources/**
      - /swagger/**
      - /webjars/**
      - /**/api-docs
      - /file/**
      - /druid/**
      - /actuator/**
      - /sso/**
      - /**/*.js
      - /**/*.css
      - /**/*.html
      - /*.html

3. 配置文件解析

创建JwtSecurityProperties.class和IgnoreUrlsProperties.class用来加载application.yml中的配置信息

package top.plgxs.common.security.properties;

import lombok.Data;
import org.springframework.boot.context.properties.ConfigurationProperties;
import org.springframework.context.annotation.Configuration;

/**
 * <p>JWT配置信息</p>
 *
 * @author Stranger。
 * @version 1.0
 * @since 2021/3/3 0003 16:03
 */
@Data
@Configuration
@ConfigurationProperties(prefix = "jwt")
public class JwtSecurityProperties {
    /**
     * JWT存储的请求头
     */
    private String header;
    /**
     * JWT加解密使用的密钥
     */
    private String secret;
    /**
     * JWT令牌过期时间 此处单位/毫秒
     */
    private Long expiration;
    /**
     * JWT令牌前缀
     */
    private String tokenHead;

}

package top.plgxs.common.security.properties;

import lombok.Data;
import org.springframework.boot.context.properties.ConfigurationProperties;
import org.springframework.context.annotation.Configuration;

import java.util.ArrayList;
import java.util.List;

/**
 * <p>配置白名单资源路径</p>
 *
 * @author Stranger。
 * @version 1.0
 * @since 2021/3/4 0004 15:59
 */
@Data
@Configuration
@ConfigurationProperties(prefix = "secure.ignored")
public class IgnoreUrlsProperties {
    private List<String> urls = new ArrayList<>();
}

4. JWT token工具类

JwtTokenUtil.class工具类实现创建token与校验token功能

package top.plgxs.common.security.util;

import cn.hutool.core.date.DateUtil;
import cn.hutool.core.util.StrUtil;
import com.sun.org.apache.xml.internal.security.utils.Base64;
import io.jsonwebtoken.Claims;
import io.jsonwebtoken.Jwts;
import io.jsonwebtoken.SignatureAlgorithm;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.InitializingBean;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.stereotype.Component;
import top.plgxs.common.security.properties.JwtSecurityProperties;

import javax.annotation.Resource;
import javax.crypto.SecretKey;
import javax.crypto.spec.SecretKeySpec;
import java.util.Date;
import java.util.HashMap;
import java.util.Map;

/**
 * <p>JWT token工具类</p>
 *
 * @author Stranger。
 * @version 1.0
 * @since 2021/3/4 0004 9:13
 */
@Slf4j
@Component
public class JwtTokenUtil implements InitializingBean {
    @Resource
    private JwtSecurityProperties jwtSecurityProperties;

    private static final String CLAIM_KEY_USERNAME = "sub";
    private static final String CLAIM_KEY_CREATED = "created";
    private SecretKey key;

    @Override
    public void afterPropertiesSet() throws Exception {
        // 解密配置文件中密钥
        byte[] decodeKey = Base64.decode(jwtSecurityProperties.getSecret());
        // AES加密
        SecretKey encodeKey = new SecretKeySpec(decodeKey, 0, decodeKey.length, "AES");
        this.key = encodeKey;
    }

    /**
     * 验证token是否还有效
     *
     * @param token       客户端传入的token
     * @param userDetails 从数据库中查询出来的用户信息
     */
    public boolean validateToken(String token, UserDetails userDetails) {
        String username = getUserNameFromToken(token);
        return username.equals(userDetails.getUsername()) && !isTokenExpired(token);
    }

    /**
     * 根据用户信息生成token
     */
    public String generateToken(UserDetails userDetails) {
        // 创建payload的私有声明(根据特定的业务需要添加,如果要拿这个做验证,一般是需要和jwt的接收方提前沟通好验证方式的)
        Map<String, Object> claims = new HashMap<>();
        claims.put(CLAIM_KEY_USERNAME, userDetails.getUsername());
        claims.put(CLAIM_KEY_CREATED, new Date());
        return generateToken(claims);
    }

    /**
     * 当原来的token没过期时是可以刷新的
     *
     * @param oldToken 带tokenHead的token
     */
    public String refreshHeadToken(String oldToken) {
        if (StrUtil.isEmpty(oldToken)) {
            return null;
        }
        String token = oldToken.substring(jwtSecurityProperties.getTokenHead().length());
        if (StrUtil.isEmpty(token)) {
            return null;
        }
        //token校验不通过
        Claims claims = getClaimsFromToken(token);
        if (claims == null) {
            return null;
        }
        //如果token已经过期,不支持刷新
        if (isTokenExpired(token)) {
            return null;
        }
        //如果token在30分钟之内刚刷新过,返回原token
        if (tokenRefreshJustBefore(token, 30 * 60)) {
            return token;
        } else {
            claims.put(CLAIM_KEY_CREATED, new Date());
            return generateToken(claims);
        }
    }

    /**
     * 从token中获取登录用户名
     */
    public String getUserNameFromToken(String token) {
        String username;
        try {
            Claims claims = getClaimsFromToken(token);
            username = claims.getSubject();
        } catch (Exception e) {
            username = null;
        }
        return username;
    }

    /**
     * 根据有效载荷payload生成JWT的token
     */
    private String generateToken(Map<String, Object> claims) {
        return Jwts.builder()
                // 设置私有声明
                .setClaims(claims)
                // 设置过期时间
                .setExpiration(generateExpirationDate())
                // 设置签名使用的签名算法和签名使用的秘钥
                .signWith(SignatureAlgorithm.HS512, key)
                // 压缩为jwt格式xxxxx.xxxxx.xxxxx,包含头部header/有效载荷payload/签名signature
                .compact();
    }

    /**
     * 从token中解析JWT
     */
    private Claims getClaimsFromToken(String token) {
        Claims claims = null;
        try {
            claims = Jwts.parser()
                    .setSigningKey(key)
                    .parseClaimsJws(token)
                    .getBody();
        } catch (Exception e) {
            log.info("JWT格式验证失败:{}", token);
        }
        return claims;
    }

    /**
     * 生成token的过期时间
     */
    private Date generateExpirationDate() {
        return new Date(System.currentTimeMillis() + jwtSecurityProperties.getExpiration() * 1000);
    }

    /**
     * 判断token是否已经失效
     */
    private boolean isTokenExpired(String token) {
        Date expiredDate = getExpiredDateFromToken(token);
        return expiredDate.before(new Date());
    }

    /**
     * 从token中获取过期时间
     */
    private Date getExpiredDateFromToken(String token) {
        Claims claims = getClaimsFromToken(token);
        return claims.getExpiration();
    }

    /**
     * 判断token在指定时间内是否刚刚刷新过
     *
     * @param token 原token
     * @param time  指定时间(秒)
     */
    private boolean tokenRefreshJustBefore(String token, int time) {
        Claims claims = getClaimsFromToken(token);
        Date created = claims.get(CLAIM_KEY_CREATED, Date.class);
        Date refreshDate = new Date();
        //刷新时间在创建时间的指定时间内
        if (refreshDate.after(created) && refreshDate.before(DateUtil.offsetSecond(created, time))) {
            return true;
        }
        return false;
    }

}

5. Security配置

在配置security之前,需要先创建几个依赖的类,包括无权限访问设置、认证失败处理、登录授权过滤器及装载BCrypt密码编码器。

5.1 无权限访问处理
package top.plgxs.common.security.component;

import cn.hutool.json.JSONUtil;
import org.springframework.security.access.AccessDeniedException;
import org.springframework.security.web.access.AccessDeniedHandler;
import org.springframework.stereotype.Component;
import top.plgxs.common.core.api.ResultInfo;

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

/**
 * <p>自定义返回结果:无权限访问时</p>
 *
 * @author Stranger。
 * @version 1.0
 * @since 2021/3/4 0004 15:24
 */
@Component
public class JwtAccessDeniedHandler implements AccessDeniedHandler {
    @Override
    public void handle(HttpServletRequest httpServletRequest, HttpServletResponse httpServletResponse, AccessDeniedException e) throws IOException, ServletException {
        httpServletResponse.setHeader("Access-Control-Allow-Origin", "*");
        httpServletResponse.setHeader("Cache-Control","no-cache");
        httpServletResponse.setCharacterEncoding("UTF-8");
        httpServletResponse.setContentType("application/json");
        httpServletResponse.getWriter().println(JSONUtil.parse(ResultInfo.forbidden(e.getMessage())));
        httpServletResponse.getWriter().flush();
    }
}

5.2 认证失败处理
package top.plgxs.common.security.component;

import cn.hutool.json.JSONUtil;
import org.springframework.security.core.AuthenticationException;
import org.springframework.security.web.AuthenticationEntryPoint;
import org.springframework.stereotype.Component;
import top.plgxs.common.core.api.ResultInfo;

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

/**
 * <p>自定义返回结果:未登录或登录过期,认证失败时</p>
 *
 * @author Stranger。
 * @version 1.0
 * @since 2021/3/4 0004 15:34
 */
@Component
public class JwtAuthenticationEntryPoint implements AuthenticationEntryPoint {
    @Override
    public void commence(HttpServletRequest httpServletRequest, HttpServletResponse httpServletResponse, AuthenticationException e) throws IOException, ServletException {
        httpServletResponse.setHeader("Access-Control-Allow-Origin", "*");
        httpServletResponse.setHeader("Cache-Control","no-cache");
        httpServletResponse.setCharacterEncoding("UTF-8");
        httpServletResponse.setContentType("application/json");
        httpServletResponse.getWriter().println(JSONUtil.parse(ResultInfo.unauthorized(e.getMessage())));
        httpServletResponse.getWriter().flush();
    }
}

5.3 JWT登录授权过滤器
package top.plgxs.common.security.component;

import lombok.extern.slf4j.Slf4j;
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.web.filter.OncePerRequestFilter;
import top.plgxs.common.security.properties.JwtSecurityProperties;
import top.plgxs.common.security.util.JwtTokenUtil;

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

/**
 * <p>JWT登录授权过滤器</p>
 *
 * @author Stranger。
 * @version 1.0
 * @since 2021/3/4 0004 14:51
 */
@Slf4j
@Component
public class JwtAuthenticationTokenFilter extends OncePerRequestFilter {
    @Resource
    private JwtSecurityProperties jwtSecurityProperties;
    @Resource
    private JwtTokenUtil jwtTokenUtil;
    @Resource
    private UserDetailsService userDetailsService;

    @Override
    protected void doFilterInternal(HttpServletRequest httpServletRequest,
                                    HttpServletResponse httpServletResponse,
                                    FilterChain filterChain) throws ServletException, IOException {
        String token = null;
        String username = null;
        String bearerToken = httpServletRequest.getHeader(this.jwtSecurityProperties.getHeader());
        if (bearerToken != null
                && bearerToken.startsWith(this.jwtSecurityProperties.getTokenHead())) {
            token = bearerToken.substring(this.jwtSecurityProperties.getTokenHead().length());
            username = this.jwtTokenUtil.getUserNameFromToken(token);
        }
        if (username != null && SecurityContextHolder.getContext().getAuthentication() == null) {
            UserDetails userDetails = this.userDetailsService.loadUserByUsername(username);
            if (this.jwtTokenUtil.validateToken(token, userDetails)) {
                UsernamePasswordAuthenticationToken authenticationToken = new UsernamePasswordAuthenticationToken(
                        userDetails, null, userDetails.getAuthorities()
                );
                authenticationToken.setDetails(new WebAuthenticationDetailsSource().buildDetails(httpServletRequest));
                log.info("authenticated user:{}", username);
                SecurityContextHolder.getContext().setAuthentication(authenticationToken);
            }
        }
        filterChain.doFilter(httpServletRequest, httpServletResponse);
    }
}

5.4 装载BCrypt密码编码器
package top.plgxs.common.security.component;

import org.springframework.context.annotation.Configuration;
import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder;
import org.springframework.security.crypto.password.PasswordEncoder;

/**
 * <p>装载BCrypt密码编码器</p>
 *
 * @author Stranger。
 * @version 1.0
 * @since 2021/3/8 0008 16:27
 */
@Configuration
public class UserPasswordEncoder {

    public PasswordEncoder passwordEncoder() {
        return new BCryptPasswordEncoder();
    }
}

5.5 security配置
package top.plgxs.common.security.config;

import org.springframework.http.HttpMethod;
import org.springframework.security.config.annotation.authentication.builders.AuthenticationManagerBuilder;
import org.springframework.security.config.annotation.web.builders.HttpSecurity;
import org.springframework.security.config.annotation.web.configuration.WebSecurityConfigurerAdapter;
import org.springframework.security.config.annotation.web.configurers.ExpressionUrlAuthorizationConfigurer;
import org.springframework.security.config.http.SessionCreationPolicy;
import org.springframework.security.web.authentication.UsernamePasswordAuthenticationFilter;
import top.plgxs.common.security.component.JwtAccessDeniedHandler;
import top.plgxs.common.security.component.JwtAuthenticationEntryPoint;
import top.plgxs.common.security.component.JwtAuthenticationTokenFilter;
import top.plgxs.common.security.component.UserPasswordEncoder;
import top.plgxs.common.security.properties.IgnoreUrlsProperties;

import javax.annotation.Resource;

/**
 * <p>Spring Security配置类</p>
 *
 * @author Stranger。
 * @version 1.0
 * @since 2021/3/4 0004 15:43
 */
public class SecurityConfig extends WebSecurityConfigurerAdapter {
    @Resource
    private JwtAccessDeniedHandler jwtAccessDeniedHandler;
    @Resource
    private JwtAuthenticationEntryPoint jwtAuthenticationEntryPoint;
    @Resource
    private JwtAuthenticationTokenFilter jwtAuthenticationTokenFilter;
    @Resource
    private IgnoreUrlsProperties ignoreUrlsProperties;
    @Resource
    private UserPasswordEncoder userPasswordEncoder;

    @Override
    protected void configure(HttpSecurity httpSecurity) throws Exception {
        ExpressionUrlAuthorizationConfigurer<HttpSecurity>.ExpressionInterceptUrlRegistry registry = httpSecurity
                .authorizeRequests();
        // 无需认证的资源路径允许访问
        for (String url : ignoreUrlsProperties.getUrls()) {
            registry.antMatchers(url).permitAll();
        }
        // 允许跨域请求的OPTIONS请求
        registry.antMatchers(HttpMethod.OPTIONS)
                .permitAll();

        registry.and()
                // 默认其他请求都需要身份认证
                .authorizeRequests()
                .anyRequest()
                .authenticated()
                // 关闭跨站请求防护及不使用session
                .and()
                .csrf().disable()  // 禁用csrf
                .sessionManagement() // 不创建会话
                .sessionCreationPolicy(SessionCreationPolicy.STATELESS)
                // 自定义权限拒绝处理类
                .and()
                .exceptionHandling()
                .accessDeniedHandler(jwtAccessDeniedHandler)
                .authenticationEntryPoint(jwtAuthenticationEntryPoint)
                // 自定义权限拦截器JWT过滤器
                .and()
                .addFilterBefore(jwtAuthenticationTokenFilter, UsernamePasswordAuthenticationFilter.class);

    }

    @Override
    protected void configure(AuthenticationManagerBuilder auth) throws Exception {
        auth.userDetailsService(userDetailsService())
                .passwordEncoder(userPasswordEncoder.passwordEncoder());
    }

}

6.使用

上面security的所有配置都已结束,由于我们是把security单拎出来作为的一个公共模块,那么其他模块该怎么使用呢?
下面以api模块的调用为例:
在这里插入图片描述

第一步,给给需要登录认证的模块添加random-common-security依赖:

		<dependency>
			<groupId>top.plgxs</groupId>
			<artifactId>random-common-security</artifactId>
			<version>0.0.1-SNAPSHOT</version>
		</dependency>

第二步,添加application.yml配置,请移到上面的目录2查看
第三步,添加RandomSecurityConfig配置类,继承自random-common-security中的SecurityConfig配置,并且配置一个UserDetailsService接口的实现类,用于获取登录用户详情:

package top.plgxs.api.config;

import org.springframework.context.annotation.Configuration;
import org.springframework.security.config.annotation.method.configuration.EnableGlobalMethodSecurity;
import org.springframework.security.config.annotation.web.configuration.EnableWebSecurity;
import org.springframework.security.core.userdetails.UserDetailsService;
import top.plgxs.api.service.AdminService;
import top.plgxs.common.security.config.SecurityConfig;

import javax.annotation.Resource;

/**
 * random-common-security模块相关配置
 * @author Stranger。
 * @version 1.0
 * @since 2021/3/4 21:30
 */
@Configuration
@EnableWebSecurity
@EnableGlobalMethodSecurity(prePostEnabled = true)
public class RandomSecurityConfig extends SecurityConfig {
    @Resource
    private AdminService adminService;

    @Override
    public UserDetailsService userDetailsService() {
        // 获取登录用户信息
        return username -> adminService.loadUserByUsername(username);
    }


}

第四步,在service及实现类中添加loadUserByUsername方法

	@Override
    public UserDetails loadUserByUsername(String username) {
        QueryWrapper<SysUser> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("username", username);
        List<SysUser> list = sysUserMapper.selectList(queryWrapper);
        if (list != null && list.size() > 0) {
            SysUser user = list.get(0);
            if (user != null) {
                List<SysMenu> menuList = this.getMenuListByUserId(user.getId());
                return new RandomUserDetail(user, menuList);
            }
        }
        return null;
    }
    
	@Override
    public List<SysMenu> getMenuListByUserId(String userId) {
    	// 根据用户id查询菜单权限信息
        return adminMapper.getMenuListByUserId(userId);
    }

第五步,配置RandomUserDetail类,实现UserDetails:

package top.plgxs.api.bo;

import cn.hutool.core.util.StrUtil;
import org.springframework.security.core.GrantedAuthority;
import org.springframework.security.core.authority.SimpleGrantedAuthority;
import org.springframework.security.core.userdetails.UserDetails;
import top.plgxs.common.core.constants.enums.StatusEnum;
import top.plgxs.mbg.entity.sys.SysMenu;
import top.plgxs.mbg.entity.sys.SysUser;

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

/**
 * SpringSecurity需要的用户详情
 *
 * @author Stranger。
 * @version 1.0
 * @since 2021/3/4 22:43
 */
public class RandomUserDetail implements UserDetails {
    private SysUser sysUser;
    private List<SysMenu> menuList;

    public RandomUserDetail(SysUser user, List<SysMenu> menus) {
        this.sysUser = user;
        this.menuList = menus;
    }

    @Override
    public Collection<? extends GrantedAuthority> getAuthorities() {
        // 返回当前用户的权限
        return menuList.stream()
                .filter(menu -> StrUtil.isNotBlank(menu.getMenuAuth())
                        && StatusEnum.ENABLE.getCode().equals(menu.getStatus()))
                .map(menu -> new SimpleGrantedAuthority(menu.getMenuAuth()))
                .collect(Collectors.toList());
    }

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

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

    /**
     * 帐号是否不过期,false则验证不通过
     */
    @Override
    public boolean isAccountNonExpired() {
        return true;
    }

    /**
     * 帐号是否不锁定,false则验证不通过
     */
    @Override
    public boolean isAccountNonLocked() {
        return true;
    }

    /**
     * 凭证是否不过期,false则验证不通过
     */
    @Override
    public boolean isCredentialsNonExpired() {
        return true;
    }

    /**
     * 该帐号是否启用,false则验证不通过
     */
    @Override
    public boolean isEnabled() {
        return StatusEnum.ENABLE.getCode().equals(sysUser.getStatus());
    }
}

至此,所有配置都已结束,可以开始使用了。下面是个登录注册的示例:

package top.plgxs.api.controller;

import cn.hutool.core.util.StrUtil;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RestController;
import top.plgxs.api.service.AdminService;
import top.plgxs.common.core.api.ResultInfo;
import top.plgxs.common.security.properties.JwtSecurityProperties;
import top.plgxs.mbg.dto.sys.LoginUser;
import top.plgxs.mbg.entity.sys.SysUser;

import javax.annotation.Resource;
import java.util.HashMap;
import java.util.Map;

/**
 * <p>登录</p>
 *
 * @author Stranger。
 * @version 1.0
 * @since 2021/3/8 0008 15:29
 */
@Api(tags = "LoginController", value = "用户登录")
@RestController
public class LoginController {
    @Resource
    private AdminService adminService;
    @Resource
    private JwtSecurityProperties jwtSecurityProperties;

    @ApiOperation(value = "用户登录")
    @PostMapping("/login")
    public ResultInfo<Object> login(LoginUser loginUser) {
        if (loginUser == null || StrUtil.isBlank(loginUser.getUsername())
                || StrUtil.isBlank(loginUser.getPassword())) {
            return ResultInfo.validateFailed();
        }
        String token = adminService.login(loginUser.getUsername(), loginUser.getPassword());
        if (token == null) {
            return ResultInfo.validateFailed("用户名或密码错误");
        }
        Map<String, String> map = new HashMap<>();
        map.put("token", token);
        map.put("tokenHead", jwtSecurityProperties.getTokenHead());
        return ResultInfo.success(map);
    }

    @ApiOperation(value = "用户注册")
    @PostMapping(value = "/register")
    public ResultInfo<SysUser> register(LoginUser loginUser) {
        if (loginUser == null || StrUtil.isBlank(loginUser.getUsername())
                || StrUtil.isBlank(loginUser.getPassword())) {
            return ResultInfo.validateFailed();
        }
        SysUser user = adminService.register(loginUser.getUsername(), loginUser.getPassword());
        if (user == null) {
            return ResultInfo.failed();
        }
        return ResultInfo.success(user);
    }
}

service中的方法

@Override
    public String login(String username, String password) {
        String token = null;
        // 密码需要加密传输,在这里需要进行解密成原始密码
        // 解密步骤省略了
        UserDetails userDetails = loadUserByUsername(username);
        if (!userPasswordEncoder.passwordEncoder().matches(password, userDetails.getPassword()) && userDetails.isEnabled()) {
            UsernamePasswordAuthenticationToken authenticationToken = new UsernamePasswordAuthenticationToken(userDetails,
                    null, userDetails.getAuthorities());
            SecurityContextHolder.getContext().setAuthentication(authenticationToken);
            token = jwtTokenUtil.generateToken(userDetails);
            // 添加登录日志,省略了
        }
        return token;
    }

    @Override
    public SysUser register(String username, String password) {
        // 查询是否有相同的用户名
        QueryWrapper<SysUser> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("username", username);
        List<SysUser> list = sysUserMapper.selectList(queryWrapper);
        if (list != null && list.size() > 0) {
            return null;
        }
        SysUser user = new SysUser();
        user.setUsername(username);
        // 将密码加密
        String encodePassword = userPasswordEncoder.passwordEncoder().encode(password);
        user.setPassword(encodePassword);
        user.setGmtCreate(LocalDateTime.now());
        sysUserMapper.insert(user);
        return user;
    }

项目地址 https://gitee.com/lp1791803611/random

如有问题请评论区留言。

评论 2
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

Stranger。

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值