1、pom.xml配置
server:
port: 8888
spring:
datasource:
url: jdbc:mysql://127.0.0.1:3306/users?useSSL=false&serverTimezone=GMT%2B8
username: root
password: sasa
driver-class-name: com.mysql.cj.jdbc.Driver
jpa:
show-sql: true
database: mysql
hibernate:
ddl-auto: update
naming:
implicit-strategy: org.hibernate.boot.model.naming.ImplicitNamingStrategyComponentPathImpl
physical-strategy: org.hibernate.boot.model.naming.PhysicalNamingStrategyStandardImpl
redis:
host: 122.51.85.243
port: 6379
password:
jedis:
pool:
max-total: 200
main:
allow-bean-definition-overriding: true
2、实体类
package com.xkxx.sso.pojo;
import lombok.Data;
import javax.persistence.*;
@Data
@Entity
@Table(name = "user")
public class User {
@Id
@GeneratedValue(strategy = GenerationType.IDENTITY)
@Column(name = "id")
private Integer id;
@Column(name = "userName")
private String userName;
@Column(name = "password")
private String password;
}
3、编写Dao,UserDao.class
public interface UserDao extends JpaRepository<User,Integer> {
public User findByUsernameAndPassword(String username, String password);
}
4、编写serviceImpl,UserServiceImpl.class进行登录的业务逻辑处理
@Service
public class UserServiceImpl{
@Autowired
private UserDao userDao;
@Autowired
private JedisDao jedisDao;
@Value("${REDIS_KEY}") //从配置文件中取值
private String KEY;
private Map<Integer,String> UserLogin = new HashMap<>();
/**
* 登录
* @param request
* @param response
* @param u
* @return
*/
public User userlogin(HttpServletRequest request, HttpServletResponse response, User u){
//查询登录是否成功
User user=userDao.findByUsernameAndPassword(u.getUsername(),u.getPassword());
//判断us是否为空
if(user==null){
return null;
}
//生成token
String token="user_"+ UUID.randomUUID().toString();
//从map中获得redis中的key
String oldToken = UserLogin.get(user.getId());
//判断map中是否存在该id
if(!StringUtils.isEmpty(oldToken)){
//删除redis中老的值
jedisDao.delValue(oldToken);
}
//将新的的key保存到map中
UserLogin.put(user.getId(),token);
//将信息存入redis
jedisDao.setValue(token, JsonUtils.objectToJson(user));
//将token放入cookie中
CookieUtils.setCookie(request,response,KEY,token,5*60,true);
return user;
}
/**
* 判断是否登录
* @param response
* @param request
* @return
*/
public String getUserByToken(HttpServletResponse response, HttpServletRequest request) {
//从cookie中取出用户token
String token=CookieUtils.getCookieValue(request,KEY);
//从redis中取出用户信息
String user= jedisDao.getValue(token);
return user;
}
}
5、编写controller,接收前端请求,返回数据
@RestController
public class LoginController {
@Autowired
private UserServiceImpl userService;
/**
* 登录
* @param response
* @param request
* @param user
* @param model
* @return
*/
@PostMapping("/login")
public ResponseResult Login(HttpServletResponse response , HttpServletRequest request, @RequestBody User user, Model model){
ResponseResult responseResult=new ResponseResult();
try {
User user2 = userService.userlogin(request, response, user);
if (user2!=null){
responseResult.setState(200);
responseResult.setMsg("登录成功!");
return responseResult;
}else{
responseResult.setState(202);
responseResult.setMsg("用户名或密码错误!");
return responseResult;
}
}catch (Exception e) {
responseResult.setState(500);
responseResult.setMsg("发生错误,登录失败!");
return responseResult;
}
}
/**
* 判断是否登录
* @param response
* @param request
* @return
* @throws Exception
*/
@GetMapping("/toLogin")
public ResponseResult getUserInfo(HttpServletResponse response , HttpServletRequest request) throws Exception {
ResponseResult responseResult=new ResponseResult();
try{
String token = userService.getUserByToken(response, request);
if(token!=null){
responseResult.setState(200);
responseResult.setMsg("登录中!");
return responseResult;
}else{
responseResult.setState(202);
responseResult.setMsg("在别处登录!");
return responseResult;
}
}catch (Exception e){
response.setStatus(500);
responseResult.setMsg("发生错误!");
return responseResult;
}
}
}
方法二
1、具体的加密和解密方法
package com.example.demo.util;
import com.google.common.base.Strings;
import sun.misc.BASE64Decoder;
import sun.misc.BASE64Encoder;
import javax.crypto.Cipher;
import javax.crypto.KeyGenerator;
import javax.crypto.spec.SecretKeySpec;
import java.security.SecureRandom;
/**
* Create by zhuenbang on 2018/12/3 11:27
*/
public class AESUtil {
private static final String defaultKey = "7bf72345-6266-4381-a4d3-988754c5f9d1";
/**
* @Description: 加密
* @Param:
* @returns: java.lang.String
* @Author: zhuenbang
* @Date: 2018/12/3 11:33
*/
public static String encryptByDefaultKey(String content) throws Exception {
return encrypt(content, defaultKey);
}
/**
* @Description: 解密
* @Param:
* @returns: java.lang.String
* @Author: zhuenbang
* @Date: 2018/12/3 11:30
*/
public static String decryptByDefaultKey(String encryptStr) throws Exception {
return decrypt(encryptStr, defaultKey);
}
/**
* AES加密为base 64 code
*
* @param content 待加密的内容
* @param encryptKey 加密密钥
* @return 加密后的base 64 code
* @throws Exception
*/
public static String encrypt(String content, String encryptKey) throws Exception {
return base64Encode(aesEncryptToBytes(content, encryptKey));
}
/**
* AES加密
*
* @param content 待加密的内容
* @param encryptKey 加密密钥
* @return 加密后的byte[]
* @throws Exception
*/
private static byte[] aesEncryptToBytes(String content, String encryptKey) throws Exception {
KeyGenerator kgen = KeyGenerator.getInstance("AES");
SecureRandom random;
if (System.getProperty("os.name").toLowerCase().contains("linux")) {
random = SecureRandom.getInstance("SHA1PRNG");
} else {
random = new SecureRandom();
}
random.setSeed(encryptKey.getBytes());
kgen.init(128, random);
Cipher cipher = Cipher.getInstance("AES");
cipher.init(Cipher.ENCRYPT_MODE, new SecretKeySpec(kgen.generateKey().getEncoded(), "AES"));
return cipher.doFinal(content.getBytes("utf-8"));
}
/**
* base 64 加密
*
* @param bytes 待编码的byte[]
* @return 编码后的base 64 code
*/
private static String base64Encode(byte[] bytes) {
return new BASE64Encoder().encode(bytes);
}
/**
* 将base 64 code AES解密
*
* @param encryptStr 待解密的base 64 code
* @param decryptKey 解密密钥
* @return 解密后的string
* @throws Exception
*/
public static String decrypt(String encryptStr, String decryptKey) throws Exception {
return Strings.isNullOrEmpty(encryptStr) ? null : aesDecryptByBytes(base64Decode(encryptStr), decryptKey);
}
/**
* AES解密
*
* @param encryptBytes 待解密的byte[]
* @param decryptKey 解密密钥
* @return 解密后的String
* @throws Exception
*/
private static String aesDecryptByBytes(byte[] encryptBytes, String decryptKey) throws Exception {
KeyGenerator kgen = KeyGenerator.getInstance("AES");
SecureRandom random;
if (System.getProperty("os.name").toLowerCase().contains("linux")) {
random = SecureRandom.getInstance("SHA1PRNG");
} else {
random = new SecureRandom();
}
random.setSeed(decryptKey.getBytes());
kgen.init(128, random);
Cipher cipher = Cipher.getInstance("AES");
cipher.init(Cipher.DECRYPT_MODE, new SecretKeySpec(kgen.generateKey().getEncoded(), "AES"));
byte[] decryptBytes = cipher.doFinal(encryptBytes);
return new String(decryptBytes);
}
/**
* base 64 解密
*
* @param base64Code 待解码的base 64 code
* @return 解码后的byte[]
* @throws Exception
*/
private static byte[] base64Decode(String base64Code) throws Exception {
return Strings.isNullOrEmpty(base64Code) ? null : new BASE64Decoder().decodeBuffer(base64Code);
}
}
4、这里获取的token很关键,每次登录都要生成新的token,token是根据userId和当前时间戳加密的
@Override
public String getToken(String userId) throws Exception {
String token = AESUtil.encryptByDefaultKey(Joiner.on("_").join(userId, System.currentTimeMillis()));
logger.debugv("token= {0}", token);
redisService.set(UserKey.userAccessKey, userId, token);
return token;
}
2、这里获取的token很关键,每次登录都要生成新的token,token是根据userId和当前时间戳加密的
@Override
public String getToken(String userId) throws Exception {
String token = AESUtil.encryptByDefaultKey(Joiner.on("_").join(userId, System.currentTimeMillis()));
logger.debugv("token= {0}", token);
redisService.set(UserKey.userAccessKey, userId, token);
return token;
}
3、写一个解密的方法,解密把用户id拿出来,然后从拦截器里拿出token和当前登录token做对比
@Override
public String checkToken(String token) throws Exception {
String userId = AESUtil.decryptByDefaultKey(token).split("_")[0];
String currentToken = redisService.get(UserKey.userAccessKey, userId, String.class);
logger.debugv("currentToken={0}", currentToken);
if (StringUtils.isEmpty(currentToken)) {
return null;
}
if (!token.equals(currentToken)) {
return null;
}
return userId;
}
4、拦截器里具体处理,这里采用注解拦截,当controller有@Secured拦截器才拦截
@Autowired
AuthTokenService authTokenService;
@Override
public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
if (handler instanceof HandlerMethod) {
HandlerMethod hm = (HandlerMethod) handler;
Secured secured = hm.getMethodAnnotation(Secured.class);
if (secured != null) {
String authToken = request.getHeader(UserConstant.USER_TOKEN);
if (StringUtils.isEmpty(authToken)) {
render(response, CodeMsg.REQUEST_ILLEGAL);
return false;
}
String userId = authTokenService.checkToken(authToken);
if (StringUtils.isEmpty(userId)) {
render(response, CodeMsg.LOGIN_FAILURE);
return false;
}
}
return true;
}
return true;
}
private void render(HttpServletResponse response, CodeMsg cm) throws Exception {
response.setContentType("application/json;charset=UTF-8");
OutputStream out = response.getOutputStream();
String str = JSON.toJSONString(Result.error(cm));
out.write(str.getBytes("UTF-8"));
out.flush();
out.close();
}
5、写一个测试登录接口和一个测试单点登录接口
/**
* @Description: 模拟登录
* @Param:
* @returns: com.example.demo.result.Result
* @Author: zhuenbang
* @Date: 2018/12/3 12:05
*/
@GetMapping("/login")
public Result login() throws Exception {
return authTokenService.login();
}
/**
* @Description: 模拟单点登录 @Secured这个方法拦截器会拦截
* @Param:
* @returns: com.example.demo.result.Result
* @Author: zhuenbang
* @Date: 2018/12/3 12:35
*/
@Secured
@GetMapping("/testSSO")
public Result testSSO() {
return authTokenService.testSSO();
}
具体的实现
@Override
public Result login() throws Exception {
String userId = "123456";
return Result.success(this.getToken(userId));
}
@Override
public Result testSSO() {
return Result.success("登录状态正常");
}
postman 测试
单点登录测试
这个方式实现单点登录的关键就是根据userId的加密和解密的实现。
github地址:https://github.com/zhuenbang/demo.git