1.Swagger添加token認(rèn)證參數(shù)
修改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: <br/>
* date: 2020/5/5 8:02<br/>
*
* @author lvxk<br />
* @since JDK 1.8
*/
@Configuration
@EnableSwagger2
public class SwaggerConfig {
@Bean
public Docket createRestApi() {
// 添加請(qǐng)求參數(shù),我們這里把token作為請(qǐng)求頭部參數(shù)傳入后端
ParameterBuilder parameterBuilder = new ParameterBuilder();
List<Parameter> parameters = new ArrayList<Parameter>();
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測(cè)試接口")
.description("小凱 - demo測(cè)試接口")
.termsOfServiceUrl("http://localhost:8081/swagger-ui.html")
.contact(new Contact("xiaokai.lv", "http://localhost:8071/swagger-ui.html", "lvxiaokai@aliyun.com"))
.version("1.0")
.build();
}
}
2.這時(shí)候在不登陸的情況下是無(wú)法訪問(wèn)接口的
3.編寫(xiě)登錄接口 生成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 獲取驗(yàn)證碼
* Description: <br/>
* date: 2020/5/5 15:19<br/>
*
* @author lvxk<br />
* @since JDK 1.8
*/
@RestController
@RequestMapping("login")
@Api(tags = "登錄相關(guān)")
public class SysLoginController {
@Autowired
private Producer producer;
@Autowired
private SysUserService sysUserService;
@Autowired
private AuthenticationManager authenticationManager;
@GetMapping("kaptcha")
@ApiOperation(value = "獲取驗(yàn)證碼(5位)")
public void captha(HttpServletResponse response, HttpServletRequest request) throws IOException {
response.setHeader("Cache-Control","no-store,no-cache");
response.setContentType("image/jpeg");
//生成文字驗(yàn)證碼
String text = producer.createText();
//生成圖片驗(yàn)證碼
BufferedImage image = producer.createImage(text);
//保存驗(yàn)證碼到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中獲取之前保存的驗(yàn)證碼跟前臺(tái)傳來(lái)的驗(yàn)證碼進(jìn)行匹配
Object kaptcha = request.getSession().getAttribute(Constants.KAPTCHA_SESSION_KEY);
if(kaptcha == null){
return HttpResult.error("驗(yàn)證碼已失效");
}
if(!captcha.equals(kaptcha)){
return HttpResult.error("驗(yàn)證碼不正確");
}
// 用戶信息
SysUser user = sysUserService.findByName(username);
// 賬號(hào)不存在、密碼錯(cuò)誤
if (user == null) {
return HttpResult.error("賬號(hào)不存在");
}
if (!PasswordUtils.matches(user.getSalt(), password, user.getPassword())) {
return HttpResult.error("密碼不正確");
}
// 賬號(hào)鎖定
if (user.getStatus() == 0) {
return HttpResult.error("賬號(hào)已被鎖定,請(qǐng)聯(lián)系管理員");
}
// 系統(tǒng)登錄認(rèn)證
JwtAuthenticatioToken token = SecurityUtils.login(request, username, password, authenticationManager);
return HttpResult.ok(token);
}
}
4.LoginBean
package com.lvxk.demo.admin.vo;
import lombok.Data;
/**
* 登錄接口封裝對(duì)象
* Description: <br/>
* date: 2020/5/5 16:42<br/>
*
* @author lvxk<br />
* @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: <br/>
* date: 2020/5/5 16:44<br/>
*
* @author lvxk<br />
* @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);
}
}
經(jīng)過(guò)測(cè)試登錄成功后用token即可正常訪問(wèn)接口