Web support module for Apache Shiro providing servlet filters, session management, and web-specific authentication and authorization features
npx @tessl/cli install tessl/maven-org-apache-shiro--shiro-web@1.13.00
# Apache Shiro Web
1
2
Apache Shiro Web is a comprehensive security framework module that extends Shiro's core security capabilities with servlet-based web application support. It provides authentication and authorization through configurable filter chains, multiple session management strategies, JSP tag libraries for view-layer security, and seamless integration with Java web applications.
3
4
## Package Information
5
6
- **Package Name**: org.apache.shiro:shiro-web
7
- **Package Type**: Maven
8
- **Language**: Java
9
- **Installation**: Add to Maven `pom.xml`:
10
11
```xml
12
<dependency>
13
<groupId>org.apache.shiro</groupId>
14
<artifactId>shiro-web</artifactId>
15
<version>1.13.0</version>
16
</dependency>
17
```
18
19
Gradle:
20
21
```gradle
22
implementation 'org.apache.shiro:shiro-web:1.13.0'
23
```
24
25
## Core Imports
26
27
```java
28
// Primary servlet filter for web applications
29
import org.apache.shiro.web.servlet.ShiroFilter;
30
31
// Environment setup and configuration
32
import org.apache.shiro.web.env.EnvironmentLoaderListener;
33
import org.apache.shiro.web.env.WebEnvironment;
34
35
// Security manager for web applications
36
import org.apache.shiro.web.mgt.DefaultWebSecurityManager;
37
import org.apache.shiro.web.mgt.WebSecurityManager;
38
39
// Filter management and configuration
40
import org.apache.shiro.web.filter.mgt.FilterChainManager;
41
import org.apache.shiro.web.filter.mgt.DefaultFilterChainManager;
42
43
// Web subject for request/response access
44
import org.apache.shiro.web.subject.WebSubject;
45
```
46
47
## Basic Usage
48
49
### Servlet Filter Configuration
50
51
```java
52
// web.xml configuration
53
/*
54
<listener>
55
<listener-class>
56
org.apache.shiro.web.env.EnvironmentLoaderListener
57
</listener-class>
58
</listener>
59
60
<filter>
61
<filter-name>ShiroFilter</filter-name>
62
<filter-class>org.apache.shiro.web.servlet.ShiroFilter</filter-class>
63
</filter>
64
65
<filter-mapping>
66
<filter-name>ShiroFilter</filter-name>
67
<url-pattern>/*</url-pattern>
68
<dispatcher>REQUEST</dispatcher>
69
<dispatcher>FORWARD</dispatcher>
70
<dispatcher>INCLUDE</dispatcher>
71
<dispatcher>ERROR</dispatcher>
72
</filter-mapping>
73
*/
74
75
// Programmatic filter configuration
76
import org.apache.shiro.web.servlet.AbstractShiroFilter;
77
import org.apache.shiro.web.mgt.DefaultWebSecurityManager;
78
import org.apache.shiro.web.filter.mgt.DefaultFilterChainManager;
79
80
public class ShiroConfig {
81
public AbstractShiroFilter createShiroFilter() {
82
DefaultWebSecurityManager securityManager = new DefaultWebSecurityManager();
83
84
AbstractShiroFilter shiroFilter = new AbstractShiroFilter() {};
85
shiroFilter.setSecurityManager(securityManager);
86
87
DefaultFilterChainManager filterChainManager = new DefaultFilterChainManager();
88
filterChainManager.createChain("/login", "authc");
89
filterChainManager.createChain("/admin/**", "authc, roles[admin]");
90
filterChainManager.createChain("/user/**", "authc");
91
filterChainManager.createChain("/**", "anon");
92
93
return shiroFilter;
94
}
95
}
96
```
97
98
### Working with Web Subjects
99
100
```java
101
import org.apache.shiro.web.subject.WebSubject;
102
import org.apache.shiro.web.util.WebUtils;
103
import javax.servlet.http.HttpServletRequest;
104
import javax.servlet.http.HttpServletResponse;
105
106
public void handleRequest(HttpServletRequest request, HttpServletResponse response) {
107
WebSubject currentUser = (WebSubject) SecurityUtils.getSubject();
108
109
// Access servlet request/response through WebSubject
110
HttpServletRequest subjectRequest = currentUser.getServletRequest();
111
HttpServletResponse subjectResponse = currentUser.getServletResponse();
112
113
// Check authentication and authorization
114
if (currentUser.isAuthenticated()) {
115
if (currentUser.hasRole("admin")) {
116
// Admin functionality
117
}
118
} else {
119
// Redirect to login
120
WebUtils.issueRedirect(request, response, "/login");
121
}
122
}
123
```
124
125
## Architecture
126
127
Apache Shiro Web follows a layered architecture designed around servlet filters:
128
129
- **Environment Layer**: `WebEnvironment` provides centralized configuration and component management
130
- **Filter Layer**: Configurable chains of servlet filters handle authentication, authorization, and session management
131
- **Security Manager**: `WebSecurityManager` coordinates web-specific security operations
132
- **Subject Layer**: `WebSubject` provides request/response-aware security context
133
- **Session Management**: Multiple strategies from servlet container sessions to Shiro native sessions
134
- **Tag Library**: JSP tags for view-layer security integration
135
136
This design enables flexible integration with any servlet-based web application while maintaining Shiro's powerful security features.
137
138
## Capabilities
139
140
### Environment and Configuration
141
142
Core components for initializing and configuring Shiro in web applications, including environment setup, filter configuration factories, and servlet integration.
143
144
```java { .api }
145
// Primary environment interface
146
interface WebEnvironment extends Environment {
147
FilterChainResolver getFilterChainResolver();
148
ServletContext getServletContext();
149
WebSecurityManager getWebSecurityManager();
150
}
151
152
// Environment initialization
153
class EnvironmentLoaderListener implements ServletContextListener {
154
public void contextInitialized(ServletContextEvent event);
155
public void contextDestroyed(ServletContextEvent event);
156
}
157
158
// Configuration factories
159
class IniFilterChainResolverFactory extends IniFactorySupport<FilterChainResolver> {
160
public FilterChainResolver createInstance(Ini ini);
161
}
162
```
163
164
[Environment and Configuration](./environment-config.md)
165
166
### Servlet Filters and Integration
167
168
Comprehensive servlet filter system providing authentication, authorization, and request processing through configurable filter chains and servlet integration components.
169
170
```java { .api }
171
// Primary servlet filter
172
class ShiroFilter extends AbstractShiroFilter {
173
public void init() throws ServletException;
174
}
175
176
// Base filter functionality
177
abstract class AbstractShiroFilter extends OncePerRequestFilter {
178
public WebSecurityManager getSecurityManager();
179
public void setSecurityManager(WebSecurityManager securityManager);
180
public FilterChainResolver getFilterChainResolver();
181
public void setFilterChainResolver(FilterChainResolver resolver);
182
}
183
184
// Filter templates
185
abstract class AccessControlFilter extends PathMatchingFilter {
186
public String getLoginUrl();
187
public void setLoginUrl(String loginUrl);
188
protected abstract boolean isAccessAllowed(ServletRequest request, ServletResponse response, Object mappedValue);
189
protected abstract boolean onAccessDenied(ServletRequest request, ServletResponse response);
190
}
191
```
192
193
[Servlet Filters and Integration](./servlet-filters.md)
194
195
### Authentication Filters
196
197
Specialized filters for various authentication mechanisms including form-based, HTTP Basic/Bearer, anonymous access, and logout handling.
198
199
```java { .api }
200
// Form authentication
201
class FormAuthenticationFilter extends AuthenticatingFilter {
202
public String getUsernameParam();
203
public void setUsernameParam(String usernameParam);
204
public String getPasswordParam();
205
public void setPasswordParam(String passwordParam);
206
public boolean isRememberMe(ServletRequest request);
207
}
208
209
// HTTP Basic authentication
210
class BasicHttpAuthenticationFilter extends HttpAuthenticationFilter {
211
protected String[] getPrincipalsAndCredentials(String authorizationHeader, ServletRequest request);
212
}
213
214
// Logout handling
215
class LogoutFilter extends AdviceFilter {
216
public String getRedirectUrl();
217
public void setRedirectUrl(String redirectUrl);
218
}
219
```
220
221
[Authentication Filters](./authentication-filters.md)
222
223
### Authorization Filters
224
225
Access control filters for role-based and permission-based authorization, including SSL enforcement, host/port restrictions, and HTTP method permissions.
226
227
```java { .api }
228
// Permission-based authorization
229
class PermissionsAuthorizationFilter extends AuthorizationFilter {
230
protected boolean isAccessAllowed(ServletRequest request, ServletResponse response, Object mappedValue);
231
}
232
233
// Role-based authorization
234
class RolesAuthorizationFilter extends AuthorizationFilter {
235
protected boolean isAccessAllowed(ServletRequest request, ServletResponse response, Object mappedValue);
236
}
237
238
// SSL enforcement
239
class SslFilter extends PortFilter {
240
public int getPort();
241
public void setPort(int port);
242
}
243
244
// HTTP method permissions
245
class HttpMethodPermissionFilter extends PermissionsAuthorizationFilter {
246
protected String getHttpMethodAction(ServletRequest request);
247
}
248
```
249
250
[Authorization Filters](./authorization-filters.md)
251
252
### Filter Chain Management
253
254
Components for managing and resolving filter chains, including path-based chain resolution, filter registration, and configuration management.
255
256
```java { .api }
257
// Filter chain resolution
258
interface FilterChainResolver {
259
FilterChain getChain(ServletRequest request, ServletResponse response, FilterChain originalChain);
260
}
261
262
// Filter chain management
263
interface FilterChainManager {
264
Map<String, NamedFilterList> getFilterChains();
265
NamedFilterList getChain(String chainName);
266
void createChain(String chainName, String chainDefinition);
267
void addToChain(String chainName, String filterName);
268
}
269
270
// Default implementations
271
class PathMatchingFilterChainResolver implements FilterChainResolver;
272
class DefaultFilterChainManager implements FilterChainManager;
273
274
// Predefined filters
275
enum DefaultFilter {
276
anon(AnonymousFilter.class),
277
authc(FormAuthenticationFilter.class),
278
authcBasic(BasicHttpAuthenticationFilter.class),
279
authcBearer(BearerHttpAuthenticationFilter.class),
280
logout(LogoutFilter.class),
281
noSessionCreation(NoSessionCreationFilter.class),
282
perms(PermissionsAuthorizationFilter.class),
283
port(PortFilter.class),
284
rest(HttpMethodPermissionFilter.class),
285
roles(RolesAuthorizationFilter.class),
286
ssl(SslFilter.class),
287
user(UserFilter.class),
288
invalidRequest(InvalidRequestFilter.class);
289
290
public Filter newInstance();
291
public Class<? extends Filter> getFilterClass();
292
public static Map<String, Filter> createInstanceMap(FilterConfig config);
293
}
294
```
295
296
[Filter Chain Management](./filter-chain-management.md)
297
298
### Web Security Management
299
300
Web-specific security manager implementations, remember-me functionality, subject factories, and session storage evaluation for servlet environments.
301
302
```java { .api }
303
// Web security manager
304
interface WebSecurityManager extends SecurityManager {
305
boolean isHttpSessionMode();
306
}
307
308
class DefaultWebSecurityManager extends DefaultSecurityManager implements WebSecurityManager {
309
public DefaultWebSecurityManager();
310
public DefaultWebSecurityManager(Realm singleRealm);
311
public DefaultWebSecurityManager(Collection<Realm> realms);
312
}
313
314
// Cookie-based remember me
315
class CookieRememberMeManager extends AbstractRememberMeManager {
316
public Cookie getCookie();
317
public void setCookie(Cookie cookie);
318
public String getCipherKey();
319
public void setCipherKey(String cipherKey);
320
}
321
322
// Web subject factory
323
class DefaultWebSubjectFactory extends DefaultSubjectFactory {
324
public Subject createSubject(SubjectContext context);
325
}
326
```
327
328
[Web Security Management](./web-security-management.md)
329
330
### Session Management
331
332
Web session management including servlet container session delegation, native Shiro session management, cookie-based session IDs, and session context management.
333
334
```java { .api }
335
// Web session manager interface
336
interface WebSessionManager extends SessionManager {
337
boolean isServletContainerSessions();
338
}
339
340
// Default web session manager
341
class DefaultWebSessionManager extends DefaultSessionManager implements WebSessionManager {
342
public boolean isServletContainerSessions();
343
public Cookie getSessionIdCookie();
344
public void setSessionIdCookie(Cookie cookie);
345
public boolean isSessionIdUrlRewritingEnabled();
346
public void setSessionIdUrlRewritingEnabled(boolean sessionIdUrlRewritingEnabled);
347
}
348
349
// Servlet container session delegation
350
class ServletContainerSessionManager implements WebSessionManager {
351
public Session start(SessionContext context);
352
public Session getSession(SessionKey key);
353
}
354
355
// Session contexts and keys
356
interface WebSessionContext extends SessionContext, RequestPairSource;
357
class DefaultWebSessionContext extends DefaultSessionContext implements WebSessionContext;
358
class WebSessionKey extends DefaultSessionKey implements RequestPairSource;
359
```
360
361
[Session Management](./session-management.md)
362
363
### Web Subjects
364
365
Web-aware subject implementations providing access to servlet requests and responses, with builder patterns for subject creation and context management.
366
367
```java { .api }
368
// Web subject interface
369
interface WebSubject extends Subject, RequestPairSource {
370
ServletRequest getServletRequest();
371
ServletResponse getServletResponse();
372
373
// Builder for creating WebSubject instances
374
class Builder extends Subject.Builder {
375
public Builder(SecurityManager securityManager, ServletRequest request, ServletResponse response);
376
public Builder sessionId(Serializable sessionId);
377
public Builder host(String host);
378
public Builder session(Session session);
379
public WebSubject buildWebSubject();
380
}
381
}
382
383
// Context for web subject creation
384
interface WebSubjectContext extends SubjectContext, RequestPairSource;
385
class DefaultWebSubjectContext extends DefaultSubjectContext implements WebSubjectContext;
386
387
// Web subject implementation
388
class WebDelegatingSubject extends DelegatingSubject implements WebSubject {
389
public ServletRequest getServletRequest();
390
public ServletResponse getServletResponse();
391
}
392
```
393
394
[Web Subjects](./web-subjects.md)
395
396
### JSP Tag Library
397
398
Complete JSP tag library for view-layer security including authentication status tags, role and permission checks, and principal display tags.
399
400
```java { .api }
401
// Base tag class
402
abstract class SecureTag extends TagSupport {
403
protected Subject getSubject();
404
protected abstract int onDoStartTag() throws JspException;
405
}
406
407
// Authentication tags
408
class AuthenticatedTag extends SecureTag; // Shows content if authenticated
409
class NotAuthenticatedTag extends SecureTag; // Shows content if not authenticated
410
class UserTag extends SecureTag; // Shows content if user known
411
class GuestTag extends SecureTag; // Shows content if guest
412
413
// Authorization tags
414
class HasRoleTag extends RoleTag; // Shows content if has role
415
class LacksRoleTag extends RoleTag; // Shows content if lacks role
416
class HasAnyRolesTag extends RoleTag; // Shows content if has any role
417
class HasPermissionTag extends PermissionTag; // Shows content if has permission
418
class LacksPermissionTag extends PermissionTag; // Shows content if lacks permission
419
420
// Utility tags
421
class PrincipalTag extends SecureTag; // Displays principal
422
```
423
424
[JSP Tag Library](./jsp-tag-library.md)
425
426
### Web Utilities
427
428
Utility classes for common web operations including request handling, path resolution, redirect management, request saving/restoration, and servlet request/response type conversion.
429
430
```java { .api }
431
class WebUtils {
432
// Path and context utilities
433
public static String getPathWithinApplication(HttpServletRequest request);
434
public static String getContextPath(HttpServletRequest request);
435
436
// Environment access
437
public static WebEnvironment getWebEnvironment(ServletContext servletContext);
438
439
// Redirect utilities
440
public static void issueRedirect(ServletRequest request, ServletResponse response, String url) throws IOException;
441
public static void issueRedirect(ServletRequest request, ServletResponse response, String url, Map<String, ?> queryParams, boolean contextRelative, boolean http10Compatible) throws IOException;
442
443
// Request saving and restoration
444
public static void saveRequest(ServletRequest request);
445
public static SavedRequest getSavedRequest(ServletRequest request);
446
public static SavedRequest getAndClearSavedRequest(ServletRequest request);
447
public static void redirectToSavedRequest(ServletRequest request, ServletResponse response, String fallbackUrl) throws IOException;
448
449
// Type conversion utilities
450
public static HttpServletRequest toHttp(ServletRequest request);
451
public static HttpServletResponse toHttp(ServletResponse response);
452
}
453
454
// Saved request representation
455
class SavedRequest implements Serializable {
456
public String getMethod();
457
public String getQueryString();
458
public String getRequestURI();
459
public String getRequestURL();
460
public Map<String, String[]> getParameterMap();
461
}
462
```
463
464
[Web Utilities](./web-utilities.md)