Blame view

src/main/java/com/huaheng/framework/config/ShiroConfig.java 14.8 KB
tangying authored
1
2
3
4
5
package com.huaheng.framework.config;

import java.util.LinkedHashMap;
import java.util.Map;
import javax.servlet.Filter;
mahuandong authored
6
tangying authored
7
8
9
10
11
12
13
14
import org.apache.shiro.cache.ehcache.EhCacheManager;
import org.apache.shiro.codec.Base64;
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;
易文鹏 authored
15
import org.springframework.beans.factory.annotation.Autowired;
tangying authored
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
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.huaheng.common.utils.StringUtils;
import com.huaheng.framework.shiro.realm.UserRealm;
import com.huaheng.framework.shiro.session.OnlineSessionDAO;
import com.huaheng.framework.shiro.session.OnlineSessionFactory;
import com.huaheng.framework.shiro.web.filter.LogoutFilter;
import com.huaheng.framework.shiro.web.filter.online.OnlineSessionFilter;
import com.huaheng.framework.shiro.web.filter.sync.SyncOnlineSessionFilter;
import com.huaheng.framework.shiro.web.session.OnlineWebSessionManager;
import com.huaheng.framework.shiro.web.session.SpringSessionValidationScheduler;
import at.pollux.thymeleaf.shiro.dialect.ShiroDialect;

/**
 * 权限配置加载
mahuandong authored
33
 *
tangying authored
34
35
36
 * @author huaheng
 */
@Configuration
mahuandong authored
37
public class ShiroConfig {
tangying authored
38
39
    public static final String PREMISSION_STRING = "perms[\"{0}\"]";
易文鹏 authored
40
41
42
43
44
    @Value("${shiro.session.redisEnabled}")
    private boolean redisEnabled;


    // Session超时时间,单位为毫秒
tangying authored
45
46
47
    @Value("${shiro.session.expireTime}")
    private int expireTime;
易文鹏 authored
48
    // 相隔多久检查一次session的有效性,单位毫秒
tangying authored
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
    @Value("${shiro.session.validationInterval}")
    private int validationInterval;

    // 验证码开关
    @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;

    // 登录地址
    @Value("${shiro.user.loginUrl}")
    private String loginUrl;

    // 登录地址
    @Value("/admin/login")
    private String loginUrls;

    // 权限认证失败地址
    @Value("${shiro.user.unauthorizedUrl}")
    private String unauthorizedUrl;
易文鹏 authored
88
89
90
    @Autowired
    private CacheManagerConfig cacheManagerConfig;
tangying authored
91
92
93
    /**
     * 缓存管理器 使用Ehcache实现
     */
易文鹏 authored
94
95
96
97
98
99
100
101
102
103
104
105
    //@Bean
    //public EhCacheManager getEhCacheManager() {
    //    net.sf.ehcache.CacheManager cacheManager = net.sf.ehcache.CacheManager.getCacheManager("huaheng");
    //    EhCacheManager em = new EhCacheManager();
    //    if (StringUtils.isNull(cacheManager)) {
    //        em.setCacheManagerConfigFile("classpath:ehcache/ehcache-shiro.xml");
    //        return em;
    //    } else {
    //        em.setCacheManager(cacheManager);
    //        return em;
    //    }
    //}
tangying authored
106
107
108
109
110

    /**
     * 自定义Realm
     */
    @Bean
易文鹏 authored
111
    public UserRealm userRealm() {
tangying authored
112
        UserRealm userRealm = new UserRealm();
易文鹏 authored
113
114
        userRealm.setCacheManager(
                redisEnabled ? cacheManagerConfig.getRedisCacheManager() : cacheManagerConfig.getEhCacheManager());
tangying authored
115
116
117
118
119
120
121
        return userRealm;
    }

    /**
     * 自定义sessionDAO会话
     */
    @Bean
mahuandong authored
122
    public OnlineSessionDAO sessionDAO() {
tangying authored
123
124
125
126
127
128
129
130
        OnlineSessionDAO sessionDAO = new OnlineSessionDAO();
        return sessionDAO;
    }

    /**
     * 自定义sessionFactory会话
     */
    @Bean
mahuandong authored
131
    public OnlineSessionFactory sessionFactory() {
tangying authored
132
133
134
135
136
137
138
139
        OnlineSessionFactory sessionFactory = new OnlineSessionFactory();
        return sessionFactory;
    }

    /**
     * 自定义sessionFactory调度器
     */
    @Bean
mahuandong authored
140
    public SpringSessionValidationScheduler sessionValidationScheduler() {
tangying authored
141
142
        SpringSessionValidationScheduler sessionValidationScheduler = new SpringSessionValidationScheduler();
        // 相隔多久检查一次session的有效性,单位毫秒,默认就是10分钟
易文鹏 authored
143
        sessionValidationScheduler.setSessionValidationInterval(validationInterval);
tangying authored
144
145
146
147
148
149
150
151
152
        // 设置会话验证调度器进行会话验证时的会话管理器
        sessionValidationScheduler.setSessionManager(sessionValidationManager());
        return sessionValidationScheduler;
    }

    /**
     * 会话管理器
     */
    @Bean
mahuandong authored
153
    public OnlineWebSessionManager sessionValidationManager() {
tangying authored
154
155
        OnlineWebSessionManager manager = new OnlineWebSessionManager();
        // 加入缓存管理器
易文鹏 authored
156
        manager.setCacheManager(redisEnabled ? cacheManagerConfig.getRedisCacheManager() : cacheManagerConfig.getEhCacheManager());
tangying authored
157
158
159
        // 删除过期的session
        manager.setDeleteInvalidSessions(true);
        // 设置全局session超时时间
易文鹏 authored
160
        manager.setGlobalSessionTimeout(expireTime);
tangying authored
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
        // 去掉 JSESSIONID
        manager.setSessionIdUrlRewritingEnabled(false);
        // 是否定时检查session
        manager.setSessionValidationSchedulerEnabled(true);
        // 自定义SessionDao
        manager.setSessionDAO(sessionDAO());
        // 自定义sessionFactory
        manager.setSessionFactory(sessionFactory());
        return manager;
    }

    /**
     * 会话管理器
     */
    @Bean
mahuandong authored
176
    public OnlineWebSessionManager sessionManager() {
tangying authored
177
178
        OnlineWebSessionManager manager = new OnlineWebSessionManager();
        // 加入缓存管理器
易文鹏 authored
179
        manager.setCacheManager(redisEnabled ? cacheManagerConfig.getRedisCacheManager() : cacheManagerConfig.getEhCacheManager());
tangying authored
180
181
182
        // 删除过期的session
        manager.setDeleteInvalidSessions(true);
        // 设置全局session超时时间
易文鹏 authored
183
        manager.setGlobalSessionTimeout(expireTime);
tangying authored
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
        // 去掉 JSESSIONID
        manager.setSessionIdUrlRewritingEnabled(false);
        // 定义要使用的无效的Session定时调度器
        manager.setSessionValidationScheduler(sessionValidationScheduler());
        // 是否定时检查session
        manager.setSessionValidationSchedulerEnabled(true);
        // 自定义SessionDao
        manager.setSessionDAO(sessionDAO());
        // 自定义sessionFactory
        manager.setSessionFactory(sessionFactory());
        return manager;
    }

    /**
     * 安全管理器
     */
    @Bean
mahuandong authored
201
    public SecurityManager securityManager(UserRealm userRealm) {
tangying authored
202
203
204
205
206
207
        DefaultWebSecurityManager securityManager = new DefaultWebSecurityManager();
        // 设置realm.
        securityManager.setRealm(userRealm);
        // 记住我
        securityManager.setRememberMeManager(rememberMeManager());
        // 注入缓存管理器;
易文鹏 authored
208
209
210
        securityManager.setCacheManager(
                redisEnabled ? cacheManagerConfig.getRedisCacheManager() : cacheManagerConfig.getEhCacheManager());
tangying authored
211
212
213
214
215
216
217
218
        // session管理器
        securityManager.setSessionManager(sessionManager());
        return securityManager;
    }

    /**
     * 退出过滤器
     */
mahuandong authored
219
    public LogoutFilter logoutFilter() {
tangying authored
220
221
222
223
224
        LogoutFilter logoutFilter = new LogoutFilter();
        logoutFilter.setLoginUrl(loginUrl);
        return logoutFilter;
    }
mahuandong authored
225
    public LogoutFilter logoutFilters() {
tangying authored
226
227
228
229
230
231
232
233
234
        LogoutFilter logoutFilter = new LogoutFilter();
        logoutFilter.setLoginUrl(loginUrls);
        return logoutFilter;
    }

    /**
     * Shiro过滤器配置
     */
    @Bean
mahuandong authored
235
    public ShiroFilterFactoryBean shiroFilterFactoryBean(SecurityManager securityManager) {
tangying authored
236
237
238
239
240
241
242
243
244
245
246
247
        ShiroFilterFactoryBean shiroFilterFactoryBean = new ShiroFilterFactoryBean();
        // Shiro的核心安全接口,这个属性是必须的
        shiroFilterFactoryBean.setSecurityManager(securityManager);
        // 身份认证失败,则跳转到登录页面的配置
        shiroFilterFactoryBean.setLoginUrl(loginUrl);
        // 权限认证失败,则跳转到指定页面
        shiroFilterFactoryBean.setUnauthorizedUrl(unauthorizedUrl);
        // Shiro连接约束配置,即过滤链的定义
        LinkedHashMap<String, String> filterChainDefinitionMap = new LinkedHashMap<>();
        // 对静态资源设置匿名访问
        filterChainDefinitionMap.put("/favicon.ico**", "anon");
        filterChainDefinitionMap.put("/huaheng.png**", "anon");
mahuandong authored
248
        filterChainDefinitionMap.put("/logo.png", "anon");
tangying authored
249
250
251
252
        filterChainDefinitionMap.put("/css/**", "anon");
        filterChainDefinitionMap.put("/docs/**", "anon");
        filterChainDefinitionMap.put("/fonts/**", "anon");
        filterChainDefinitionMap.put("/img/**", "anon");
游杰 authored
253
        filterChainDefinitionMap.put("/apk/**", "anon");
游杰 authored
254
        filterChainDefinitionMap.put("/reservation/**", "anon");
tangying authored
255
256
257
258
259
        filterChainDefinitionMap.put("/ajax/**", "anon");
        filterChainDefinitionMap.put("/js/**", "anon");
        filterChainDefinitionMap.put("/huaheng/**", "anon");
        filterChainDefinitionMap.put("/druid/**", "anon");
        filterChainDefinitionMap.put("/captcha/captchaImage**", "anon");
260
        filterChainDefinitionMap.put("/reservation/add", "anon");
tangying authored
261
262
263
264
265
        // 退出 logout地址,shiro去清除session
        filterChainDefinitionMap.put("/logout", "logout");
        filterChainDefinitionMap.put("/admin/logout", "adminlogout");
        // 不需要拦截的访问
//        filterChainDefinitionMap.put("/admin/home", "anon,captchaValidate");
266
        filterChainDefinitionMap.put("/mobile/download/*", "anon");
267
268
269
270
271
        //filterChainDefinitionMap.put("/config/zone/*", "anon");
        //filterChainDefinitionMap.put("/receipt/receiptHeader/listPda", "anon");
        //filterChainDefinitionMap.put("/receipt/receiving/*", "anon");
        //filterChainDefinitionMap.put("/task/taskHeader/*", "anon");
        //filterChainDefinitionMap.put("/mobile/inventory/completeTaskListByWMS", "anon");
272
273
        filterChainDefinitionMap.put("/admin/login", "anon");
        filterChainDefinitionMap.put("/login", "anon");
274
        filterChainDefinitionMap.put("/file/**", "anon");
275
276
        filterChainDefinitionMap.put("/api/login", "anon");
        filterChainDefinitionMap.put("/mobile/login", "anon");
游杰 authored
277
        filterChainDefinitionMap.put("/api/getTokenForMobile", "anon");
278
        filterChainDefinitionMap.put("/getWarehouseByUserCode", "anon");
易文鹏 authored
279
280
281
282
        //积木报表排除
        filterChainDefinitionMap.put("/jmreport/**", "anon");
        filterChainDefinitionMap.put("/**/*.js.map", "anon");
        filterChainDefinitionMap.put("/**/*.css.map", "anon");
283
284
285
//        filterChainDefinitionMap.put("/websocket", "anon");
//        filterChainDefinitionMap.put("/websocket/*", "anon");
//        filterChainDefinitionMap.put("/user/lincoln/message", "anon");
286
        filterChainDefinitionMap.put("/API/WMS/v2/login", "anon");
mahuandong authored
287
        filterChainDefinitionMap.put("/api/**", "anon");
周峰 authored
288
        filterChainDefinitionMap.put("/endpoint/**", "anon");
游杰 authored
289
        filterChainDefinitionMap.put("/manager/**", "anon");
290
291
        filterChainDefinitionMap.put("/API/WMS/v2/**", "anon");
        filterChainDefinitionMap.put("/mobile/receipt/batch/**", "anon");
292
293

        //todo pda出入库查询,测试后注释
294
295
296
297
298
299
300
301
        //filterChainDefinitionMap.put("/receipt/receiptHeader/listPda", "anon");
        //filterChainDefinitionMap.put("/receipt/receiptDetail/list", "anon");
        //filterChainDefinitionMap.put("/receipt/receiptDetail/pdaList", "anon");
        //filterChainDefinitionMap.put("/task/taskHeader/getTaskByTaskId", "anon");
        //filterChainDefinitionMap.put("/task/taskHeader/getTaskByShipmentCode", "anon");
        //filterChainDefinitionMap.put("/mobile/inventory/completeTaskListByWMS", "anon");
        //filterChainDefinitionMap.put("/receipt/receiving/saveBatch", "anon");
        //filterChainDefinitionMap.put("/config/zone/getAllFlatLocation", "anon");
易文鹏 authored
302
        //filterChainDefinitionMap.put("/mobile/getModules2", "anon");
303
304
tangying authored
305
306
307
        // 系统权限列表
//        filterChainDefinitionMap.putAll(SpringUtils.getBean(IMenuService.class).selectPermsAll());
易文鹏 authored
308
        //websocket
tangying authored
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
        Map<String, Filter> filters = new LinkedHashMap<>();
        filters.put("onlineSession", onlineSessionFilter());
        filters.put("syncOnlineSession", syncOnlineSessionFilter());
        // 注销成功,则跳转到指定页面
        filters.put("logout", logoutFilter());
        filters.put("adminlogout", logoutFilters());
        shiroFilterFactoryBean.setFilters(filters);

        // 所有请求需要认证
        filterChainDefinitionMap.put("/**", "user,onlineSession,syncOnlineSession");
        shiroFilterFactoryBean.setFilterChainDefinitionMap(filterChainDefinitionMap);

        return shiroFilterFactoryBean;
    }

    /**
     * 自定义在线用户处理过滤器
     */
    @Bean
mahuandong authored
328
    public OnlineSessionFilter onlineSessionFilter() {
tangying authored
329
330
331
332
333
334
335
336
337
        OnlineSessionFilter onlineSessionFilter = new OnlineSessionFilter();
        onlineSessionFilter.setLoginUrl(loginUrl);
        return onlineSessionFilter;
    }

    /**
     * 自定义在线用户同步过滤器
     */
    @Bean
mahuandong authored
338
    public SyncOnlineSessionFilter syncOnlineSessionFilter() {
tangying authored
339
340
341
342
343
344
345
        SyncOnlineSessionFilter syncOnlineSessionFilter = new SyncOnlineSessionFilter();
        return syncOnlineSessionFilter;
    }

    /**
     * cookie 属性设置
     */
mahuandong authored
346
    public SimpleCookie rememberMeCookie() {
tangying authored
347
348
349
350
        SimpleCookie cookie = new SimpleCookie("rememberMe");
        cookie.setDomain(domain);
        cookie.setPath(path);
        cookie.setHttpOnly(httpOnly);
易文鹏 authored
351
        cookie.setMaxAge(maxAge * 24 * 60 * 60);
tangying authored
352
353
354
355
356
357
        return cookie;
    }

    /**
     * 记住我
     */
mahuandong authored
358
    public CookieRememberMeManager rememberMeManager() {
tangying authored
359
360
361
362
363
364
365
366
367
368
        CookieRememberMeManager cookieRememberMeManager = new CookieRememberMeManager();
        cookieRememberMeManager.setCookie(rememberMeCookie());
        cookieRememberMeManager.setCipherKey(Base64.decode("fCq+/xW488hMTCD+cmJ3aQ=="));
        return cookieRememberMeManager;
    }

    /**
     * thymeleaf模板引擎和shiro框架的整合
     */
    @Bean
mahuandong authored
369
    public ShiroDialect shiroDialect() {
tangying authored
370
371
372
373
374
375
376
377
        return new ShiroDialect();
    }

    /**
     * 开启Shiro注解通知器
     */
    @Bean
    public AuthorizationAttributeSourceAdvisor authorizationAttributeSourceAdvisor(
mahuandong authored
378
            @Qualifier("securityManager") SecurityManager securityManager) {
tangying authored
379
380
381
382
383
        AuthorizationAttributeSourceAdvisor authorizationAttributeSourceAdvisor = new AuthorizationAttributeSourceAdvisor();
        authorizationAttributeSourceAdvisor.setSecurityManager(securityManager);
        return authorizationAttributeSourceAdvisor;
    }
}