Start line:  
End line:  

Snippet Preview

Snippet HTML Code

Stack Overflow Questions
  /*
   * Licensed to the Apache Software Foundation (ASF) under one
   * or more contributor license agreements.  See the NOTICE file
   * distributed with this work for additional information
   * regarding copyright ownership.  The ASF licenses this file
   * to you under the Apache License, Version 2.0 (the
   * "License"); you may not use this file except in compliance
   * with the License.  You may obtain a copy of the License at
   *
  *     http://www.apache.org/licenses/LICENSE-2.0
  *
  * Unless required by applicable law or agreed to in writing,
  * software distributed under the License is distributed on an
  * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
  * KIND, either express or implied.  See the License for the
  * specific language governing permissions and limitations
  * under the License.
  */
 package org.apache.shiro.cas;
 
 
 import java.util.List;
 import java.util.Map;

This realm implementation acts as a CAS client to a CAS server for authentication and basic authorization.

This realm functions by inspecting a submitted CasToken (which essentially wraps a CAS service ticket) and validates it against the CAS server using a configured CAS TicketValidator.

The validationProtocol is CAS by default, which indicates that a a Cas20ServiceTicketValidator will be used for ticket validation. You can alternatively set or Saml11TicketValidator of CAS client. It is based on AuthorizingRealm for both authentication and authorization. User id and attributes are retrieved from the CAS service ticket validation response during authentication phase. Roles and permissions are computed during authorization phase (according to the attributes previously retrieved).

Since:
1.2
 
 public class CasRealm extends AuthorizingRealm {
 
     // default name of the CAS attribute for remember me authentication (CAS 3.4.10+)
     public static final String DEFAULT_REMEMBER_ME_ATTRIBUTE_NAME = "longTermAuthenticationRequestTokenUsed";
     public static final String DEFAULT_VALIDATION_PROTOCOL = "CAS";
     
     private static Logger log = LoggerFactory.getLogger(CasRealm.class);
     
     // this is the url of the CAS server (example : http://host:port/cas)
     private String casServerUrlPrefix;
     
     // this is the CAS service url of the application (example : http://host:port/mycontextpath/shiro-cas)
     private String casService;
     
     /* CAS protocol to use for ticket validation : CAS (default) or SAML :
        - CAS protocol can be used with CAS server version < 3.1 : in this case, no user attributes can be retrieved from the CAS ticket validation response (except if there are some customizations on CAS server side)
        - SAML protocol can be used with CAS server version >= 3.1 : in this case, user attributes can be extracted from the CAS ticket validation response
     */
     
     // default name of the CAS attribute for remember me authentication (CAS 3.4.10+)
     
     // this class from the CAS client is used to validate a service ticket on CAS server
     private TicketValidator ticketValidator;
     
     // default roles to applied to authenticated user
     private String defaultRoles;
     
     // default permissions to applied to authenticated user
     private String defaultPermissions;
     
     // names of attributes containing roles
     private String roleAttributeNames;
     
     // names of attributes containing permissions
     private String permissionAttributeNames;
     
     public CasRealm() {
         setAuthenticationTokenClass(CasToken.class);
     }
 
    @Override
    protected void onInit() {
        super.onInit();
        ensureTicketValidator();
    }
    protected TicketValidator ensureTicketValidator() {
        if (this. == null) {
            this. = createTicketValidator();
        }
        return this.;
    }
    
    protected TicketValidator createTicketValidator() {
        String urlPrefix = getCasServerUrlPrefix();
        if ("saml".equalsIgnoreCase(getValidationProtocol())) {
            return new Saml11TicketValidator(urlPrefix);
        }
        return new Cas20ServiceTicketValidator(urlPrefix);
    }
    
    
Authenticates a user and retrieves its information.

Parameters:
token the authentication token
Throws:
org.apache.shiro.authc.AuthenticationException if there is an error during authentication.
    @Override
    @SuppressWarnings("unchecked")
        CasToken casToken = (CasTokentoken;
        if (token == null) {
            return null;
        }
        
        String ticket = (String)casToken.getCredentials();
        if (!StringUtils.hasText(ticket)) {
            return null;
        }
        
        TicketValidator ticketValidator = ensureTicketValidator();
        try {
            // contact CAS server to validate service ticket
            Assertion casAssertion = ticketValidator.validate(ticketgetCasService());
            // get principal, user id and attributes
            AttributePrincipal casPrincipal = casAssertion.getPrincipal();
            String userId = casPrincipal.getName();
            .debug("Validate ticket : {} in CAS server : {} to retrieve user : {}"new Object[]{
                    ticketgetCasServerUrlPrefix(), userId
            });
            Map<StringObjectattributes = casPrincipal.getAttributes();
            // refresh authentication token (user id + remember me)
            casToken.setUserId(userId);
            String rememberMeAttributeName = getRememberMeAttributeName();
            String rememberMeStringValue = (String)attributes.get(rememberMeAttributeName);
            boolean isRemembered = rememberMeStringValue != null && Boolean.parseBoolean(rememberMeStringValue);
            if (isRemembered) {
                casToken.setRememberMe(true);
            }
            // create simple authentication info
            List<Objectprincipals = CollectionUtils.asList(userIdattributes);
            PrincipalCollection principalCollection = new SimplePrincipalCollection(principalsgetName());
            return new SimpleAuthenticationInfo(principalCollectionticket);
        } catch (TicketValidationException e) { 
            throw new CasAuthenticationException("Unable to validate ticket [" + ticket + "]"e);
        }
    }
    
    
Retrieves the AuthorizationInfo for the given principals (the CAS previously authenticated user : id + attributes).

Parameters:
principals the primary identifying principals of the AuthorizationInfo that should be retrieved.
Returns:
the AuthorizationInfo associated with this principals.
    @Override
    @SuppressWarnings("unchecked")
        // retrieve user information
        SimplePrincipalCollection principalCollection = (SimplePrincipalCollectionprincipals;
        List<ObjectlistPrincipals = principalCollection.asList();
        Map<StringStringattributes = (Map<StringString>) listPrincipals.get(1);
        // create simple authorization info
        SimpleAuthorizationInfo simpleAuthorizationInfo = new SimpleAuthorizationInfo();
        // add default roles
        addRoles(simpleAuthorizationInfosplit());
        // add default permissions
        addPermissions(simpleAuthorizationInfosplit());
        // get roles from attributes
        List<StringattributeNames = split();
        for (String attributeName : attributeNames) {
            String value = attributes.get(attributeName);
            addRoles(simpleAuthorizationInfosplit(value));
        }
        // get permissions from attributes
        attributeNames = split();
        for (String attributeName : attributeNames) {
            String value = attributes.get(attributeName);
            addPermissions(simpleAuthorizationInfosplit(value));
        }
        return simpleAuthorizationInfo;
    }
    
    
Split a string into a list of not empty and trimmed strings, delimiter is a comma.

Parameters:
s the input string
Returns:
the list of not empty and trimmed strings
    private List<Stringsplit(String s) {
        List<Stringlist = new ArrayList<String>();
        String[] elements = StringUtils.split(s',');
        if (elements != null && elements.length > 0) {
            for (String element : elements) {
                if (StringUtils.hasText(element)) {
                    list.add(element.trim());
                }
            }
        }
        return list;
    }
    
    
Add roles to the simple authorization info.

Parameters:
simpleAuthorizationInfo
roles the list of roles to add
    private void addRoles(SimpleAuthorizationInfo simpleAuthorizationInfoList<Stringroles) {
        for (String role : roles) {
            simpleAuthorizationInfo.addRole(role);
        }
    }
    
    
Add permissions to the simple authorization info.

Parameters:
simpleAuthorizationInfo
permissions the list of permissions to add
    private void addPermissions(SimpleAuthorizationInfo simpleAuthorizationInfoList<Stringpermissions) {
        for (String permission : permissions) {
            simpleAuthorizationInfo.addStringPermission(permission);
        }
    }
    public String getCasServerUrlPrefix() {
        return ;
    }
    public void setCasServerUrlPrefix(String casServerUrlPrefix) {
        this. = casServerUrlPrefix;
    }
    public String getCasService() {
        return ;
    }
    public void setCasService(String casService) {
        this. = casService;
    }
    public String getValidationProtocol() {
        return ;
    }
    public void setValidationProtocol(String validationProtocol) {
        this. = validationProtocol;
    }
        return ;
    }
    public void setRememberMeAttributeName(String rememberMeAttributeName) {
        this. = rememberMeAttributeName;
    }
    public String getDefaultRoles() {
        return ;
    }
    public void setDefaultRoles(String defaultRoles) {
        this. = defaultRoles;
    }
    public String getDefaultPermissions() {
        return ;
    }
    public void setDefaultPermissions(String defaultPermissions) {
        this. = defaultPermissions;
    }
    public String getRoleAttributeNames() {
        return ;
    }
    public void setRoleAttributeNames(String roleAttributeNames) {
        this. = roleAttributeNames;
    }
        return ;
    }
    public void setPermissionAttributeNames(String permissionAttributeNames) {
        this. = permissionAttributeNames;
    }
New to GrepCode? Check out our FAQ X