作者 朱兆平

卡口用户登录验证OK

正在显示 20 个修改的文件 包含 732 行增加24 行删除
... ... @@ -10,9 +10,9 @@
<relativePath/> <!-- lookup parent from repository -->
</parent>
<groupId>com.tianbo</groupId>
<artifactId>warehouse</artifactId>
<version>2.2Beta</version>
<name>warehouse</name>
<artifactId>usercenter</artifactId>
<version>2.3Kako</version>
<name>usercenter</name>
<description>usercenter for springcloud</description>
<properties>
... ... @@ -22,6 +22,7 @@
<lombok_sersion>1.18.6</lombok_sersion>
<swagger2_version>2.9.2</swagger2_version>
<shiro.version>1.2.5</shiro.version>
<commons-lang3.version>3.3.2</commons-lang3.version>
</properties>
<dependencies>
... ... @@ -227,6 +228,20 @@
<artifactId>shiro-core</artifactId>
<version>${shiro.version}</version>
</dependency>
<dependency>
<groupId>org.apache.commons</groupId>
<artifactId>commons-lang3</artifactId>
<version>${commons-lang3.version}</version>
</dependency>
<!-- 验证码配置-->
<dependency>
<groupId>com.github.axet</groupId>
<artifactId>kaptcha</artifactId>
<version>0.0.9</version>
</dependency>
</dependencies>
<dependencyManagement>
... ...
package com.tianbo.warehouse.controller;
import com.google.code.kaptcha.Constants;
import com.google.code.kaptcha.impl.DefaultKaptcha;
import com.google.code.kaptcha.util.Config;
import com.tianbo.warehouse.model.USERS;
import com.tianbo.warehouse.service.UserService;
import com.tianbo.warehouse.util.RedisUtils;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Bean;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import javax.imageio.ImageIO;
import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.awt.image.BufferedImage;
import java.io.IOException;
import java.util.List;
import java.util.Properties;
@Slf4j
@RestController
public class MainController {
@Autowired
UserService userService;
private DefaultKaptcha captchaProducer;
@Autowired
private UserService userService;
@Autowired
private RedisUtils redisUtils;
@GetMapping("/error")
public String error(){
... ... @@ -23,4 +45,75 @@ 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;
}
}
... ...
... ... @@ -35,9 +35,9 @@ import java.util.Map;
@RestController
@Slf4j
@RequestMapping("/user")
@RequestMapping("/olduser")
@Api("swaggerDemoController相关的api")
public class UserController {
public class OldUserController {
@Autowired
UserService userService;
... ...
package com.tianbo.warehouse.controller.kako;
import com.alibaba.fastjson.JSON;
import com.github.pagehelper.PageInfo;
import com.google.code.kaptcha.Constants;
import com.google.code.kaptcha.impl.DefaultKaptcha;
import com.google.code.kaptcha.util.Config;
import com.tianbo.warehouse.annotation.LogAnnotation;
import com.tianbo.warehouse.annotation.RequestRequire;
import com.tianbo.warehouse.annotation.UserPasswordMd5;
import com.tianbo.warehouse.annotation.cache.annotation.RedisCacheDelTarget;
import com.tianbo.warehouse.controller.response.ResultJson;
import com.tianbo.warehouse.dao.KakoUserMapper;
import com.tianbo.warehouse.model.KakoUser;
import com.tianbo.warehouse.model.KakoUserRole;
import com.tianbo.warehouse.model.USERS;
import com.tianbo.warehouse.model.UserRole;
import com.tianbo.warehouse.security.CustomUserDetailService;
import com.tianbo.warehouse.service.UserService;
import com.tianbo.warehouse.service.kakoImp.KakoUserService;
import com.tianbo.warehouse.service.validated.InsertUser;
import com.tianbo.warehouse.service.validated.UpdateUser;
import com.tianbo.warehouse.util.RedisUtils;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiImplicitParam;
import io.swagger.annotations.ApiImplicitParams;
import io.swagger.annotations.ApiOperation;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Bean;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.validation.BindingResult;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*;
import javax.annotation.Resource;
import javax.imageio.ImageIO;
import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.awt.image.BufferedImage;
import java.io.IOException;
import java.util.List;
import java.util.Map;
import java.util.Properties;
@RestController
@Slf4j
@RequestMapping("/user")
@Api("swaggerDemoController相关的api")
public class UserController {
@Autowired
private KakoUserService userService;
@Autowired
private CustomUserDetailService userDetailService;
@Autowired
private RedisUtils redisUtils;
@ApiOperation(value = "查询用户列表及信息", notes = "查询用户列表及单个用户信息")
@ApiImplicitParams({@ApiImplicitParam(name = "pageNum", value = "分页-当前页", required = false, dataType = "int",defaultValue = "1"),
@ApiImplicitParam(name = "pageSize", value = "分页-每页显示多少条", required = false, dataType = "int",defaultValue = "5")})
@RequestRequire
@GetMapping("/list")
public ResultJson<PageInfo> list(@RequestParam(value = "pageNum",required = false,defaultValue = "1")
int pageNum,
@RequestParam(value = "pageSize",required = false,defaultValue = "5")
int pageSize,
@RequestParam(value = "userName",required = false) String username,
@RequestParam(value = "realName",required = false) String realname)
{
PageInfo<KakoUser> usersPageInfo = userService.selectAllUser(pageNum,pageSize, username, realname);
return new ResultJson("200","success",usersPageInfo);
}
public String getCurrentUser(){
//通过session获取当前登录的用户信息
UserDetails userDetails =(UserDetails) SecurityContextHolder.getContext().getAuthentication().getPrincipal();
return userDetails.getUsername();
}
@LogAnnotation(moduleName = "用户管理",operate = "用户编辑")
@PutMapping("/edit")
public ResultJson updateUserById(@Validated(UpdateUser.class) @RequestBody KakoUser user){
user.setPassword(null);
int i = userService.updateByPrimaryKeySelective(user);
ResultJson resultJson = new ResultJson();
return i==1 ? new ResultJson("200","success") :new ResultJson("500","update faild");
}
@LogAnnotation(moduleName = "用户管理",operate = "用户密码修改")
@PutMapping("/password")
public ResultJson updateUserPassById(@RequestBody KakoUser user){
int i = userService.updateByPrimaryKeySelective(user);
return i==1 ? new ResultJson("200","success") :new ResultJson("500","update faild");
}
@LogAnnotation(moduleName = "用户管理",operate = "用户添加")
@PostMapping("/add")
public ResultJson addUser(@RequestBody @Validated(InsertUser.class) KakoUser user, HttpServletRequest request, HttpServletResponse response, BindingResult bindingResult){
if (bindingResult.hasErrors()){
String s = bindingResult.toString();
}
int i = userService.insertSelective(user);
ResultJson resultJson = new ResultJson();
return i==1 ? new ResultJson("200","新建账户成功") :new ResultJson("500","insert faild");
}
@LogAnnotation(moduleName = "用户管理",operate = "用户删除")
@DeleteMapping("/del")
public ResultJson delUser(@RequestBody KakoUser user,HttpServletRequest request,HttpServletResponse response){
//String username = getusername();
int i = userService.deleteByPrimaryKey(user);
ResultJson resultJson = new ResultJson();
return i==1 ? new ResultJson("200","删除账户成功") :new ResultJson("500","delete faild");
}
@PutMapping("/roleset")
public ResultJson roleSet(@RequestBody Map<String,Object> map,HttpServletRequest request,HttpServletResponse respons){
String id = map.get("userId").toString();
List<Integer> roles = (List<Integer>) map.get("roleIds");
KakoUserRole userRole = new KakoUserRole();
userRole.setUserId(id);
userRole.setRoleIds(roles);
int i = userService.setUserRole(userRole);
return i==1 ? new ResultJson("200","设置角色成功") :new ResultJson("500","设置角色失败");
}
/**
* 刷新redis权限缓存
*/
@ApiOperation(value = "更新用户权限缓存", notes = "重新生成用户的信息到redis")
@RedisCacheDelTarget(cacheKey = "com.tianbo.warehouse.service.imp.PermissionServiceImp")
@PutMapping("/resetToken")
public ResultJson resetToken(HttpServletRequest request,HttpServletResponse respons) {
/**
* 更新目标用户的权限缓存
*/
String authHeader = request.getHeader("Authorization");
if (authHeader != null && authHeader.startsWith("Bearer ")) {
final String authToken = authHeader.substring("Bearer ".length());
try {
String userJson = redisUtils.get(authToken);
if (userJson != null) {
KakoUser u = JSON.parseObject(userJson, KakoUser.class);
String username = u.getUsername();
// String username = JwtTokenUtil.parseToken(authToken);
if (username != null) {
UserDetails userDetails = userDetailService.loadUserByUsername(username);
if (userDetails != null) {
String json = JSON.toJSONString(userDetails);
redisUtils.set(authToken, json, 3600 * 24 * 7);
return new ResultJson("200", "缓存更新成功");
}
}
}
}catch (Exception e){
log.error(e.toString());
return new ResultJson("500","缓存更新失败");
}
}
return new ResultJson("500","缓存更新失败");
}
}
... ...
... ... @@ -19,5 +19,9 @@ public interface KakoUserMapper {
List<KakoUser> selectByUsername(String userName);
List<KakoUser> selectAllUser(KakoUser record);
int lockUser(KakoUser record);
}
\ No newline at end of file
... ...
package com.tianbo.warehouse.dao;
import com.tianbo.warehouse.model.KakoUserRole;
import com.tianbo.warehouse.model.UserRole;
public interface UserRoleMapper {
... ... @@ -7,10 +8,14 @@ public interface UserRoleMapper {
int deleteByUserId(Integer userId);
int deleteByUserIdKako(String userId);
int insert(UserRole record);
int insertSelective(UserRole record);
int insertSelectiveKako(KakoUserRole record);
UserRole selectByPrimaryKey(Integer id);
int updateByPrimaryKeySelective(UserRole record);
... ...
... ... @@ -2,10 +2,16 @@ package com.tianbo.warehouse.model;
import com.alibaba.fastjson.annotation.JSONField;
import com.alibaba.fastjson.serializer.SerializerFeature;
import com.tianbo.warehouse.service.validated.InsertUser;
import com.tianbo.warehouse.service.validated.UpdateUser;
import com.tianbo.warehouse.validate.CheckUserExist;
import org.hibernate.validator.constraints.Length;
import org.springframework.security.core.GrantedAuthority;
import org.springframework.security.core.authority.SimpleGrantedAuthority;
import org.springframework.security.core.userdetails.UserDetails;
import javax.validation.constraints.NotBlank;
import javax.validation.constraints.NotNull;
import java.util.ArrayList;
import java.util.Collection;
import java.util.Date;
... ... @@ -18,8 +24,13 @@ public class KakoUser implements UserDetails {
private String officeId;
@NotBlank(message="用户名不能为空",groups={InsertUser.class, UpdateUser.class})
@Length(min = 4, max = 11, message = "username 长度必须在 {min} - {max} 之间",groups={InsertUser.class, UpdateUser.class})
private String loginName;
@NotNull(message="密码不能为null",groups=InsertUser.class)
@NotBlank(message="密码不能为空",groups=InsertUser.class)
@Length(min = 6, max = 22, message = "密码 长度必须在 {min} - {max} 之间",groups=InsertUser.class)
private String password;
private String no;
... ...
package com.tianbo.warehouse.model;
import lombok.Data;
import javax.validation.constraints.DecimalMin;
import java.util.List;
@Data
public class KakoUserRole {
@DecimalMin("1")
private Integer id;
private String userId;
@DecimalMin("1")
private Integer roleId;
private List<Integer> roleIds;
public KakoUserRole(){
}
public KakoUserRole(Integer id, String userId, Integer roleId){
this.id = id;
this.roleId=roleId;
this.userId = userId;
}
public KakoUserRole(String userId, Integer roleId){
this.roleId=roleId;
this.userId = userId;
}
}
... ...
... ... @@ -49,6 +49,8 @@ public class MyAccessDecisionManager implements AccessDecisionManager{
if(needRole.trim().equals(ga.getAuthority())) {
return;
}
if("ROLE_ANONYMOUS".equals(ga.getAuthority())) {return;};
}
}
throw new AccessDeniedException("权限不足!");
... ...
... ... @@ -11,6 +11,7 @@ import org.springframework.security.web.util.matcher.AntPathRequestMatcher;
import org.springframework.stereotype.Service;
import org.springframework.util.AntPathMatcher;
import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import java.util.*;
... ... @@ -21,8 +22,9 @@ import java.util.*;
@Service
public class MyInvocationSecurityMetadataSourceService implements FilterInvocationSecurityMetadataSource{
@Autowired
PERMISSIONMapper permissionMapper;
@Resource
private PERMISSIONMapper permissionMapper;
AntPathMatcher pathMatcher = new AntPathMatcher();
private HashMap<String, Collection<ConfigAttribute>> map =null;
... ...
package com.tianbo.warehouse.security.config;
import com.tianbo.warehouse.security.CustomUserDetailService;
import com.tianbo.warehouse.security.filter.JwtAuthenticationTokenFilter;
import com.tianbo.warehouse.security.handel.*;
import com.tianbo.warehouse.security.MyFilterSecurityInterceptor;
import com.tianbo.warehouse.security.handel.kakologin.KakoJwtAuthenticationTokenFilter;
import com.tianbo.warehouse.security.handel.kakologin.MyKakoAuthenticationSuccessHandler;
import com.tianbo.warehouse.security.handel.kakologin.MyLoginAuthenticationProcessFilter;
import org.springframework.beans.factory.annotation.Autowired;
... ... @@ -54,7 +54,7 @@ public class WebSecurityConfig extends WebSecurityConfigurerAdapter {
private MyAuthenticationEntryPoint authenticationEntryPoint;
@Autowired
private JwtAuthenticationTokenFilter jwtAuthenticationTokenFilter;
private KakoJwtAuthenticationTokenFilter jwtAuthenticationTokenFilter;
private final MyLoginAuthenticationProcessFilter adminAuthenticationProcessingFilter;
... ... @@ -92,7 +92,7 @@ public class WebSecurityConfig extends WebSecurityConfigurerAdapter {
//跨域配置
.requestMatchers(CorsUtils::isPreFlightRequest).permitAll()
//管理页面只允许管理员角色访问
.antMatchers("/admin/**","/ROLE/**","/user/**").authenticated()
.antMatchers("/admin/**","/ROLE/**","/user/**","/perm/**","/role/**").authenticated()
//任何请求,登录后可以访问
//其余的不需要验证
.anyRequest().permitAll()
... ...
/**
* Copyright (c) 2005-2012 springside.org.cn
*/
package com.tianbo.warehouse.security.handel.kakologin;
import org.apache.commons.lang3.Validate;
import java.io.IOException;
import java.io.InputStream;
import java.security.GeneralSecurityException;
import java.security.MessageDigest;
import java.security.SecureRandom;
/**
* 支持SHA-1/MD5消息摘要的工具类.
*
* 返回ByteSource,可进一步被编码为Hex, Base64或UrlSafeBase64
*
* @author calvin
*/
public class Digests {
private static final String SHA1 = "SHA-1";
private static final String MD5 = "MD5";
private static SecureRandom random = new SecureRandom();
/**
* 对输入字符串进行md5散列.
*/
public static byte[] md5(byte[] input) {
return digest(input, MD5, null, 1);
}
public static byte[] md5(byte[] input, int iterations) {
return digest(input, MD5, null, iterations);
}
/**
* 对输入字符串进行sha1散列.
*/
public static byte[] sha1(byte[] input) {
return digest(input, SHA1, null, 1);
}
public static byte[] sha1(byte[] input, byte[] salt) {
return digest(input, SHA1, salt, 1);
}
public static byte[] sha1(byte[] input, byte[] salt, int iterations) {
return digest(input, SHA1, salt, iterations);
}
/**
* 对字符串进行散列, 支持md5与sha1算法.
*/
private static byte[] digest(byte[] input, String algorithm, byte[] salt, int iterations) {
try {
MessageDigest digest = MessageDigest.getInstance(algorithm);
if (salt != null) {
digest.update(salt);
}
byte[] result = digest.digest(input);
for (int i = 1; i < iterations; i++) {
digest.reset();
result = digest.digest(result);
}
return result;
} catch (GeneralSecurityException e) {
throw Exceptions.unchecked(e);
}
}
/**
* 生成随机的Byte[]作为salt.
*
* @param numBytes byte数组的大小
*/
public static byte[] generateSalt(int numBytes) {
Validate.isTrue(numBytes > 0, "numBytes argument must be a positive integer (1 or larger)", numBytes);
byte[] bytes = new byte[numBytes];
random.nextBytes(bytes);
return bytes;
}
/**
* 对文件进行md5散列.
*/
public static byte[] md5(InputStream input) throws IOException {
return digest(input, MD5);
}
/**
* 对文件进行sha1散列.
*/
public static byte[] sha1(InputStream input) throws IOException {
return digest(input, SHA1);
}
private static byte[] digest(InputStream input, String algorithm) throws IOException {
try {
MessageDigest messageDigest = MessageDigest.getInstance(algorithm);
int bufferLength = 8 * 1024;
byte[] buffer = new byte[bufferLength];
int read = input.read(buffer, 0, bufferLength);
while (read > -1) {
messageDigest.update(buffer, 0, read);
read = input.read(buffer, 0, bufferLength);
}
return messageDigest.digest();
} catch (GeneralSecurityException e) {
throw Exceptions.unchecked(e);
}
}
}
... ...
... ... @@ -6,8 +6,11 @@ package com.tianbo.warehouse.security.handel.kakologin;
import org.apache.commons.codec.DecoderException;
import org.apache.commons.codec.binary.Base64;
import org.apache.commons.codec.binary.Hex;
import org.apache.commons.lang3.StringEscapeUtils;
import java.io.UnsupportedEncodingException;
import java.net.URLDecoder;
import java.net.URLEncoder;
/**
* 封装各种格式的编码解码工具类.
... ... @@ -95,4 +98,55 @@ public class Encodes {
return new String(chars);
}
/**
* Html 转码.
*/
public static String escapeHtml(String html) {
return StringEscapeUtils.escapeHtml4(html);
}
/**
* Html 解码.
*/
public static String unescapeHtml(String htmlEscaped) {
return StringEscapeUtils.unescapeHtml4(htmlEscaped);
}
/**
* Xml 转码.
*/
public static String escapeXml(String xml) {
return StringEscapeUtils.escapeXml10(xml);
}
/**
* Xml 解码.
*/
public static String unescapeXml(String xmlEscaped) {
return StringEscapeUtils.unescapeXml(xmlEscaped);
}
/**
* URL 编码, Encode默认为UTF-8.
*/
public static String urlEncode(String part) {
try {
return URLEncoder.encode(part, DEFAULT_URL_ENCODING);
} catch (UnsupportedEncodingException e) {
throw Exceptions.unchecked(e);
}
}
/**
* URL 解码, Encode默认为UTF-8.
*/
public static String urlDecode(String part) {
try {
return URLDecoder.decode(part, DEFAULT_URL_ENCODING);
} catch (UnsupportedEncodingException e) {
throw Exceptions.unchecked(e);
}
}
}
... ...
package com.tianbo.warehouse.security.filter;
package com.tianbo.warehouse.security.handel.kakologin;
import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.tianbo.warehouse.model.KakoUser;
import com.tianbo.warehouse.model.USERS;
import com.tianbo.warehouse.security.CustomUserDetailService;
import com.tianbo.warehouse.util.RedisUtils;
... ... @@ -9,7 +9,6 @@ import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.authentication.UsernamePasswordAuthenticationToken;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.security.core.userdetails.User;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.web.authentication.WebAuthenticationDetailsSource;
import org.springframework.stereotype.Component;
... ... @@ -17,8 +16,6 @@ import org.springframework.web.filter.OncePerRequestFilter;
import javax.servlet.FilterChain;
import javax.servlet.ServletException;
import javax.servlet.ServletRequest;
import javax.servlet.ServletResponse;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
... ... @@ -31,13 +28,13 @@ import java.io.IOException;
*/
@Slf4j
@Component
public class JwtAuthenticationTokenFilter extends OncePerRequestFilter{
public class KakoJwtAuthenticationTokenFilter extends OncePerRequestFilter{
@Autowired
RedisUtils redisUtils;
@Autowired
CustomUserDetailService userDetailService;
KakoUserDetailService userDetailService;
@Override
protected void doFilterInternal(
... ... @@ -56,7 +53,7 @@ public class JwtAuthenticationTokenFilter extends OncePerRequestFilter{
String userJson = redisUtils.get(authToken);
try {
if (userJson!=null){
USERS u = JSON.parseObject(userJson,USERS.class);
KakoUser u = JSON.parseObject(userJson,KakoUser.class);
String username = u.getUsername();
//有JWT 没有登录,去JWT的 信息 获取用户信息,赋予登录
if (username != null && SecurityContextHolder.getContext().getAuthentication() == null) {
... ...
... ... @@ -69,6 +69,7 @@ public class MyKakoAuthenticationSuccessHandler extends SavedRequestAwareAuthent
loginedUser.setLoginName(user.getUsername());
loginedUser.setId(user.getId());
loginedUser.setName(user.getName());
loginedUser.setRoles(user.getRoles());
//设置用户的TOKEN的有效时间,时间配置在配置文件中设置
... ...
package com.tianbo.warehouse.security.handel.kakologin;
import com.google.code.kaptcha.Constants;
import com.tianbo.warehouse.security.handel.MyAuthenticationFailHandler;
import com.tianbo.warehouse.util.RedisUtils;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.authentication.AuthenticationServiceException;
import org.springframework.security.authentication.BadCredentialsException;
import org.springframework.security.authentication.UsernamePasswordAuthenticationToken;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.AuthenticationException;
import org.springframework.security.web.authentication.AbstractAuthenticationProcessingFilter;
import org.springframework.security.web.authentication.preauth.PreAuthenticatedCredentialsNotFoundException;
import org.springframework.security.web.util.matcher.AntPathRequestMatcher;
import org.springframework.stereotype.Component;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
/**
* 用户登录自定义校验过滤器
... ... @@ -20,6 +26,10 @@ import javax.servlet.http.HttpServletResponse;
@Slf4j
@Component
public class MyLoginAuthenticationProcessFilter extends AbstractAuthenticationProcessingFilter {
@Autowired
private RedisUtils redisUtils;
/**
* @param authenticationManager: 认证管理器
* @param adminAuthenticationSuccessHandler: 认证成功处理
... ... @@ -42,9 +52,25 @@ public class MyLoginAuthenticationProcessFilter extends AbstractAuthenticationPr
try {
String loginUserName = request.getParameter("username");
String loginUserPass = request.getParameter("password");
String loginVerify = request.getParameter("verify");
// //验证码判断
// 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("验证码错误!");
// }
authRequest = new UsernamePasswordAuthenticationToken(loginUserName,loginUserPass, null);
authRequest.setDetails(authenticationDetailsSource.buildDetails(request));
} catch (Exception e) {
} catch (BadCredentialsException e){
throw new PreAuthenticatedCredentialsNotFoundException(e.getMessage());
}catch (Exception e) {
throw new AuthenticationServiceException(e.getMessage());
}
return this.getAuthenticationManager().authenticate(authRequest);
... ...
package com.tianbo.warehouse.service.kakoImp;
import com.github.pagehelper.PageInfo;
import com.tianbo.warehouse.model.KakoUser;
import com.tianbo.warehouse.model.KakoUserRole;
import com.tianbo.warehouse.model.USERS;
import org.springframework.stereotype.Service;
import java.util.List;
... ... @@ -9,4 +12,14 @@ import java.util.List;
public interface KakoUserService {
KakoUser loadByUsername(String username);
PageInfo<KakoUser> selectAllUser(int pageNum, int pageSize, String username, String realName);
int insertSelective(KakoUser record);
int setUserRole(KakoUserRole userRole);
int updateByPrimaryKeySelective(KakoUser record);
int deleteByPrimaryKey(KakoUser record);
}
... ...
package com.tianbo.warehouse.service.kakoImp;
import com.github.pagehelper.Page;
import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import com.tianbo.warehouse.dao.KakoUserMapper;
import com.tianbo.warehouse.dao.ROLEMapper;
import com.tianbo.warehouse.dao.UserRoleMapper;
import com.tianbo.warehouse.model.*;
import com.tianbo.warehouse.security.handel.kakologin.Digests;
import com.tianbo.warehouse.security.handel.kakologin.Encodes;
import com.tianbo.warehouse.service.PermissionService;
import com.tianbo.warehouse.service.UserService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import javax.annotation.Resource;
import java.util.Date;
import java.util.List;
import java.util.UUID;
@Service
public class KakoUserServiceImpl implements KakoUserService{
public static final String HASH_ALGORITHM = "SHA-1";
public static final int HASH_INTERATIONS = 1024;
public static final int SALT_SIZE = 8;
@Resource
private KakoUserMapper kakoUserMapper;
... ... @@ -24,6 +35,9 @@ public class KakoUserServiceImpl implements KakoUserService{
@Resource
private ROLEMapper roleMapper;
@Resource
private UserRoleMapper userRoleMapper;
@Override
public KakoUser loadByUsername(String username){
List<KakoUser> userList = kakoUserMapper.selectByUsername(username);
... ... @@ -44,4 +58,102 @@ public class KakoUserServiceImpl implements KakoUserService{
return null;
}
@Override
public PageInfo<KakoUser> selectAllUser(int pageNum, int pageSize,String username, String realName){
Page<KakoUser> page = PageHelper.startPage(pageNum,pageSize);
KakoUser users = new KakoUser();
users.setLoginName(username);
users.setName(realName);
List<KakoUser> list = kakoUserMapper.selectAllUser(users);
for (KakoUser user: list) {
// List<PERMISSION> permissionList = permissionMapper.findByUserId(user.getUserId());
// user.setPermissions(permissionList);
List<ROLE> roleList = roleMapper.findRolesByUserIdKako(user.getId());
user.setRoles(roleList);
}
PageInfo<KakoUser> result = new PageInfo<KakoUser>(list);
return result;
}
@Override
public int updateByPrimaryKeySelective(KakoUser record){
int i = 0;
if(record.getPassword()!=null && !record.getPassword().isEmpty()){
String entryPassWord = entryptPassword(record.getPassword());
record.setPassword(entryPassWord);
}
if (record!=null){
i = kakoUserMapper.updateByPrimaryKeySelective(record);
}
return i;
}
@Override
public int deleteByPrimaryKey(KakoUser record) {
return kakoUserMapper.deleteByPrimaryKey(record.getId());
}
@Override
public int insertSelective(KakoUser record) {
if (!userValid(record)){
return 0;
}
if(record.getPassword()!=null && !record.getPassword().isEmpty()){
String entryPassWord = entryptPassword(record.getPassword());
record.setPassword(entryPassWord);
}
record.setCreateDate(new Date());
record.setUpdateDate(new Date());
record.setLoginFlag("1");
record.setId(UUID.randomUUID().toString());
return kakoUserMapper.insertSelective(record);
}
/**
* 生成安全的密码,生成随机的16位salt并经过1024次 sha-1 hash
*/
public static String entryptPassword(String plainPassword) {
String plain = Encodes.unescapeHtml(plainPassword);
byte[] salt = Digests.generateSalt(SALT_SIZE);
byte[] hashPassword = Digests.sha1(plain.getBytes(), salt, HASH_INTERATIONS);
return Encodes.encodeHex(salt)+Encodes.encodeHex(hashPassword);
}
/**
* 检查是否存在用户
*/
public boolean userValid(KakoUser user){
//根据用户名查询出来有数据,则返回失败存在用户
if (loadByUsername(user.getLoginName())!=null){
return false;
}else {
return true;
}
}
@Override
@Transactional(rollbackFor = Exception.class)
public int setUserRole(KakoUserRole userRole) {
try{
String userId = userRole.getUserId();
List<Integer> ids = userRole.getRoleIds();
userRoleMapper.deleteByUserIdKako(userId);
if (null!=ids && !ids.isEmpty()){
for (Integer id:ids) {
KakoUserRole ur = new KakoUserRole(userId,id);
userRoleMapper.insertSelectiveKako(ur);
}
}
/**
* 重写redis用户权限等相关资料
*/
return 1;
}catch (Exception e){
e.printStackTrace();
return 0;
}
}
}
... ...
... ... @@ -35,16 +35,29 @@
from sys_user
where id = #{id,jdbcType=VARCHAR}
</select>
<select id="selectAllUser" resultMap="BaseResultMap" parameterType="com.tianbo.warehouse.model.KakoUser" >
select
<include refid="Base_Column_List" />
from sys_user
WHERE 1=1
<if test=" loginName != null" >
and login_name = #{loginName,jdbcType=VARCHAR}
</if>
<if test="name != null" >
and name = #{name,jdbcType=VARCHAR}
</if>
</select>
<select id="selectByUsername" resultMap="BaseResultMap" parameterType="java.lang.String" >
select
<include refid="Base_Column_List" />
from sys_user
where login_name = #{login_name,jdbcType=VARCHAR}
</select>
<delete id="deleteByPrimaryKey" parameterType="java.lang.String" >
delete from sys_user
<update id="deleteByPrimaryKey" parameterType="java.lang.String" >
update from sys_user
del_flag = '1'
where id = #{id,jdbcType=VARCHAR}
</delete>
</update>
<insert id="insert" parameterType="com.tianbo.warehouse.model.KakoUser" >
insert into sys_user (id, company_id, office_id,
login_name, password, no,
... ...
... ... @@ -23,6 +23,11 @@
delete from user_role
where user_id = #{userId,jdbcType=INTEGER}
</delete>
<delete id="deleteByUserIdKako" parameterType="java.lang.String" >
delete from user_role
where user_id = #{userId,jdbcType=VARCHAR}
</delete>
<insert id="insert" parameterType="com.tianbo.warehouse.model.UserRole" >
insert into user_role (id,user_id, role_id
)
... ... @@ -54,6 +59,32 @@
</if>
</trim>
</insert>
<insert id="insertSelectiveKako" parameterType="com.tianbo.warehouse.model.KakoUserRole" >
insert into user_role
<trim prefix="(" suffix=")" suffixOverrides="," >
<if test="id != null" >
id,
</if>
<if test="userId != null" >
user_id,
</if>
<if test="roleId != null" >
role_id,
</if>
</trim>
<trim prefix="values (" suffix=")" suffixOverrides="," >
<if test="id != null" >
#{id,jdbcType=INTEGER},
</if>
<if test="userId != null" >
#{userId,jdbcType=VARCHAR},
</if>
<if test="roleId != null" >
#{roleId,jdbcType=INTEGER},
</if>
</trim>
</insert>
<update id="updateByPrimaryKeySelective" parameterType="com.tianbo.warehouse.model.UserRole" >
update user_role
<set >
... ...