🎨 jwt + shiro

This commit is contained in:
ronger 2022-10-30 00:32:44 +08:00
parent 2e888c1e88
commit bfa169e44e
3 changed files with 30 additions and 16 deletions

View File

@ -1,5 +1,7 @@
package com.rymcu.forest.auth;
import com.alibaba.fastjson2.JSONObject;
import com.rymcu.forest.core.result.GlobalResultGenerator;
import io.jsonwebtoken.Claims;
import io.jsonwebtoken.Jwts;
import io.jsonwebtoken.SignatureException;
@ -72,14 +74,20 @@ public class JwtFilter extends BasicHttpAuthenticationFilter {
*/
@Override
protected boolean isAccessAllowed(ServletRequest request, ServletResponse response, Object mappedValue) {
return false;
}
@Override
protected boolean onAccessDenied(ServletRequest request, ServletResponse response) {
if (isLoginAttempt(request, response)) {
try {
executeLogin(request, response);
} catch (Exception e) {
response401(request, response);
onLoginFail(response);
}
}
return true;
onLoginFail(response);
return false;
}
/**
@ -104,12 +112,12 @@ public class JwtFilter extends BasicHttpAuthenticationFilter {
/**
* 将非法请求跳转到 /401
*/
private void response401(ServletRequest request, ServletResponse response) {
private void onLoginFail(ServletResponse response) {
try {
HttpServletResponse httpResponse = (HttpServletResponse) response;
httpResponse.setStatus(HttpServletResponse.SC_UNAUTHORIZED);
httpResponse.setContentType("application/json;charset=utf-8");
httpResponse.getOutputStream().write("login fail".getBytes());
HttpServletResponse httpServletResponse = (HttpServletResponse) response;
httpServletResponse.setContentType("application/json");
httpServletResponse.setCharacterEncoding("UTF-8");
httpServletResponse.getOutputStream().write(JSONObject.toJSONString(GlobalResultGenerator.genErrorResult("未登录或已登录超时,请重新登录")).getBytes());
} catch (IOException e) {
// 错误日志
log.error(e.getMessage());

View File

@ -34,6 +34,12 @@ public class ShiroConfig {
Map<String, String> filterChainDefinitionMap = new LinkedHashMap<String, String>();
filterChainDefinitionMap.put("/api/v1/console/**", "anon");
filterChainDefinitionMap.put("/api/v1/article/detail/**", "anon");
filterChainDefinitionMap.put("/api/v1/topic/**", "anon");
filterChainDefinitionMap.put("/api/v1/user/**", "anon");
filterChainDefinitionMap.put("/api/v1/article/*/comments", "anon");
filterChainDefinitionMap.put("/api/v1/rule/currency/**", "anon");
filterChainDefinitionMap.put("/api/v1/lucene/**", "anon");
filterChainDefinitionMap.put("/api/v1/open-data/**", "anon");
filterChainDefinitionMap.put("/**", "jwt");
shiroFilterFactoryBean.setFilterChainDefinitionMap(filterChainDefinitionMap);