作者 朱兆平

匿名者路由缓存处理

图片登录验证码
... ... @@ -4,13 +4,18 @@
*/
package com.tianbo.warehouse;
import com.google.code.kaptcha.impl.DefaultKaptcha;
import com.google.code.kaptcha.util.Config;
import org.mybatis.spring.annotation.MapperScan;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.cloud.netflix.eureka.EnableEurekaClient;
import org.springframework.context.annotation.Bean;
import org.springframework.scheduling.annotation.EnableScheduling;
import org.springframework.transaction.annotation.EnableTransactionManagement;
import java.util.Properties;
@SpringBootApplication
@EnableScheduling
@EnableEurekaClient
... ... @@ -22,5 +27,24 @@ public class WarehouseApplication {
SpringApplication.run(WarehouseApplication.class, args);
}
/*声明验证码生成策略属性 Bean*/
@Bean
public DefaultKaptcha captchaProducer(){
DefaultKaptcha captchaProducer =new DefaultKaptcha();
Properties properties =new Properties();
properties.setProperty("kaptcha.border","yes");
properties.setProperty("kaptcha.border.color","105,179,90");
properties.setProperty("kaptcha.textproducer.font.color","red");
properties.setProperty("kaptcha.image.width","125");
properties.setProperty("kaptcha.image.height","60");
properties.setProperty("kaptcha.textproducer.font.size","36");
properties.setProperty("kaptcha.session.key","code");
properties.setProperty("kaptcha.textproducer.char.length","4");
properties.setProperty("kaptcha.textproducer.font.names","宋体,楷体,微软雅黑");
Config config=new Config(properties);
captchaProducer.setConfig(config);
return captchaProducer;
}
}
... ...
package com.tianbo.warehouse.controller;
import com.alibaba.fastjson.JSON;
import com.google.code.kaptcha.impl.DefaultKaptcha;
import com.thoughtworks.xstream.core.util.Base64Encoder;
import com.tianbo.warehouse.controller.response.ResultJson;
import com.tianbo.warehouse.model.ROLE;
import com.tianbo.warehouse.service.RoleService;
import com.tianbo.warehouse.util.RedisUtils;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import javax.imageio.ImageIO;
import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.awt.image.BufferedImage;
import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.UUID;
@Slf4j
@RestController()
@RequestMapping("/anonymous")
public class AnonymousController {
@Autowired
RoleService roleService;
@Autowired
RedisUtils redisUtils;
@Autowired
private DefaultKaptcha captchaProducer;
/**
* 配置匿名者可以访问的路由,并更新到redis,匿名者默认可以访问的role_name =ROLE_anonymous
* 此方法会将所有符合权限组名=ROLE_anonymous的权限更新到redis中,供gateway调用判断权限
* @return
*/
@PostMapping("initAnonymousRoute")
public ResultJson initAnonymousRoute(){
List<ROLE> list = roleService.getROLE_anonymousPermList();
String json = JSON.toJSONString(list);
boolean result= redisUtils.set("ROLE_anonymous_routers", json,0);
return result ? new ResultJson("200","匿名者权限配置成功") :new ResultJson("500","匿名者权限配置失败");
}
/**
* 生成验证码
*/
@RequestMapping(value = "/randCode")
public ResultJson getRandCode(){
// 获取验证码上的文字
String capText = captchaProducer.createText();
// 将文件渲染到图片上
BufferedImage bi = captchaProducer.createImage(capText);
ByteArrayOutputStream outputStream = null;
outputStream = new ByteArrayOutputStream();
Base64Encoder encoder = new Base64Encoder();
Map<String,Object> map = new HashMap<>();
String verifyToken = "";
try {
verifyToken = UUID.randomUUID().toString();
redisUtils.set("verifyToken_" + verifyToken,capText,120);
ImageIO.write(bi, "jpeg", outputStream);
map.put("verifyImg","data:image/jpeg;base64,"+encoder.encode(outputStream.toByteArray()));
} catch (IOException e) {
e.printStackTrace();
return new ResultJson("500","verify get error");
}
return new ResultJson("200","verify get ok",map,verifyToken);
}
}
... ...
package com.tianbo.warehouse.controller;
import com.tianbo.warehouse.controller.response.ResultJson;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
... ... @@ -16,5 +18,4 @@ public class IndexController {
}
}
... ...
... ... @@ -27,15 +27,6 @@ import java.util.Properties;
@RestController
public class MainController {
@Autowired
private DefaultKaptcha captchaProducer;
@Autowired
private UserService userService;
@Autowired
private RedisUtils redisUtils;
@GetMapping("/error")
public String error(){
return "error";
... ... @@ -45,75 +36,4 @@ public class MainController {
public String main(){
return "main";
}
/**
* 生成验证码
*/
@RequestMapping(value = "/randCode")
public void getRandCode(HttpServletRequest request, HttpServletResponse response){
HttpSession session = request.getSession();
response.setDateHeader("Expires", 0);
// Set standard HTTP/1.1 no-cache headers.
response.setHeader("Cache-Control", "no-store, no-cache, must-revalidate");
// Set IE extended HTTP/1.1 no-cache headers (use addHeader).
response.addHeader("Cache-Control", "post-check=0, pre-check=0");
// Set standard HTTP/1.0 no-cache header.
response.setHeader("Pragma", "no-cache");
// 设置返回文件类型
response.setContentType("image/jpeg");
// 获取验证码上的文字
String capText = captchaProducer.createText();
// 将验证码上的文字保存在session中
session.setAttribute(Constants.KAPTCHA_SESSION_KEY, capText);
//缓存存储登录验证码信息
redisUtils.set(session.getId(),capText,60);
String code = (String)session.getAttribute(Constants.KAPTCHA_SESSION_KEY);
log.info("验证码为:"+code);
// 将文件渲染到图片上
BufferedImage bi = captchaProducer.createImage(capText);
ServletOutputStream out = null;
try {
out = response.getOutputStream();
ImageIO.write(bi, "jpeg", out);
out.flush();
} catch (IOException e) {
e.printStackTrace();
}
}
/*声明验证码生成策略属性 Bean*/
@Bean
public DefaultKaptcha captchaProducer(){
DefaultKaptcha captchaProducer =new DefaultKaptcha();
Properties properties =new Properties();
properties.setProperty("kaptcha.border","yes");
properties.setProperty("kaptcha.border.color","105,179,90");
properties.setProperty("kaptcha.textproducer.font.color","red");
properties.setProperty("kaptcha.image.width","125");
properties.setProperty("kaptcha.image.height","60");
properties.setProperty("kaptcha.textproducer.font.size","36");
properties.setProperty("kaptcha.session.key","code");
properties.setProperty("kaptcha.textproducer.char.length","4");
properties.setProperty("kaptcha.textproducer.font.names","宋体,楷体,微软雅黑");
Config config=new Config(properties);
captchaProducer.setConfig(config);
return captchaProducer;
}
}
... ...
... ... @@ -40,4 +40,11 @@ public class ResultJson<T> implements Serializable{
this.msg = msg;
this.data = data;
}
public ResultJson(String code, String msg, T data,String jwtToken) {
this.code = code;
this.msg = msg;
this.data = data;
this.jwtToken = jwtToken;
}
}
... ...
... ... @@ -16,6 +16,7 @@ import org.springframework.security.web.authentication.preauth.PreAuthenticatedC
import org.springframework.security.web.util.matcher.AntPathRequestMatcher;
import org.springframework.stereotype.Component;
import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
... ... @@ -53,21 +54,19 @@ public class MyLoginAuthenticationProcessFilter extends AbstractAuthenticationPr
String loginUserName = request.getParameter("username");
String loginUserPass = request.getParameter("password");
String loginVerify = request.getParameter("verify");
String verifyToken = request.getParameter("verifyToken");
// //验证码判断
// HttpSession session = request.getSession();
// String verify = "";
//// String verify = redisUtils.get(session.getId());
// if (session.getAttribute(Constants.KAPTCHA_SESSION_KEY)!=null){
// verify = session.getAttribute(Constants.KAPTCHA_SESSION_KEY).toString();
// }
//
// if(verify!= null && !verify.equals(loginVerify)){
// throw new BadCredentialsException("验证码错误!");
// }
//验证码判断
String verify = "";
authRequest = new UsernamePasswordAuthenticationToken(loginUserName,loginUserPass, null);
authRequest.setDetails(authenticationDetailsSource.buildDetails(request));
verify = redisUtils.get("verifyToken_" + verifyToken);
if(verify != null && loginVerify != null && verify.equals(loginVerify)){
authRequest = new UsernamePasswordAuthenticationToken(loginUserName,loginUserPass, null);
authRequest.setDetails(authenticationDetailsSource.buildDetails(request));
}else {
throw new BadCredentialsException("验证码错误!");
}
} catch (BadCredentialsException e){
throw new PreAuthenticatedCredentialsNotFoundException(e.getMessage());
}catch (Exception e) {
... ...
package com.tianbo.warehouse.service;
public interface LoginService {
}
... ...
... ... @@ -4,9 +4,13 @@ import com.github.pagehelper.PageInfo;
import com.tianbo.warehouse.model.ROLE;
import com.tianbo.warehouse.model.RolePermission;
import java.util.List;
public interface RoleService {
PageInfo<ROLE> findAll(int pageNum, int pageSize, String roleName, String type);
List<ROLE> getROLE_anonymousPermList();
int insertSelective(ROLE record);
int setRolePermissoin(RolePermission record);
... ...
... ... @@ -46,6 +46,12 @@ public class RoleServiceImp implements RoleService{
return roleMapper.insertSelective(record);
}
@Override
public List<ROLE> getROLE_anonymousPermList() {
List<ROLE> list = roleMapper.findAll("ROLE_anonymous", null);
return list;
}
@Transactional(rollbackFor = Exception.class)
@Override
public int setRolePermissoin(RolePermission record){
... ...