【java】RuoYiBootstrap多模块版本-新写的接口,用接口工具访问,状态码302,访问不到。打的断点也进不去
你如果着急,可以直接看
《ShiroConfig.java文件源码-过滤器配置-重点代码》
重点
- 状态码:302
- 访问不到
- 断点进不去
状态码:302,解决了,“访问不到”和“断点进不去”的问题也就解决了
原因
程序流程逻辑可以看我之前发的章:
文章链接:
【java】RuoYiBootstrap多模块版本-登陆请求流程解析
通过文章,我们了解到程序业务被shiro的过滤器
给拦截了。
意味着,程序拿不到用户的登陆状态,
所以,我们的请求,被302跳转到了登陆页面
。
解决
既然知道了原因,那我们就知道怎么解决了,找到shiro的过滤器
.
- 模块:ruoyi-framework
- 位置:src/main/java
- 包名:com.ruoyi.framework.config
- 类名:ShiroConfig.java
- 路径 /ruoyi-framework/src/main/java/com/ruoyi/framework/config/ShiroConfig.java
ShiroConfig.java文件源码
package com.ruoyi.framework.config;import java.io.ByteArrayInputStream;
import java.io.IOException;
import java.io.InputStream;
import java.util.LinkedHashMap;
import java.util.List;
import java.util.Map;
import javax.servlet.Filter;
import org.apache.commons.io.IOUtils;
import org.apache.shiro.cache.ehcache.EhCacheManager;
import org.apache.shiro.codec.Base64;
import org.apache.shiro.config.ConfigurationException;
import org.apache.shiro.io.ResourceUtils;
import org.apache.shiro.mgt.SecurityManager;
import org.apache.shiro.spring.security.interceptor.AuthorizationAttributeSourceAdvisor;
import org.apache.shiro.spring.web.ShiroFilterFactoryBean;
import org.apache.shiro.web.mgt.CookieRememberMeManager;
import org.apache.shiro.web.mgt.DefaultWebSecurityManager;
import org.apache.shiro.web.servlet.SimpleCookie;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import com.ruoyi.common.constant.Constants;
import com.ruoyi.common.utils.StringUtils;
import com.ruoyi.common.utils.security.CipherUtils;
import com.ruoyi.common.utils.spring.SpringUtils;
import com.ruoyi.framework.config.properties.PermitAllUrlProperties;
import com.ruoyi.framework.shiro.realm.UserRealm;
import com.ruoyi.framework.shiro.session.OnlineSessionDAO;
import com.ruoyi.framework.shiro.session.OnlineSessionFactory;
import com.ruoyi.framework.shiro.web.CustomShiroFilterFactoryBean;
import com.ruoyi.framework.shiro.web.filter.LogoutFilter;
import com.ruoyi.framework.shiro.web.filter.captcha.CaptchaValidateFilter;
import com.ruoyi.framework.shiro.web.filter.kickout.KickoutSessionFilter;
import com.ruoyi.framework.shiro.web.filter.online.OnlineSessionFilter;
import com.ruoyi.framework.shiro.web.filter.sync.SyncOnlineSessionFilter;
import com.ruoyi.framework.shiro.web.session.OnlineWebSessionManager;
import com.ruoyi.framework.shiro.web.session.SpringSessionValidationScheduler;
import at.pollux.thymeleaf.shiro.dialect.ShiroDialect;/*** 权限配置加载* * @author ruoyi*/
@Configuration
public class ShiroConfig
{/*** Session超时时间,单位为毫秒(默认30分钟)*/@Value("${shiro.session.expireTime}")private int expireTime;/*** 相隔多久检查一次session的有效性,单位毫秒,默认就是10分钟*/@Value("${shiro.session.validationInterval}")private int validationInterval;/*** 同一个用户最大会话数*/@Value("${shiro.session.maxSession}")private int maxSession;/*** 踢出之前登录的/之后登录的用户,默认踢出之前登录的用户*/@Value("${shiro.session.kickoutAfter}")private boolean kickoutAfter;/*** 验证码开关*/@Value("${shiro.user.captchaEnabled}")private boolean captchaEnabled;/*** 验证码类型*/@Value("${shiro.user.captchaType}")private String captchaType;/*** 设置Cookie的域名*/@Value("${shiro.cookie.domain}")private String domain;/*** 设置cookie的有效访问路径*/@Value("${shiro.cookie.path}")private String path;/*** 设置HttpOnly属性*/@Value("${shiro.cookie.httpOnly}")private boolean httpOnly;/*** 设置Cookie的过期时间,秒为单位*/@Value("${shiro.cookie.maxAge}")private int maxAge;/*** 设置cipherKey密钥*/@Value("${shiro.cookie.cipherKey}")private String cipherKey;/*** 登录地址*/@Value("${shiro.user.loginUrl}")private String loginUrl;/*** 权限认证失败地址*/@Value("${shiro.user.unauthorizedUrl}")private String unauthorizedUrl;/*** 是否开启记住我功能*/@Value("${shiro.rememberMe.enabled: false}")private boolean rememberMe;/*** 缓存管理器 使用Ehcache实现*/@Beanpublic EhCacheManager getEhCacheManager(){net.sf.ehcache.CacheManager cacheManager = net.sf.ehcache.CacheManager.getCacheManager("ruoyi");EhCacheManager em = new EhCacheManager();if (StringUtils.isNull(cacheManager)){em.setCacheManager(new net.sf.ehcache.CacheManager(getCacheManagerConfigFileInputStream()));return em;}else{em.setCacheManager(cacheManager);return em;}}/*** 返回配置文件流 避免ehcache配置文件一直被占用,无法完全销毁项目重新部署*/protected InputStream getCacheManagerConfigFileInputStream(){String configFile = "classpath:ehcache/ehcache-shiro.xml";InputStream inputStream = null;try{inputStream = ResourceUtils.getInputStreamForPath(configFile);byte[] b = IOUtils.toByteArray(inputStream);InputStream in = new ByteArrayInputStream(b);return in;}catch (IOException e){throw new ConfigurationException("Unable to obtain input stream for cacheManagerConfigFile [" + configFile + "]", e);}finally{IOUtils.closeQuietly(inputStream);}}/*** 自定义Realm*/@Beanpublic UserRealm userRealm(EhCacheManager cacheManager){UserRealm userRealm = new UserRealm();userRealm.setAuthorizationCacheName(Constants.SYS_AUTH_CACHE);userRealm.setCacheManager(cacheManager);return userRealm;}/*** 自定义sessionDAO会话*/@Beanpublic OnlineSessionDAO sessionDAO(){OnlineSessionDAO sessionDAO = new OnlineSessionDAO();return sessionDAO;}/*** 自定义sessionFactory会话*/@Beanpublic OnlineSessionFactory sessionFactory(){OnlineSessionFactory sessionFactory = new OnlineSessionFactory();return sessionFactory;}/*** 会话管理器*/@Beanpublic OnlineWebSessionManager sessionManager(){OnlineWebSessionManager manager = new OnlineWebSessionManager();// 加入缓存管理器manager.setCacheManager(getEhCacheManager());// 删除过期的sessionmanager.setDeleteInvalidSessions(true);// 设置全局session超时时间manager.setGlobalSessionTimeout(expireTime * 60 * 1000);// 去掉 JSESSIONIDmanager.setSessionIdUrlRewritingEnabled(false);// 定义要使用的无效的Session定时调度器manager.setSessionValidationScheduler(SpringUtils.getBean(SpringSessionValidationScheduler.class));// 是否定时检查sessionmanager.setSessionValidationSchedulerEnabled(true);// 自定义SessionDaomanager.setSessionDAO(sessionDAO());// 自定义sessionFactorymanager.setSessionFactory(sessionFactory());return manager;}/*** 安全管理器*/@Beanpublic SecurityManager securityManager(UserRealm userRealm){DefaultWebSecurityManager securityManager = new DefaultWebSecurityManager();// 设置realm.securityManager.setRealm(userRealm);// 记住我securityManager.setRememberMeManager(rememberMe ? rememberMeManager() : null);// 注入缓存管理器;securityManager.setCacheManager(getEhCacheManager());// session管理器securityManager.setSessionManager(sessionManager());return securityManager;}/*** 退出过滤器*/public LogoutFilter logoutFilter(){LogoutFilter logoutFilter = new LogoutFilter();logoutFilter.setLoginUrl(loginUrl);return logoutFilter;}/*** Shiro过滤器配置*/@Beanpublic ShiroFilterFactoryBean shiroFilterFactoryBean(SecurityManager securityManager){CustomShiroFilterFactoryBean shiroFilterFactoryBean = new CustomShiroFilterFactoryBean();// Shiro的核心安全接口,这个属性是必须的shiroFilterFactoryBean.setSecurityManager(securityManager);// 身份认证失败,则跳转到登录页面的配置shiroFilterFactoryBean.setLoginUrl(loginUrl);// 权限认证失败,则跳转到指定页面shiroFilterFactoryBean.setUnauthorizedUrl(unauthorizedUrl);// Shiro连接约束配置,即过滤链的定义LinkedHashMap<String, String> filterChainDefinitionMap = new LinkedHashMap<>();// 对静态资源设置匿名访问filterChainDefinitionMap.put("/favicon.ico**", "anon");filterChainDefinitionMap.put("/ruoyi.png**", "anon");filterChainDefinitionMap.put("/html/**", "anon");filterChainDefinitionMap.put("/css/**", "anon");filterChainDefinitionMap.put("/docs/**", "anon");filterChainDefinitionMap.put("/fonts/**", "anon");filterChainDefinitionMap.put("/img/**", "anon");filterChainDefinitionMap.put("/ajax/**", "anon");filterChainDefinitionMap.put("/js/**", "anon");filterChainDefinitionMap.put("/ruoyi/**", "anon");filterChainDefinitionMap.put("/captcha/captchaImage**", "anon");// 匿名访问不鉴权注解列表List<String> permitAllUrl = SpringUtils.getBean(PermitAllUrlProperties.class).getUrls();if (StringUtils.isNotEmpty(permitAllUrl)){permitAllUrl.forEach(url -> filterChainDefinitionMap.put(url, "anon"));}// 退出 logout地址,shiro去清除sessionfilterChainDefinitionMap.put("/logout", "logout");// 不需要拦截的访问filterChainDefinitionMap.put("/login", "anon,captchaValidate");// 不需要拦截的访问filterChainDefinitionMap.put("/jjy/**", "anon");// 注册相关filterChainDefinitionMap.put("/register", "anon,captchaValidate");// 系统权限列表// filterChainDefinitionMap.putAll(SpringUtils.getBean(IMenuService.class).selectPermsAll());Map<String, Filter> filters = new LinkedHashMap<String, Filter>();filters.put("onlineSession", onlineSessionFilter());filters.put("syncOnlineSession", syncOnlineSessionFilter());filters.put("captchaValidate", captchaValidateFilter());filters.put("kickout", kickoutSessionFilter());// 注销成功,则跳转到指定页面filters.put("logout", logoutFilter());shiroFilterFactoryBean.setFilters(filters);// 所有请求需要认证filterChainDefinitionMap.put("/**", "user,kickout,onlineSession,syncOnlineSession");shiroFilterFactoryBean.setFilterChainDefinitionMap(filterChainDefinitionMap);return shiroFilterFactoryBean;}/*** 自定义在线用户处理过滤器*/public OnlineSessionFilter onlineSessionFilter(){OnlineSessionFilter onlineSessionFilter = new OnlineSessionFilter();onlineSessionFilter.setLoginUrl(loginUrl);onlineSessionFilter.setOnlineSessionDAO(sessionDAO());return onlineSessionFilter;}/*** 自定义在线用户同步过滤器*/public SyncOnlineSessionFilter syncOnlineSessionFilter(){SyncOnlineSessionFilter syncOnlineSessionFilter = new SyncOnlineSessionFilter();syncOnlineSessionFilter.setOnlineSessionDAO(sessionDAO());return syncOnlineSessionFilter;}/*** 自定义验证码过滤器*/public CaptchaValidateFilter captchaValidateFilter(){CaptchaValidateFilter captchaValidateFilter = new CaptchaValidateFilter();captchaValidateFilter.setCaptchaEnabled(captchaEnabled);captchaValidateFilter.setCaptchaType(captchaType);return captchaValidateFilter;}/*** cookie 属性设置*/public SimpleCookie rememberMeCookie(){SimpleCookie cookie = new SimpleCookie("rememberMe");cookie.setDomain(domain);cookie.setPath(path);cookie.setHttpOnly(httpOnly);cookie.setMaxAge(maxAge * 24 * 60 * 60);return cookie;}/*** 记住我*/public CookieRememberMeManager rememberMeManager(){CookieRememberMeManager cookieRememberMeManager = new CookieRememberMeManager();cookieRememberMeManager.setCookie(rememberMeCookie());if (StringUtils.isNotEmpty(cipherKey)){cookieRememberMeManager.setCipherKey(Base64.decode(cipherKey));}else{cookieRememberMeManager.setCipherKey(CipherUtils.generateNewKey(128, "AES").getEncoded());}return cookieRememberMeManager;}/*** 同一个用户多设备登录限制*/public KickoutSessionFilter kickoutSessionFilter(){KickoutSessionFilter kickoutSessionFilter = new KickoutSessionFilter();kickoutSessionFilter.setCacheManager(getEhCacheManager());kickoutSessionFilter.setSessionManager(sessionManager());// 同一个用户最大的会话数,默认-1无限制;比如2的意思是同一个用户允许最多同时两个人登录kickoutSessionFilter.setMaxSession(maxSession);// 是否踢出后来登录的,默认是false;即后者登录的用户踢出前者登录的用户;踢出顺序kickoutSessionFilter.setKickoutAfter(kickoutAfter);// 被踢出后重定向到的地址;kickoutSessionFilter.setKickoutUrl("/login?kickout=1");return kickoutSessionFilter;}/*** thymeleaf模板引擎和shiro框架的整合*/@Beanpublic ShiroDialect shiroDialect(){return new ShiroDialect();}/*** 开启Shiro注解通知器*/@Beanpublic AuthorizationAttributeSourceAdvisor authorizationAttributeSourceAdvisor(@Qualifier("securityManager") SecurityManager securityManager){AuthorizationAttributeSourceAdvisor authorizationAttributeSourceAdvisor = new AuthorizationAttributeSourceAdvisor();authorizationAttributeSourceAdvisor.setSecurityManager(securityManager);return authorizationAttributeSourceAdvisor;}
}
ShiroConfig.java文件源码-过滤器配置
- 代码所在行:第270行
/*** Shiro过滤器配置*/@Beanpublic ShiroFilterFactoryBean shiroFilterFactoryBean(SecurityManager securityManager){CustomShiroFilterFactoryBean shiroFilterFactoryBean = new CustomShiroFilterFactoryBean();// Shiro的核心安全接口,这个属性是必须的shiroFilterFactoryBean.setSecurityManager(securityManager);// 身份认证失败,则跳转到登录页面的配置shiroFilterFactoryBean.setLoginUrl(loginUrl);// 权限认证失败,则跳转到指定页面shiroFilterFactoryBean.setUnauthorizedUrl(unauthorizedUrl);// Shiro连接约束配置,即过滤链的定义LinkedHashMap<String, String> filterChainDefinitionMap = new LinkedHashMap<>();// 对静态资源设置匿名访问filterChainDefinitionMap.put("/favicon.ico**", "anon");filterChainDefinitionMap.put("/ruoyi.png**", "anon");filterChainDefinitionMap.put("/html/**", "anon");filterChainDefinitionMap.put("/css/**", "anon");filterChainDefinitionMap.put("/docs/**", "anon");filterChainDefinitionMap.put("/fonts/**", "anon");filterChainDefinitionMap.put("/img/**", "anon");filterChainDefinitionMap.put("/ajax/**", "anon");filterChainDefinitionMap.put("/js/**", "anon");filterChainDefinitionMap.put("/ruoyi/**", "anon");filterChainDefinitionMap.put("/captcha/captchaImage**", "anon");// 匿名访问不鉴权注解列表List<String> permitAllUrl = SpringUtils.getBean(PermitAllUrlProperties.class).getUrls();if (StringUtils.isNotEmpty(permitAllUrl)){permitAllUrl.forEach(url -> filterChainDefinitionMap.put(url, "anon"));}// 退出 logout地址,shiro去清除sessionfilterChainDefinitionMap.put("/logout", "logout");// 不需要拦截的访问filterChainDefinitionMap.put("/login", "anon,captchaValidate");// 不需要拦截的访问filterChainDefinitionMap.put("/jjy/**", "anon");// 注册相关filterChainDefinitionMap.put("/register", "anon,captchaValidate");// 系统权限列表// filterChainDefinitionMap.putAll(SpringUtils.getBean(IMenuService.class).selectPermsAll());Map<String, Filter> filters = new LinkedHashMap<String, Filter>();filters.put("onlineSession", onlineSessionFilter());filters.put("syncOnlineSession", syncOnlineSessionFilter());filters.put("captchaValidate", captchaValidateFilter());filters.put("kickout", kickoutSessionFilter());// 注销成功,则跳转到指定页面filters.put("logout", logoutFilter());shiroFilterFactoryBean.setFilters(filters);// 所有请求需要认证filterChainDefinitionMap.put("/**", "user,kickout,onlineSession,syncOnlineSession");shiroFilterFactoryBean.setFilterChainDefinitionMap(filterChainDefinitionMap);return shiroFilterFactoryBean;}
ShiroConfig.java文件源码-过滤器配置-重点代码
// 退出 logout地址,shiro去清除session
filterChainDefinitionMap.put("/logout", "logout");
// 不需要拦截的访问
filterChainDefinitionMap.put("/login", "anon,captchaValidate");
我们需要根据上面的匹配规则,
来增加我们的接口
// 不需要拦截的访问
filterChainDefinitionMap.put("/jjy/**", "anon");
我的这段代码的意思是:
如果访问地址是http://localhost:8031/jjy/**
将不再拦截
就是说路以/jjy/
开头,都不会被拦截
如:
http://localhost:8031/jjy/user/list
不会被拦截
http://localhost:8031/jjy/user/get
不会被拦截
http://localhost:8031/jjy/GetCongfig
不会被拦截
延伸阅读-过滤器匹配规则
-
Shiro是一个Java的安全框架,可以简单实现登录、鉴权等等的功能。
Basic认证是一种较为简单的HTTP认证方式,客户端通过明文(Base64编码格式)传输用户名和密码到服务端进行认证,通常需要配合HTTPS来保证信息传输的安全。 -
Java 项目中集成 Shiro 框架的配置代码,
用于配置 Shiro 的 URL 拦截规则。
具体来说,它创建了一个LinkedHashMap<string,string〉对象,用于存储 URL拦截规则,其中 key是 URL的模式匹配规则,value 是该 URL需要执行的拦截器。 -
fiterchaindefinitionmap是一个过滤器链定义映射,用于在Shir0安全框架中定义过滤器链。
它可以指定不同的URL路径需要使用哪些过滤器,
以及这些过滤器的顺序和参数。
这个映射可以在Shiro的配置文件中进行配置,
以便在应用程序中实现安全控制。
filterChainDefinitionMap.put("/admin", "authc");
filterChainDefinitionMap.put("/admin/**", "requestURL");
filterChainDefinitionMap.put("/**", "anon");
shiroFilterFactoryBean.setFilterChainDefinitionMap(filterChainDefinitionMap);
在这个配置中,它定义了三个 URL 拦截规则:
/admin:
需要进行用户认证(authc)才能访问;/admin/**:
需要使用自定义的拦截器(requestURL)进行权限控制;/**:
不需要进行任何拦截,即允许匿名访问。
最后,它将这个 URL拦截规则设置到shirofilterfactoryBean
对象的filterchainpefinitionap
属性中,然后返回该对象.
Shiro 规则说明
Shiro 内置了很多默认的拦截器,比如身份验证、授权等相关的。默认拦截器可以参考 org.apache.shiro.web.filter.mgt.DefaultFilter 中的枚举拦截器:
默认拦截器名 | 拦截器类 | 说明(括号里的表示默认值) |
---|---|---|
身份验证相关的 | - | - |
authc | org.apache.shiro.web.filter.authc.FormAuthenticationFilter | left-aligned: 基于表单的拦截器;如“/**=authc”,如果没有登录会跳到相应的登录页面登录;主要属性:usernameParam:表单提交的用户名参数名(username); passwordParam:表单提交的密码参数名(password);rememberMeParam:表单提交的密码参数名(rememberMe); loginUrl:登录页面地址(/login.jsp);successUrl:登录成功后的默认重定向地址;failureKeyAttribute:登录失败后错误信息存储key(shiroLoginFailure); |
authcBasic | org.apache.shiro.web.filter.authc.BasicHttpAuthenticationFilter | BasicHTTP身份验证拦截器,主要属性:applicationName:弹出登录框显示的信息(application); |
logout | org.apache.shiro.web.filter.authc.LogoutFilter | 退出拦截器,主要属性:redirectUrl:退出成功后重定向的地址(/);示例“/logout=logout” |
user | org.apache.shiro.web.filter.authc.UserFilter | 用户拦截器,用户已经身份验证/记住我登录的都可;示例“/**=user” |
anon | org.apache.shiro.web.filter.authc.AnonymousFilter | 匿名拦截器,即不需要登录即可访问;一般用于静态资源过滤;示例“/static/**=anon” |
授权相关的 | - | - |
roles | org.apache.shiro.web.filter.authz.RolesAuthorizationFilter | 角色授权拦截器,验证用户是否拥有所有角色;主要属性:loginUrl:登录页面地址(/login.jsp);unauthorizedUrl:未授权后重定向的地址;示例“/admin/**=roles[admin]” |
perms | org.apache.shiro.web.filter.authz.PermissionsAuthorizationFilter | 权限授权拦截器,验证用户是否拥有所有权限;属性和roles一样;示例“/user/**=perms[“user:create”]” |
port | org.apache.shiro.web.filter.authz.PortFilter | 端口拦截器,主要属性:port(80):可以通过的端口;示例“/test=port[80]”,如果用户访问该页面是非80,将自动将请求端口改为80并重定向到该80端口,其他路径/参数等都一样 |
rest | org.apache.shiro.web.filter.authz.HttpMethodPermissionFilter | rest风格拦截器,自动根据请求方法构建权限字符串(GET=read,POST=create,PUT=update,DELETE=delete,HEAD=read,TRACE=read,OPTIONS=read,MKCOL=create)构建权限字符串;示例“/users=rest[user]”,会自动拼出“user:read,user:create,user:update,user:delete”权限字符串进行权限匹配(所有都得匹配,isPermittedAll); |
ssl | org.apache.shiro.web.filter.authz.SslFilter | SSL拦截器,只有请求协议是https才能通过;否则自动跳转会https端口(443);其他和port拦截器一样; |
其他 | - | - |
noSessionCreation | org.apache.shiro.web.filter.session.NoSessionCreationFilter | 不创建会话拦截器,调用subject.getSession(false)不会有什么问题,但是如果subject.getSession(true)将抛出DisabledSessionException异常; |
另外还提供了一个 org.apache.shiro.web.filter.authz.HostFilter,即主机拦截器,比如其提供了属性:authorizedIps:已授权的 ip 地址,deniedIps:表示拒绝的 ip 地址;不过目前还没有完全实现,不可用。
这些默认的拦截器会自动注册,可以直接在 ini 配置文件中通过 “拦截器名. 属性” 设置其属性:
perms.unauthorizedUrl=/unauthorized
另外如果某个拦截器不想使用了可以直接通过如下配置直接禁用:
perms.enabled=false
你也可以通过下面文章进行了解Shiro 入门教程 - Shiro 拦截器机制