or run

npx @tessl/cli init
Log in

Version

Tile

Overview

Evals

Files

Files

docs

authentication.mdauthorization.mdindex.mdrealms.mdsecurity-annotations.mdsecurity-manager.mdsession-management.mdsubject-operations.mdutilities.md

subject-operations.mddocs/

0

# Subject Operations

1

2

The Subject interface represents the security-specific view of the current user and serves as the primary interface for all security operations in Apache Shiro. It provides methods for authentication, authorization, session management, and secure execution of code blocks.

3

4

## Capabilities

5

6

### Authentication Operations

7

8

Methods for logging in, checking authentication status, and logging out users.

9

10

```java { .api }

11

/**

12

* Performs a login attempt for this Subject/user with the given authentication token.

13

* @param token the authentication token encapsulating the user's login credentials

14

* @throws AuthenticationException if the authentication attempt fails

15

*/

16

void login(AuthenticationToken token) throws AuthenticationException;

17

18

/**

19

* Returns true if this Subject has successfully completed authentication.

20

* @return true if authenticated, false otherwise

21

*/

22

boolean isAuthenticated();

23

24

/**

25

* Returns true if this Subject is remembered from a successful authentication during a previous session.

26

* @return true if remembered, false otherwise

27

*/

28

boolean isRemembered();

29

30

/**

31

* Logs out this Subject and invalidates and/or removes any associated entities.

32

*/

33

void logout();

34

```

35

36

**Usage Example:**

37

38

```java

39

Subject currentUser = SecurityUtils.getSubject();

40

UsernamePasswordToken token = new UsernamePasswordToken("username", "password");

41

token.setRememberMe(true);

42

43

try {

44

currentUser.login(token);

45

System.out.println("Login successful");

46

} catch (UnknownAccountException uae) {

47

System.out.println("Unknown account");

48

} catch (IncorrectCredentialsException ice) {

49

System.out.println("Incorrect credentials");

50

} catch (LockedAccountException lae) {

51

System.out.println("Account locked");

52

} catch (AuthenticationException ae) {

53

System.out.println("Authentication failed");

54

}

55

```

56

57

### Authorization Operations

58

59

Methods for checking roles and permissions, with both boolean return and exception-throwing variants.

60

61

```java { .api }

62

/**

63

* Returns true if this Subject has the specified role, false otherwise.

64

* @param roleIdentifier the application-specific role identifier (usually a role id or role name)

65

* @return true if this Subject has the specified role, false otherwise

66

*/

67

boolean hasRole(String roleIdentifier);

68

69

/**

70

* Checks if this Subject implies the given roles and returns a boolean array.

71

* @param roleIdentifiers the application-specific role identifiers to check

72

* @return a boolean array where indices correspond to the index of the roles in the given identifiers

73

*/

74

boolean[] hasRoles(List<String> roleIdentifiers);

75

76

/**

77

* Returns true if this Subject has all the specified roles, false otherwise.

78

* @param roleIdentifiers the application-specific role identifiers to check

79

* @return true if this Subject has all the specified roles, false otherwise

80

*/

81

boolean hasAllRoles(Collection<String> roleIdentifiers);

82

83

/**

84

* Asserts this Subject has the specified role by returning quietly if they do or throwing an AuthorizationException if they do not.

85

* @param roleIdentifier the application-specific role identifier

86

* @throws AuthorizationException if this Subject does not have the role

87

*/

88

void checkRole(String roleIdentifier) throws AuthorizationException;

89

90

/**

91

* Same as checkRole(String) but for multiple roles.

92

* @param roleIdentifiers the application-specific role identifiers to check

93

* @throws AuthorizationException if this Subject does not have all specified roles

94

*/

95

void checkRoles(Collection<String> roleIdentifiers) throws AuthorizationException;

96

```

97

98

**Permission checking methods:**

99

100

```java { .api }

101

/**

102

* Returns true if this Subject is permitted to perform an action or access a resource summarized by the specified permission string.

103

* @param permission a permission string

104

* @return true if permitted, false otherwise

105

*/

106

boolean isPermitted(String permission);

107

108

/**

109

* Returns true if this Subject is permitted to perform an action or access a resource summarized by the specified permission.

110

* @param permission a permission object

111

* @return true if permitted, false otherwise

112

*/

113

boolean isPermitted(Permission permission);

114

115

/**

116

* Checks if this Subject implies the given permissions and returns a boolean array.

117

* @param permissions the permissions to check

118

* @return a boolean array where indices correspond to the index of the permissions in the given list

119

*/

120

boolean[] isPermitted(String... permissions);

121

122

/**

123

* Returns true if this Subject is permitted all of the specified permissions, false otherwise.

124

* @param permissions the permissions to check

125

* @return true if permitted all, false otherwise

126

*/

127

boolean isPermittedAll(String... permissions);

128

129

/**

130

* Ensures this Subject implies the specified permission.

131

* @param permission a permission string

132

* @throws AuthorizationException if this Subject does not have the permission

133

*/

134

void checkPermission(String permission) throws AuthorizationException;

135

136

/**

137

* Ensures this Subject implies the specified permission.

138

* @param permission a permission object

139

* @throws AuthorizationException if this Subject does not have the permission

140

*/

141

void checkPermission(Permission permission) throws AuthorizationException;

142

143

/**

144

* Ensures this Subject implies all of the specified permissions.

145

* @param permissions the permissions to check

146

* @throws AuthorizationException if this Subject does not have all permissions

147

*/

148

void checkPermissions(String... permissions) throws AuthorizationException;

149

```

150

151

**Usage Example:**

152

153

```java

154

Subject currentUser = SecurityUtils.getSubject();

155

156

// Role checking

157

if (currentUser.hasRole("admin")) {

158

System.out.println("User is an admin");

159

} else if (currentUser.hasRole("user")) {

160

System.out.println("User is a regular user");

161

}

162

163

// Permission checking

164

if (currentUser.isPermitted("user:create")) {

165

System.out.println("User can create other users");

166

}

167

168

if (currentUser.isPermitted("document:read:123")) {

169

System.out.println("User can read document 123");

170

}

171

172

// Exception-throwing authorization

173

try {

174

currentUser.checkPermission("admin:delete");

175

// User has permission, continue with operation

176

performAdminDeletion();

177

} catch (AuthorizationException e) {

178

System.out.println("User not authorized for admin deletion");

179

}

180

```

181

182

### Session Management

183

184

Methods for working with the Subject's session.

185

186

```java { .api }

187

/**

188

* Returns the application Session associated with this Subject.

189

* @return the application Session associated with this Subject

190

*/

191

Session getSession();

192

193

/**

194

* Returns the application Session associated with this Subject.

195

* @param create boolean argument determining if a session should be created if one does not exist

196

* @return the application Session associated with this Subject or null if create is false and no session exists

197

*/

198

Session getSession(boolean create);

199

```

200

201

**Usage Example:**

202

203

```java

204

Subject currentUser = SecurityUtils.getSubject();

205

Session session = currentUser.getSession();

206

207

// Store data in session

208

session.setAttribute("userPreferences", userPrefs);

209

210

// Retrieve data from session

211

Object preferences = session.getAttribute("userPreferences");

212

213

// Session management

214

session.touch(); // Update last access time

215

session.setTimeout(30 * 60 * 1000); // 30 minutes timeout

216

```

217

218

### Principal Access

219

220

Methods for accessing the Subject's identity information.

221

222

```java { .api }

223

/**

224

* Returns this Subject's application-wide uniquely identifying principal, or null if this Subject is anonymous.

225

* @return this Subject's application-wide uniquely identifying principal, or null if this Subject is anonymous

226

*/

227

Object getPrincipal();

228

229

/**

230

* Returns this Subject's principals (identifying attributes) in the form of a PrincipalCollection.

231

* @return this Subject's identifying attributes, or an empty PrincipalCollection if this Subject is anonymous

232

*/

233

PrincipalCollection getPrincipals();

234

```

235

236

### Secure Execution

237

238

Methods for executing code blocks with the Subject's security context automatically applied.

239

240

```java { .api }

241

/**

242

* Executes a Callable with this Subject instance as the calling thread's Subject.

243

* @param callable the callable to execute as this Subject

244

* @return the result returned by the callable

245

* @throws ExecutionException if the callable throws an exception

246

*/

247

<V> V execute(Callable<V> callable) throws ExecutionException;

248

249

/**

250

* Executes a Runnable with this Subject instance as the calling thread's Subject.

251

* @param runnable the runnable to execute as this Subject

252

*/

253

void execute(Runnable runnable);

254

255

/**

256

* Associates the specified Callable with this Subject instance and then executes it on the currently running thread.

257

* @param callable the callable to associate with this subject and then execute

258

* @return the result of the callable execution

259

* @throws ExecutionException if the callable execution throws an exception

260

*/

261

<V> V associateWith(Callable<V> callable) throws ExecutionException;

262

263

/**

264

* Associates the specified Runnable with this Subject instance and then executes it on the currently running thread.

265

* @param runnable the runnable to associate with this subject and then execute

266

*/

267

void associateWith(Runnable runnable);

268

```

269

270

**Usage Example:**

271

272

```java

273

Subject adminUser = SecurityUtils.getSubject();

274

275

// Execute code block with admin context

276

String result = adminUser.execute(new Callable<String>() {

277

public String call() throws Exception {

278

// This code runs with adminUser's security context

279

performSecureOperation();

280

return "Operation completed";

281

}

282

});

283

284

// Using lambda (Java 8+)

285

String result2 = adminUser.execute(() -> {

286

return performAnotherSecureOperation();

287

});

288

```

289

290

## Types

291

292

```java { .api }

293

public interface PrincipalCollection extends Iterable, Serializable {

294

Object getPrimaryPrincipal();

295

<T> T oneByType(Class<T> type);

296

<T> Collection<T> byType(Class<T> type);

297

List asList();

298

Set asSet();

299

boolean isEmpty();

300

}

301

302

public class ExecutionException extends Exception {

303

public ExecutionException(Throwable cause);

304

public ExecutionException(String message, Throwable cause);

305

}

306

```