1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19 package org.apache.shiro.samples.guice;
20
21 import com.google.inject.Provides;
22 import com.google.inject.binder.AnnotatedBindingBuilder;
23 import com.google.inject.name.Names;
24 import org.apache.shiro.lang.codec.Base64;
25 import org.apache.shiro.config.ConfigurationException;
26 import org.apache.shiro.config.Ini;
27 import org.apache.shiro.guice.web.ShiroWebModule;
28 import org.apache.shiro.realm.text.IniRealm;
29 import org.apache.shiro.web.mgt.CookieRememberMeManager;
30 import org.apache.shiro.web.mgt.DefaultWebSecurityManager;
31 import org.apache.shiro.web.mgt.WebSecurityManager;
32
33 import javax.inject.Singleton;
34 import javax.servlet.ServletContext;
35 import java.net.MalformedURLException;
36 import java.net.URL;
37
38 public class SampleShiroServletModule extends ShiroWebModule {
39 private final ServletContext servletContext;
40
41 public SampleShiroServletModule(ServletContext servletContext) {
42 super(servletContext);
43
44 this.servletContext = servletContext;
45 }
46
47 @Override
48 protected void configureShiroWeb() {
49 bindConstant().annotatedWith(Names.named("shiro.loginUrl")).to("/login.jsp");
50 try {
51 this.bindRealm().toConstructor(IniRealm.class.getConstructor(Ini.class));
52 } catch (NoSuchMethodException e) {
53 addError("Could not locate proper constructor for IniRealm.", e);
54 }
55
56 this.addFilterChain("/login.jsp", AUTHC);
57 this.addFilterChain("/logout", LOGOUT);
58 this.addFilterChain("/account/**", AUTHC);
59
60 this.addFilterChain("/remoting/**",
61 filterConfig(AUTHC),
62 filterConfig(ROLES, "b2bClient"),
63 filterConfig(PERMS, "remote:invoke:lan,wan"));
64 }
65
66 @Provides
67 @Singleton
68 Ini loadShiroIni() throws MalformedURLException {
69 URL iniUrl = servletContext.getResource("/WEB-INF/shiro.ini");
70 return Ini.fromResourcePath("url:" + iniUrl.toExternalForm());
71 }
72
73 @Override
74 protected void bindWebSecurityManager(AnnotatedBindingBuilder<? super WebSecurityManager> bind) {
75 try {
76 String cipherKey = loadShiroIni().getSectionProperty("main", "securityManager.rememberMeManager.cipherKey");
77
78 DefaultWebSecurityManager securityManager = new DefaultWebSecurityManager();
79 CookieRememberMeManager rememberMeManager = new CookieRememberMeManager();
80 rememberMeManager.setCipherKey(Base64.decode(cipherKey));
81 securityManager.setRememberMeManager(rememberMeManager);
82 bind.toInstance(securityManager);
83 } catch (MalformedURLException e) {
84
85
86 throw new ConfigurationException("securityManager.rememberMeManager.cipherKey must be set in shiro.ini.");
87 }
88
89
90 }
91 }