16.登录接口认证测试

1.Swagger添加token认证参数

修改swagger配置类

package com.lvxk.demo.admin.config;

import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import springfox.documentation.builders.ApiInfoBuilder;
import springfox.documentation.builders.ParameterBuilder;
import springfox.documentation.builders.PathSelectors;
import springfox.documentation.builders.RequestHandlerSelectors;
import springfox.documentation.schema.ModelRef;
import springfox.documentation.service.ApiInfo;
import springfox.documentation.service.Contact;
import springfox.documentation.service.Parameter;
import springfox.documentation.spi.DocumentationType;
import springfox.documentation.spring.web.plugins.Docket;
import springfox.documentation.swagger2.annotations.EnableSwagger2;

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

/**
 * SwaggerConfig
 * Description: 
* date: 2020/5/5 8:02
* * @author lvxk
* @since JDK 1.8 */ @Configuration @EnableSwagger2 public class SwaggerConfig { @Bean public Docket createRestApi() { // 添加请求参数,我们这里把token作为请求头部参数传入后端 ParameterBuilder parameterBuilder = new ParameterBuilder(); List parameters = new ArrayList(); parameterBuilder.name("token").description("令牌") .modelRef(new ModelRef("string")).parameterType("header").required(false).build(); parameters.add(parameterBuilder.build()); return new Docket(DocumentationType.SWAGGER_2) .apiInfo(apiInfo()) .select() .apis(RequestHandlerSelectors.basePackage("com.lvxk.demo.admin.controller")) .paths(PathSelectors.any()) .build().globalOperationParameters(parameters); } private ApiInfo apiInfo() { return new ApiInfoBuilder() .title("小凯 - demo测试接口") .description("小凯 - demo测试接口") .termsOfServiceUrl("http://localhost:8081/swagger-ui.html") .contact(new Contact("xiaokai.lv", "http://localhost:8071/swagger-ui.html", "[email protected]")) .version("1.0") .build(); } }

2.这时候在不登陆的情况下是无法访问接口的

image.png

3.编写登录接口 生成token

package com.lvxk.demo.admin.controller;

import com.demo.core.http.HttpResult;
import com.google.code.kaptcha.Constants;
import com.google.code.kaptcha.Producer;
import com.lvxk.demo.admin.model.SysUser;
import com.lvxk.demo.admin.security.JwtAuthenticatioToken;
import com.lvxk.demo.admin.service.SysUserService;
import com.lvxk.demo.admin.util.SecurityUtils;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import org.apache.tomcat.util.http.fileupload.IOUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.authentication.AuthenticationManager;
import org.springframework.web.bind.annotation.*;

import javax.imageio.ImageIO;
import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.awt.image.BufferedImage;
import java.io.IOException;

/**
 * SysLoginController 获取验证码
 * Description: 
* date: 2020/5/5 15:19
* * @author lvxk
* @since JDK 1.8 */ @RestController @RequestMapping("login") @Api(tags = "登录相关") public class SysLoginController { @Autowired private Producer producer; @Autowired private SysUserService sysUserService; @Autowired private AuthenticationManager authenticationManager; @GetMapping("kaptcha") @ApiOperation(value = "获取验证码(5位)") public void captha(HttpServletResponse response, HttpServletRequest request) throws IOException { response.setHeader("Cache-Control","no-store,no-cache"); response.setContentType("image/jpeg"); //生成文字验证码 String text = producer.createText(); //生成图片验证码 BufferedImage image = producer.createImage(text); //保存验证码到session中 request.getSession().setAttribute(Constants.KAPTCHA_SESSION_KEY,text); ServletOutputStream out = response.getOutputStream(); ImageIO.write(image,"jpg",out); IOUtils.closeQuietly(out); } /** * 登录接口 */ @PostMapping(value = "/login") public HttpResult login(@RequestBody LoginBean loginBean, HttpServletRequest request) throws IOException { String username = loginBean.getAccount(); String password = loginBean.getPassword(); String captcha = loginBean.getCaptcha(); // 从session中获取之前保存的验证码跟前台传来的验证码进行匹配 Object kaptcha = request.getSession().getAttribute(Constants.KAPTCHA_SESSION_KEY); if(kaptcha == null){ return HttpResult.error("验证码已失效"); } if(!captcha.equals(kaptcha)){ return HttpResult.error("验证码不正确"); } // 用户信息 SysUser user = sysUserService.findByName(username); // 账号不存在、密码错误 if (user == null) { return HttpResult.error("账号不存在"); } if (!PasswordUtils.matches(user.getSalt(), password, user.getPassword())) { return HttpResult.error("密码不正确"); } // 账号锁定 if (user.getStatus() == 0) { return HttpResult.error("账号已被锁定,请联系管理员"); } // 系统登录认证 JwtAuthenticatioToken token = SecurityUtils.login(request, username, password, authenticationManager); return HttpResult.ok(token); } }

4.LoginBean

package com.lvxk.demo.admin.vo;

import lombok.Data;

/**
 * 登录接口封装对象
 * Description: 
* date: 2020/5/5 16:42
* * @author lvxk
* @since JDK 1.8 */ @Data public class LoginBean { private String account; private String password; private String captcha; }

5.PasswordUtils

package com.lvxk.demo.admin.util;
import java.util.UUID;
/**
 * 密码工具类
 * Description: 
* date: 2020/5/5 16:44
* * @author lvxk
* @since JDK 1.8 */ public class PasswordUtils { /** * 匹配密码 * @param salt 盐 * @param rawPass 明文 * @param encPass 密文 * @return */ public static boolean matches(String salt, String rawPass, String encPass) { return new PasswordEncoder(salt).matches(encPass, rawPass); } /** * 明文密码加密 * @param rawPass 明文 * @param salt * @return */ public static String encode(String rawPass, String salt) { return new PasswordEncoder(salt).encode(rawPass); } /** * 获取加密盐 * @return */ public static String getSalt() { return UUID.randomUUID().toString().replaceAll("-", "").substring(0, 20); } }

经过测试登录成功后用token即可正常访问接口

你可能感兴趣的:(16.登录接口认证测试)