Package org.apache.shiro.subject
Class Subject.Builder
- java.lang.Object
-
- org.apache.shiro.subject.Subject.Builder
-
- Enclosing interface:
- Subject
public static class Subject.Builder extends Object
Builder design pattern implementation for creatingSubjectinstances in a simplified way without requiring knowledge of Shiro's construction techniques. NOTE: This is provided for framework development support only and should typically never be used by application developers.Subjectinstances should generally be acquired by usingSecurityUtils.getSubject()Usage
The simplest usage of this builder is to construct an anonymous, session-lessSubjectinstance:Subject subject = new Subject.
The default, no-argBuilder().buildSubject();Subject.Builder()constructor shown above will use the application's currently accessibleSecurityManagerviaSecurityUtils.. You may also specify the exactgetSecurityManager()SecurityManagerinstance to be used by the additionalSubject.constructor if desired. All other methods may be called before theBuilder(securityManager)buildSubject()method to provide context on how to construct theSubjectinstance. For example, if you have a session id and want to acquire theSubjectthat 'owns' that session (assuming the session exists and is not expired):Subject subject = new Subject.Builder().sessionId(sessionId).buildSubject();
Similarly, if you want aSubjectinstance reflecting a certain identity:PrincipalCollection principals = new SimplePrincipalCollection("username", yourRealmName); Subject subject = new Subject.Builder().principals(principals).build();Note* that the returnedSubjectinstance is not automatically bound to the application (thread) for further use. That is,SecurityUtils.getSubject()will not automatically return the same instance as what is returned by the builder. It is up to the framework developer to bind the builtSubjectfor continued use if desired.- Since:
- 1.0
-
-
Constructor Summary
Constructors Constructor Description Builder()Constructs a newSubject.Builderinstance, using theSecurityManagerinstance available to the calling code as determined by a call toSecurityUtils.getSecurityManager()to build theSubjectinstance.Builder(SecurityManager securityManager)Constructs a newSubject.Builderinstance which will use the specifiedSecurityManagerwhen building theSubjectinstance.
-
Method Summary
All Methods Instance Methods Concrete Methods Modifier and Type Method Description Subject.Builderauthenticated(boolean authenticated)Ensures theSubjectbeing built will be consideredauthenticated.SubjectbuildSubject()Creates and returns a newSubjectinstance reflecting the cumulative state acquired by the other methods in this class.Subject.BuildercontextAttribute(String attributeKey, Object attributeValue)Allows custom attributes to be added to the underlying contextMapused to construct theSubjectinstance.protected SubjectContextgetSubjectContext()Returns the backing context used to build theSubjectinstance, available to subclasses since thecontextclass attribute is marked asprivate.Subject.Builderhost(String host)Ensures theSubjectbeing built will reflect the specified host name or IP as its originating location.protected SubjectContextnewSubjectContextInstance()Creates a newSubjectContextinstance to be used to populate with subject contextual data that will then be sent to theSecurityManagerto create a newSubjectinstance.Subject.Builderprincipals(PrincipalCollection principals)Ensures theSubjectbeing built will reflect the specified principals (aka identity).Subject.Buildersession(Session session)Ensures theSubjectbeing built will use the specifiedSessioninstance.Subject.BuildersessionCreationEnabled(boolean enabled)Configures whether or not the created Subject instance can create a newSessionif one does not already exist.Subject.BuildersessionId(Serializable sessionId)
-
-
-
Constructor Detail
-
Builder
public Builder()
Constructs a newSubject.Builderinstance, using theSecurityManagerinstance available to the calling code as determined by a call toSecurityUtils.getSecurityManager()to build theSubjectinstance.
-
Builder
public Builder(SecurityManager securityManager)
Constructs a newSubject.Builderinstance which will use the specifiedSecurityManagerwhen building theSubjectinstance.- Parameters:
securityManager- theSecurityManagerto use when building theSubjectinstance.
-
-
Method Detail
-
newSubjectContextInstance
protected SubjectContext newSubjectContextInstance()
Creates a newSubjectContextinstance to be used to populate with subject contextual data that will then be sent to theSecurityManagerto create a newSubjectinstance.- Returns:
- a new
SubjectContextinstance
-
getSubjectContext
protected SubjectContext getSubjectContext()
Returns the backing context used to build theSubjectinstance, available to subclasses since thecontextclass attribute is marked asprivate.- Returns:
- the backing context used to build the
Subjectinstance, available to subclasses.
-
sessionId
public Subject.Builder sessionId(Serializable sessionId)
Enables building aSubjectinstance that owns theSessionwith the specifiedsessionId. Usually when specifying asessionId, no otherBuildermethods would be specified because everything else (principals, inet address, etc) can usually be reconstructed based on the referenced session alone. In other words, this is almost always sufficient:new Subject.Builder().sessionId(sessionId).buildSubject();
Although simple in concept, this method provides very powerful functionality previously absent in almost all Java environments: The ability to reference aSubjectand their server-side session across clients of different mediums such as web applications, Java applets, standalone C# clients over XML-RPC and/or SOAP, and many others. This is a huge benefit in heterogeneous enterprise applications. To maintain session integrity across client mediums, thesessionIdmust be transmitted to all client mediums securely (e.g. over SSL) to prevent man-in-the-middle attacks. This is nothing new - all web applications are susceptible to the same problem when transmittingCookies or when using URL rewriting. As long as thesessionIdis transmitted securely, session integrity can be maintained.- Parameters:
sessionId- the id of the session that backs the desired Subject being acquired.- Returns:
- this
Builderinstance for method chaining.
-
host
public Subject.Builder host(String host)
Ensures theSubjectbeing built will reflect the specified host name or IP as its originating location.- Parameters:
host- the host name or IP address to use as theSubject's originating location.- Returns:
- this
Builderinstance for method chaining.
-
session
public Subject.Builder session(Session session)
Ensures theSubjectbeing built will use the specifiedSessioninstance. Note that it is more common to use thesessionIdbuilder method rather than having to construct aSessioninstance for this method.- Parameters:
session- the session to use as theSubject'sSession- Returns:
- this
Builderinstance for method chaining.
-
principals
public Subject.Builder principals(PrincipalCollection principals)
Ensures theSubjectbeing built will reflect the specified principals (aka identity). For example, if your application's unique identifier for users is aStringusername, and you wanted to create aSubjectinstance that reflected a user whose username is 'jsmith', and you knew the Realm that could acquirejsmith's principals based on the username was named "myRealm", you might create the 'jsmithSubjectinstance this way:PrincipalCollection identity = new
Similarly, if your application's unique identifier for users is aSimplePrincipalCollection("jsmith", "myRealm"); Subject jsmith = new Subject.Builder().principals(identity).buildSubject();longvalue (such as might be used as a primary key in a relational database) and you were using aJDBCRealmnamed, (unimaginatively) "jdbcRealm", you might create the Subject instance this way:long userId = //get user ID from somewhere PrincipalCollection userIdentity = new
SimplePrincipalCollection(userId, "jdbcRealm"); Subject user = new Subject.Builder().principals(identity).buildSubject();- Parameters:
principals- the principals to use as theSubject's identity.- Returns:
- this
Builderinstance for method chaining.
-
sessionCreationEnabled
public Subject.Builder sessionCreationEnabled(boolean enabled)
Configures whether or not the created Subject instance can create a newSessionif one does not already exist. If set tofalse, any application calls tosubject.getSession()orsubject.getSession(true))will result in a SessionException. This setting istrueby default, as most applications find value in sessions.- Parameters:
enabled- whether or not the created Subject instance can create a newSessionif one does not already exist.- Returns:
- this
Builderinstance for method chaining. - Since:
- 1.2
-
authenticated
public Subject.Builder authenticated(boolean authenticated)
Ensures theSubjectbeing built will be consideredauthenticated. Per theisAuthenticated()JavaDoc, be careful when specifyingtrue- you should know what you are doing and have a good reason for ignoring Shiro's default authentication state mechanisms.- Parameters:
authenticated- whether or not the builtSubjectwill be considered authenticated.- Returns:
- this
Builderinstance for method chaining. - See Also:
Subject.isAuthenticated()
-
contextAttribute
public Subject.Builder contextAttribute(String attributeKey, Object attributeValue)
Allows custom attributes to be added to the underlying contextMapused to construct theSubjectinstance. Anullkey throws anIllegalArgumentException. Anullvalue effectively removes any previously stored attribute under the given key from the context map. *NOTE*: This method is only useful when configuring Shiro with a customSubjectFactoryimplementation. This method allows end-users to append additional data to the context map which theSubjectFactoryimplementation can use when building custom Subject instances. As such, this method is only useful when a customSubjectFactoryimplementation has been configured.- Parameters:
attributeKey- the key under which the corresponding value will be stored in the contextMap.attributeValue- the value to store in the context map under the specifiedattributeKey.- Returns:
- this
Builderinstance for method chaining. - Throws:
IllegalArgumentException- if theattributeKeyisnull.- See Also:
SubjectFactory.createSubject(SubjectContext)
-
buildSubject
public Subject buildSubject()
Creates and returns a newSubjectinstance reflecting the cumulative state acquired by the other methods in this class. ThisBuilderinstance will still retain the underlying state after this method is called - it will not clear it; repeated calls to this method will return multipleSubjectinstances, all reflecting the exact same state. If a new (different)Subjectis to be constructed, a newBuilderinstance must be created. Note that the returnedSubjectinstance is not automatically bound to the application (thread) for further use. That is,SecurityUtils.getSubject()will not automatically return the same instance as what is returned by the builder. It is up to the framework developer to bind the returnedSubjectfor continued use if desired.- Returns:
- a new
Subjectinstance reflecting the cumulative state acquired by the other methods in this class.
-
-