SpringBoot实现免登录
最近公司有个需求,⽤户在以前的项⽬⾥登录了之后,跳转到新项⽬可以不⽤登录
为了实现这个需求,在旧项⽬跳转到新项⽬的时候需要把token带过来,新项⽬后台调⽤旧项⽬的接⼝,通过token获取登录⽤户信息,将登录信息存⼊redis实现免登录,具体代码如下:
import java.io.IOException;
import javax.servlet.FilterChain;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.authentication.UsernamePasswordAuthenticationToken;
import org.ontext.SecurityContextHolder;
import org.springframework.security.web.authentication.WebAuthenticationDetailsSource;
import org.springframework.stereotype.Component;
import org.springframework.web.filter.OncePerRequestFilter;
import com.stant.Constants;
import com.hzbs.servermon.utils.SecurityUtils;
import com.hzbs.servermon.utils.StringUtils;
import com.hzbs.server.security.LoginUser;
import com.hzbs.server.security.service.TokenService;
@Component
public class JwtAuthenticationTokenFilter extends OncePerRequestFilter
{
@Autowired
private TokenService tokenService;
@Override
protected void doFilterInternal(HttpServletRequest request, HttpServletResponse
response, FilterChain chain)
throws ServletException, IOException
{
LoginUser loginUser = LoginUser(request);
if(loginUser == null){
loginUser = tokenService.checkToken(request);
}
if (StringUtils.isNotNull(loginUser) &&
StringUtils.Authentication()))
{
tokenService.verifyToken(loginUser);
UsernamePasswordAuthenticationToken authenticationToken = new
UsernamePasswordAuthenticationToken(loginUser, null,
authenticationToken.setDetails(new
WebAuthenticationDetailsSource().buildDetails(request));
.setAuthentication(authenticationToken);
}
chain.doFilter(request, response);
}
}
/**
* 验证token
*/
public LoginUser checkToken(HttpServletRequest request) {
String token = Token(request);
BufferedReader br = null;
if (StringUtils.isNotEmpty(token)) {
if (StringUtils.isNotEmpty(token)) {
HttpURLConnection conn = null;
URL url = null;
try {
url = new URL(checkTokenUrl);
conn = (HttpURLConnection) url.openConnection();
// 设置超时
conn.setConnectTimeout(1000 * 10);
// 设置请求⽅式
conn.setRequestMethod("POST");
// 设置请求头和编码
conn.setRequestProperty("Content-Type",
"application/json;charset=UTF-8");
conn.setDoOutput(true);
conn.setUseCaches(false);
conn.setRequestProperty("Authorization", token);
if (ResponseCode() == 200) {
br = new BufferedReader(new
InputStream(),"UTF-8"));
StringBuilder sb = new StringBuilder();
String index;
while((index = br.readLine())!=null){
sb.append(index);
}
JSONObject jobj = JSONObject.String());
jobj = JSONObject.("data").toString());
LoginUser user = JavaObject(LoginUser.class);
Claims claims = parseToken(token);
// 解析对应的权限以及⽤户信息
String uuid = (String) (Constants.LOGIN_USER_KEY);
String userKey = getTokenKey(uuid);
redisCache.setCacheObject(userKey, user);
return user;
}
} catch (Exception e) {
e.printStackTrace();
} finally {
if(br!=null){
try {
br.close();
} catch (IOException e) {
e.printStackTrace();
}
}
if (conn != null) {
conn.disconnect();
}
}
}
return null;
}
/**
* 缓存基本的对象,Integer、String、实体类等
*
* @param key 缓存的键值
* @param value 缓存的值
* @return 缓存的对象
*/
public <T> ValueOperations<String, T> setCacheObject(String key, T value) {
ValueOperations<String, T> operation = redisTemplate.opsForValue(); operation.set(key, value);
return operation;
}
}
/**
* 验证前端传过来的token是否正确
* @param token
* @return
*/
@PostMapping("/checkToken")
public AjaxResult checkToken(HttpServletRequest request){ LoginUser user = LoginUser(request);
if(user != null){
return AjaxResult.success(user);
}
(500,null);
}
/**
* 返回成功数据
*
* @return 成功消息
*/
public static AjaxResult success(Object data)
{
return AjaxResult.success("操作成功", data);
}
/**
* 返回成功消息
*
* @param msg 返回内容
* @param data 数据对象
* @return 成功消息
*/
public static AjaxResult success(String msg, Object data)
{
return new AjaxResult(HttpStatus.SUCCESS, msg, data); }
/**
* 返回错误消息
*
* @param code 状态码
* @param msg 返回内容
* @return 警告消息
*/
public static AjaxResult error(int code, String msg)
{
return new AjaxResult(code, msg, null);
}
/**
* 获取⽤户⾝份信息
*
* @return ⽤户信息
*/
public LoginUser getLoginUser(HttpServletRequest request) {
// 获取请求携带的令牌
String token = getToken(request);
if (StringUtils.isNotEmpty(token))
{
Claims claims = parseToken(token);
// 解析对应的权限以及⽤户信息
// 解析对应的权限以及⽤户信息
String uuid = (String) ("login_user_key");
String userKey = getTokenKey(uuid);
LoginUser user = CacheObject(userKey);
return user;
}
return null;
}
/**
* 获得缓存的基本对象。
*
* @param key 缓存键值
* @return 缓存键值对应的数据
*/
public <T> T getCacheObject(String key)
{
ValueOperations<String, T> operation = redisTemplate.opsForValue(); (key);
}
/**
* 登录⽤户 redis key
*/
public static final String LOGIN_TOKEN_KEY = "login_tokens:";
private String getTokenKey(String uuid)
{
return Constants.LOGIN_TOKEN_KEY + uuid;
}
/**
* 从令牌中获取数据声明
*
* @param token 令牌
* @return 数据声明
*/
private Claims parseToken(String token)
{
return Jwts.parser()
.setSigningKey("abcdefghijklmnopqrstuvwxyz")
.
parseClaimsJws(token)
.getBody();
}
/**
* 获取请求token
*
* @param request
* @return token
*/
private String getToken(HttpServletRequest request)
{
String token = Header("Authorization");
if (StringUtils.isNotEmpty(token) &&
token.startsWith(Constants.TOKEN_PREFIX))
{
token = place("Bearer", "");
}
return token;
}web端登录
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系QQ:729038198,我们将在24小时内删除。
发表评论