找了很多,这两篇结合一下,基本涉及到了所有点:
https://www.cnblogs.com/HowieYuan/p/9259638.html
https://www.cnblogs.com/xifengxiaoma/p/9508760.html
补充:
shiro进入授权方法一共有四种情况:
1、通过代码:subject.hasRole(“admin”) 或 subject.isPermitted(“admin”):自己去调用这个是否有什么角色或者是否有什么权限的时候;
2、@RequiresRoles("admin") :在方法上加这个注解的时候;
3、<shiro:hasRole> <shiro:hasPermission name="XX">在页面上加shiro标签的时候,即进这个页面的时候扫描到有这个标签的时候。
4、配置了过滤器链也会进入:filterChainDefinitionMap.put("/admin/**", "roles[admin]");
另 : 重写DefaultWebSessionManager
正常来讲 Shiro 是从 Cookie 中获取 SessionId 的,然后找到相对应的 Session 来保证用户登陆的正确性和权限的正确性,
但是在前后端分离的项目中,由于每次的 SessionId 都是不一样的,所以我这里选择的是重写 DefaultWebSessionManager 的部分方法,
然后在用户登陆的时候给前端返回 SessionId 来当用户的凭证信息,前端在请求头中携带信息,来解决 Shiro 的用户 Token 认证问题。代码如下:
public class WebSessionManager extends DefaultWebSessionManager {
private static final String AUTHORIZATION = "Authorization";
private static final String SESSION_ID_SOURCE = "Stateless request";
public WebSessionManager() {
super();
}
@Override
protected Serializable getSessionId(ServletRequest request, ServletResponse response) {
HttpServletRequest httpServletRequest = WebUtils.toHttp(request);
String token = httpServletRequest.getHeader(AUTHORIZATION);
request.setAttribute(ShiroHttpServletRequest.REFERENCED_SESSION_ID_SOURCE, SESSION_ID_SOURCE);
request.setAttribute(ShiroHttpServletRequest.REFERENCED_SESSION_ID, token);
request.setAttribute(ShiroHttpServletRequest.REFERENCED_SESSION_ID_IS_VALID, Boolean.TRUE);
//不会把sessionId放在URL后
request.setAttribute(ShiroHttpServletRequest.SESSION_ID_URL_REWRITING_ENABLED, Boolean.FALSE);
return token;
}
}
配置类添加安全管理器Bean:
@Bean
public SecurityManager securityManager() {
// 将自定义 Realm 加进来
DefaultSecurityManager securityManager = new DefaultWebSecurityManager(adminAuthRealm());
// Use a custom sessionManager
WebSessionManager webSessionManager = new WebSessionManager();
// Set the session expiration time 1 hour
webSessionManager.setGlobalSessionTimeout(3600000);
webSessionManager.setSessionDAO(new EnterpriseCacheSessionDAO());
securityManager.setSessionManager(webSessionManager);
return securityManager;
}