jwt 拦截器
用来拦截登陆,判断token是否生效
这里demo的token是在session中拿到的token,登陆时将token存入了session当中
@Slf4j
public class JWTFilter extends AuthenticationFilter {
/**
* 判断用户是否想要登入。
* 检测 header 里面是否包含 Token
*/
protected boolean isLoginAttempt(HttpServletRequest request, ServletResponse response) {
HttpServletRequest req = (HttpServletRequest) request;
HttpSession session = req.getSession();
String token = (String) session.getAttribute("token"); //这个是将token放入session中
//String token = req.getHeader(JWTUtil.AUTHORIZATION); 这个是将token放入header中
return token != null;
}
@Override
protected boolean isAccessAllowed(ServletRequest request, ServletResponse response, Object mappedValue) {
if (isLoginAttempt((HttpServletRequest) request, response)) {
UserVO user = (UserVO) SecurityUtils.getSubject().getPrincipal();
if (user != null) {
return JWTUtil.verify(user.getToken(), user.getUserName(), user.getId());
}
}
return false;
}
@Override
protected boolean onAccessDenied(ServletRequest request, ServletResponse response) throws Exception {
HttpServletRequest res = (HttpServletRequest) request;
HttpSession session = res.getSession();
String token = (String) session.getAttribute("token");
Boolean isLogin = false;
if (!StringUtils.isEmpty(token)) {
JWTToken loginToken = new JWTToken(token);
log.debug("使用Token进行登录:" + token);
try {
getSubject(request, response).login(loginToken);
isLogin = true;
} catch (AuthenticationException exp) {
getSubject(request, response).logout();
}
}
//登录后续操作
if (isLogin) {
UserVO user = (UserVO) SecurityUtils.getSubject().getPrincipal();
log.debug("当前登录用户:" + user);
issueSuccessRedirect(request, response);
} else {
//跳转401
response401(request, response);
}
return isLogin;
}
/**
* 对跨域提供支持
*/
@Override
protected boolean preHandle(ServletRequest request, ServletResponse response) throws Exception {
HttpServletRequest httpServletRequest = (HttpServletRequest) request;
HttpServletResponse httpServletResponse = (HttpServletResponse) response;
httpServletResponse.setHeader("Access-control-Allow-Origin", httpServletRequest.getHeader("Origin"));
httpServletResponse.setHeader("Access-Control-Allow-Methods", "GET,POST,OPTIONS,PUT,DELETE");
httpServletResponse.setHeader("Access-Control-Allow-Headers",
httpServletRequest.getHeader("Access-Control-Request-Headers"));
if (httpServletRequest.getMethod().equals(RequestMethod.OPTIONS.name())) {
httpServletResponse.setStatus(HttpStatus.OK.value());
return false;
}
return super.preHandle(request, response);
}
/**
* 将非法请求跳转到
*/
private void response401(ServletRequest req, ServletResponse resp) {
//Ajax请求
if (isAjaxRequest(req)) {
HttpServletResponse response = (HttpServletResponse) resp;
response.setContentType("application/json;charset=UTF-8");
response.setCharacterEncoding("UTF-8");
String msg = "当前会话已经失效,需要重新登录后才能继续操作";
ResponseData data = ResponseData.newFailed()
.setStatus(401)
.setCode("401")
.setMessage(msg)
.setMessage(msg);
try {
PrintWriter out = response.getWriter();
out.print(new Gson().toJson(data));
out.flush();
out.close();
} catch (IOException e) {
log.error(e.getMessage());
}
} else {
//非AJAX请求
try {
saveRequestAndRedirectToLogin(req, resp);
} catch (IOException e) {
log.error(e.getMessage());
}
}
}
/**
* 判断是否为ajax请求
*/
private boolean isAjaxRequest(ServletRequest request) {
HttpServletRequest httpServletRequest = (HttpServletRequest) request;
String requestedWith = httpServletRequest.getHeader("X-Requested-With");
return "XMLHttpRequest".equalsIgnoreCase(requestedWith);
}
@Override
protected void issueSuccessRedirect(ServletRequest request,
ServletResponse response) throws Exception {
HttpServletRequest httpServletRequest = (HttpServletRequest) request;
log.debug("跳转至:" + httpServletRequest.getRequestURL());
String superURL = httpServletRequest.getRequestURI();
WebUtils.issueRedirect(request, response, superURL, null, true);
}
}
JWT工具类
用来生成token及解析token还原token中的用户信息等
@Slf4j
public class JWTUtil {
public final static String USER_ID = "user_id";
public final static String APP_CODE = "app_code";
public final static String USER_NAME = "user_name";
private final static String SECRET = "0b2ad71cfedc4feab58000db9e59d7bc";
public static final String AUTHORIZATION = "auth-token";
/**
* 过期时间
*
* @Deprecated
*/
private static final long EXPIRE_TIME = 1000 * 60 * 60 * 24;
/**
* 验证Token是否正确
*
* @param token 需要验证的token
* @param userName 需要验证的用户名
* @param userId 用户id
* @return 验证结果,正确返回true,反之false
*/
public static boolean verify(String token, String userName, Long userId) {
try {
//不考虑token本身的失效时间,由应用的缓存去控制
Algorithm algorithm = Algorithm.HMAC256(SECRET);
JWTVerifier verifier = JWT.require(algorithm)
.withClaim(USER_NAME, userName)
.withClaim(USER_ID, userId)
.build();
verifier.verify(token);
return true;
} catch (TokenExpiredException exp) {
log.error(String.format("用户[%s]登录用token[%s]已经过期", userName, token));
return false;
} catch (JWTVerificationException exp) {
log.error(String.format("用户[%s]登录用token[%s]已经失效", userId, token));
return false;
} catch (Exception exception) {
log.error(String.format("用户[%s]登录用token[%s]验证失败, 失败原因: %s", userName, token, exception.getMessage()), exception);
return false;
// throw new ServiceException(String.format("用户[%s]登录用token[%s]验证失败, 失败原因: %s", userName, token, exception.getMessage()), exception);
}
}
/**
* 注册生成JWT
*
* @param userName 用户账号
* @param userId 用户id
* @return 生成的Token
*/
public static String sign(String userName, Long userId) {
Date date = new Date(System.currentTimeMillis() + EXPIRE_TIME);
Algorithm algorithm = Algorithm.HMAC256(SECRET);
return JWT.create()
.withClaim(USER_NAME, userName)
.withClaim(USER_ID, userId)
.withExpiresAt(date)
.sign(algorithm);
}
/**
* 从Token中获取userId
*
* @param token 需要解析的token
* @return 解析出的字段值
*/
public static Long getUserId(String token) {
try {
DecodedJWT jwt = parseJWT(token);
return jwt.getClaim(USER_ID) != null ? jwt.getClaim(USER_ID).asLong() : null;
} catch (JWTDecodeException e) {
return null;
}
}
/**
* 获取账号
*
* @param token
* @return
*/
public static String getUserName(String token) {
try {
DecodedJWT jwt = parseJWT(token);
return jwt.getClaim(USER_NAME) != null ? jwt.getClaim(USER_NAME).asString() : null;
} catch (JWTDecodeException e) {
return null;
}
}
/**
* 获取应用编码
*
* @param token
* @return
*/
public static String getAppCode(String token) {
try {
DecodedJWT jwt = parseJWT(token);
return jwt.getClaim(APP_CODE) != null ? jwt.getClaim(APP_CODE).asString() : null;
} catch (JWTDecodeException e) {
return null;
}
}
/**
* 解析JWT
*
* @param jwt
* @return
*/
public static DecodedJWT parseJWT(String jwt) {
Algorithm algorithm = Algorithm.HMAC256(SECRET);
return JWT.require(algorithm).build().verify(jwt);
}
}
UserRealm
登陆之后解析token,设置当前用户信息及用户token
@Slf4j
public class UserRealm extends AuthorizingRealm {
@Autowired
private UserService userService;
/**
* 必须重写此方法,不然Shiro会报错
*/
@Override
public boolean supports(AuthenticationToken token) {
return token instanceof JWTToken;
}
/**
* 只有当需要检测用户权限的时候才会调用此方法,例如checkRole,checkPermission之类的
*/
@Override
protected AuthorizationInfo doGetAuthorizationInfo(PrincipalCollection principals) {
// 创建一个用于返回的授权信息对象
SimpleAuthorizationInfo authorizationInfo = new SimpleAuthorizationInfo();
return authorizationInfo;
}
/**
* 登录之后解析Token,设置当前用户的信息及Token
*/
@Override
protected AuthenticationInfo doGetAuthenticationInfo(AuthenticationToken auth) throws AuthenticationException {
String token = (String) auth.getCredentials();
String userName = JWTUtil.getUserName(token);
Long userId = JWTUtil.getUserId(token);
log.debug("登录验证:" + token + ", " + userId);
if (StringUtils.isEmpty(userName) || userId == null) {
throw new AuthenticationException("用户身份验证失败, Token无效");
}
UserVO user = userService.getUserInfo(userName, userId);
log.debug("用户信息:" + user);
if (user == null) {
throw new AuthenticationException("认证失败, 用户不存在");
} else {
user.setToken(token);
return new SimpleAuthenticationInfo(user, token, getName());
}
}
@Override
public String getName() {
return "familyRealm";
}
}
JWTToken
token存储对象
public class JWTToken implements AuthenticationToken {
private static final long serialVersionUID = -8414484413319621557L;
// public static final String TOKEN_PREFIX = "FAMILY_TOKEN_";
// 密钥
private String token;
public JWTToken(String token) {
this.token = token;
}
@Override
public Object getPrincipal() {
return token;
}
@Override
public Object getCredentials() {
return token;
}
}
Shiro
Shiro相关的配置
@Configuration
public class ShiroConfig {
/**
*
* 配置Shiro安全验证领域对象
*
* @return
*/
@Bean
public Realm passwordAuthorizingRealm() {
return new UserRealm();
}
@Bean
public ModularRealmAuthenticator modularRealmAuthenticator() {
ModularRealmAuthenticator modularRealmAuthenticator = new ModularRealmAuthenticator();
modularRealmAuthenticator.setAuthenticationStrategy(new AtLeastOneSuccessfulStrategy());
return modularRealmAuthenticator;
}
@Bean
public DefaultWebSecurityManager securityManager() {
DefaultWebSecurityManager securityManager = new DefaultWebSecurityManager();
securityManager.setAuthenticator(modularRealmAuthenticator());
List<Realm> realms = new ArrayList<>();
realms.add(passwordAuthorizingRealm());
securityManager.setRealms(realms);
securityManager.setSessionManager(sessionManager());
return securityManager;
}
/**
* 根据Token自定义SessionManager
*
* @return
*/
@Bean
public SessionManager sessionManager() {
TokenSessionManager sessionManager = new TokenSessionManager();
return sessionManager;
}
/**
* ShiroFilter工厂类配置
*
* @param securityManager
* @return
*/
@Bean
public ShiroFilterFactoryBean shiroFilterFactoryBean(SecurityManager securityManager) {
ShiroFilterFactoryBean shiroFilterFactoryBean = new ShiroFilterFactoryBean();
shiroFilterFactoryBean.setSecurityManager(securityManager);
shiroFilterFactoryBean.setLoginUrl("/login/index.html");
// 登录验证
shiroFilterFactoryBean.getFilters().put("authc", new JWTFilter());
// 设置登出重定向
LogoutFilter logout = new LogoutFilter();
shiroFilterFactoryBean.getFilters().put("logout", logout);
Map<String, String> filterChainDefinitionMap = new LinkedHashMap<String, String>();
// 静态资源可直接访问
filterChainDefinitionMap.put("/static/**", "anon");
// filterChainDefinitionMap.put("/api/common/**", "anon");
// 登录相关接口
filterChainDefinitionMap.put("/login**", "anon");
filterChainDefinitionMap.put("/login/**", "anon");
filterChainDefinitionMap.put("/login/login", "anon");
// 认证
filterChainDefinitionMap.put("/api/**", "authc");
filterChainDefinitionMap.put("/test/**", "authc");
filterChainDefinitionMap.put("/**", "authc");
// 登录成功后自动跳转到指定的页面
shiroFilterFactoryBean.setSuccessUrl("/index");
// 未授权界面;
shiroFilterFactoryBean.setFilterChainDefinitionMap(filterChainDefinitionMap);
return shiroFilterFactoryBean;
}
@Bean
public AuthorizationAttributeSourceAdvisor authorizationAttributeSourceAdvisor() {
AuthorizationAttributeSourceAdvisor authorizationAttributeSourceAdvisor = new AuthorizationAttributeSourceAdvisor();
authorizationAttributeSourceAdvisor.setSecurityManager(securityManager());
return authorizationAttributeSourceAdvisor;
}
}
html.js
hml里面设置ajax全局请求头,只要引入该js,ajax会自带带上设置好的token
var isLogin = true; // 是否需要判断登录
var token = localStorage.getItem("token") || '';
$.ajaxSetup({
dataType: "json",
// cache: false,
headers: {
"auth-token": token
},
xhrFields: {
withCredentials: true
},
complete: function(xhr) {
//token过期,则跳转到登录页面
if(xhr.responseJSON != undefined && xhr.responseJSON.code != undefined){
if( xhr.responseJSON.code == 401 && isLogin){
window.location = '/login/index.html';
}
}
}
});