Example usage for org.springframework.security.core.userdetails.memory UserAttribute getAuthorities

List of usage examples for org.springframework.security.core.userdetails.memory UserAttribute getAuthorities

Introduction

In this page you can find the example usage for org.springframework.security.core.userdetails.memory UserAttribute getAuthorities.

Prototype

public List<GrantedAuthority> getAuthorities() 

Source Link

Usage

From source file:nu.localhost.tapestry5.springsecurity.services.SecurityModule.java

@Marker(SpringSecurityServices.class)
public static HttpServletRequestFilter buildAnonymousProcessingFilter(
        @Inject @Value("${spring-security.anonymous.attribute}") final String anonymousAttr,
        @Inject @Value("${spring-security.anonymous.key}") final String anonymousKey) throws Exception {

    final UserAttributeEditor attrEditor = new UserAttributeEditor();
    attrEditor.setAsText(anonymousAttr);
    final UserAttribute attr = (UserAttribute) attrEditor.getValue();

    final AnonymousAuthenticationFilter filter = new AnonymousAuthenticationFilter(anonymousKey,
            "anonymousUser", attr.getAuthorities());
    filter.afterPropertiesSet();//from w  w  w  .  j  a  v a  2 s . c  om
    return new HttpServletRequestFilterWrapper(filter);
}

From source file:org.pentaho.proxy.spring4.security.UserDetailsImpl.java

public UserDetailsImpl(String username, UserAttribute userAttribute) {
    super(username, userAttribute.getPassword(), userAttribute.getAuthorities());
}

From source file:org.geoserver.security.GeoServerSecurityManager.java

/**
 * @return the master password used for the migration
 * @throws Exception/*from  w w w  .  j  av a  2s.c  o  m*/
 */
char[] extractMasterPasswordForMigration(Properties props) throws Exception {

    Map<String, String> candidates = new HashMap<String, String>();
    String defaultPasswordAsString = new String(MASTER_PASSWD_DEFAULT);

    if (props != null) {
        //load user.properties populate the services 

        UserAttributeEditor configAttribEd = new UserAttributeEditor();

        for (Iterator<Object> iter = props.keySet().iterator(); iter.hasNext();) {
            String username = (String) iter.next();

            configAttribEd.setAsText(props.getProperty(username));
            UserAttribute attr = (UserAttribute) configAttribEd.getValue();
            if (attr == null)
                continue;

            // The master password policy is not yet available, the default is to
            // have a minimum of 8 chars --> all passwords shorter than 8 chars
            // are no candidates
            if (attr.getPassword() == null || attr.getPassword().length() < 8)
                continue;

            // The default password is not allowed
            if (defaultPasswordAsString.equals(attr.getPassword()))
                continue;

            // the  user named "admin" having a non default password is the primary candiate                
            if (GeoServerUser.ADMIN_USERNAME.equals(username)) {
                candidates.put(GeoServerUser.ADMIN_USERNAME, attr.getPassword());
                continue;
            }

            // other users having the amin role are secondary candidates
            if (attr.getAuthorities().contains(GeoServerRole.ADMIN_ROLE)) {
                candidates.put(username, attr.getPassword());
            }
        }
    }

    String username = GeoServerUser.ADMIN_USERNAME;
    String masterPW = candidates.get(username);
    if (masterPW == null && candidates.size() > 0) {
        username = candidates.keySet().iterator().next();
        masterPW = candidates.get(username);
    }

    String message = null;
    File info = new File(getSecurityRoot(), MASTER_PASSWD_INFO_FILENAME);
    char[] masterPasswordArray = null;
    if (masterPW != null) {
        message = "Master password is identical to the password of user: " + username;
        masterPasswordArray = masterPW.toCharArray();
        writeMasterPasswordInfo(info, message, null);
    } else {
        message = "The generated master password is: ";
        masterPasswordArray = getRandomPassworddProvider().getRandomPassword(8);
        writeMasterPasswordInfo(info, message, masterPasswordArray);
    }

    LOGGER.info("Information regarding the master password is in: " + info.getCanonicalPath());
    return masterPasswordArray;
}

From source file:org.geoserver.security.GeoServerSecurityManager.java

/**
 * converts an 2.1.x security configuration to 2.2.x
 * /*from w w w .  j  ava2  s .c  om*/
 * @return <code>true</code> if migration has taken place  
 * @throws Exception
 */
boolean migrateFrom21() throws Exception {

    if (getRoleRoot(false) != null) {
        File oldUserFile = new File(getSecurityRoot(), "users.properties.old");
        if (oldUserFile.exists()) {
            LOGGER.warning(oldUserFile.getCanonicalPath() + " could be removed manually");
        }
        return false; // already migrated
    }

    LOGGER.info("Start security migration");

    //create required directories
    getRoleRoot();
    getUserGroupRoot();
    getAuthRoot();
    getPasswordPolicyRoot();
    getFilterRoot();
    getMasterPasswordProviderRoot();

    //master password configuration
    MasterPasswordProviderConfig mpProviderConfig = loadMasterPassswordProviderConfig("default");
    if (mpProviderConfig == null) {
        mpProviderConfig = new URLMasterPasswordProviderConfig();
        mpProviderConfig.setName("default");
        mpProviderConfig.setClassName(URLMasterPasswordProvider.class.getCanonicalName());
        mpProviderConfig.setReadOnly(false);

        ((URLMasterPasswordProviderConfig) mpProviderConfig).setURL(new URL("file:passwd"));
        ((URLMasterPasswordProviderConfig) mpProviderConfig).setEncrypting(true);
        saveMasterPasswordProviderConfig(mpProviderConfig, false);

        //save out the default master password
        MasterPasswordProvider mpProvider = loadMasterPasswordProvider(mpProviderConfig.getName());
        File propFile = new File(getSecurityRoot(), "users.properties");
        Properties userprops = null;
        if (propFile.exists())
            userprops = Util.loadPropertyFile(propFile);
        mpProvider.setMasterPassword(extractMasterPasswordForMigration(userprops));
    }

    MasterPasswordConfig mpConfig = new MasterPasswordConfig();
    mpConfig.setProviderName(mpProviderConfig.getName());
    saveMasterPasswordConfig(mpConfig);

    // check for services.properties, create if necessary
    File serviceFile = new File(getSecurityRoot(), "services.properties");
    if (serviceFile.exists() == false) {
        FileUtils.copyURLToFile(Util.class.getResource("serviceTemplate.properties"), serviceFile);
    }

    long checkInterval = 10000; // 10 secs

    //check for the default user group service, create if necessary
    GeoServerUserGroupService userGroupService = loadUserGroupService(XMLUserGroupService.DEFAULT_NAME);

    KeyStoreProvider keyStoreProvider = getKeyStoreProvider();
    keyStoreProvider.reloadKeyStore();
    keyStoreProvider.setUserGroupKey(XMLUserGroupService.DEFAULT_NAME,
            randomPasswdProvider.getRandomPassword(32));
    keyStoreProvider.storeKeyStore();

    PasswordValidator validator = loadPasswordValidator(PasswordValidator.DEFAULT_NAME);
    if (validator == null) {
        // Policy allows any password except null, this is the default
        // at before migration
        PasswordPolicyConfig pwpconfig = new PasswordPolicyConfig();
        pwpconfig.setName(PasswordValidator.DEFAULT_NAME);
        pwpconfig.setClassName(PasswordValidatorImpl.class.getName());
        pwpconfig.setMinLength(0);
        savePasswordPolicy(pwpconfig);
        validator = loadPasswordValidator(PasswordValidator.DEFAULT_NAME);
    }

    validator = loadPasswordValidator(PasswordValidator.MASTERPASSWORD_NAME);
    if (validator == null) {
        // Policy requires a minimum of 8 chars for the master password            
        PasswordPolicyConfig pwpconfig = new PasswordPolicyConfig();
        pwpconfig.setName(PasswordValidator.MASTERPASSWORD_NAME);
        pwpconfig.setClassName(PasswordValidatorImpl.class.getName());
        pwpconfig.setMinLength(8);
        savePasswordPolicy(pwpconfig);
        validator = loadPasswordValidator(PasswordValidator.MASTERPASSWORD_NAME);
    }

    if (userGroupService == null) {
        XMLUserGroupServiceConfig ugConfig = new XMLUserGroupServiceConfig();
        ugConfig.setName(XMLUserGroupService.DEFAULT_NAME);
        ugConfig.setClassName(XMLUserGroupService.class.getName());
        ugConfig.setCheckInterval(checkInterval);
        ugConfig.setFileName(XMLConstants.FILE_UR);
        ugConfig.setValidating(true);
        // start with weak encryption, plain passwords can be restored
        ugConfig.setPasswordEncoderName(
                loadPasswordEncoder(GeoServerPBEPasswordEncoder.class, null, false).getName());
        ugConfig.setPasswordPolicyName(PasswordValidator.DEFAULT_NAME);
        saveUserGroupService(ugConfig);
        userGroupService = loadUserGroupService(XMLUserGroupService.DEFAULT_NAME);
    }

    //check for the default role service, create if necessary
    GeoServerRoleService roleService = loadRoleService(XMLRoleService.DEFAULT_NAME);

    if (roleService == null) {
        XMLRoleServiceConfig gaConfig = new XMLRoleServiceConfig();
        gaConfig.setName(XMLRoleService.DEFAULT_NAME);
        gaConfig.setClassName(XMLRoleService.class.getName());
        gaConfig.setCheckInterval(checkInterval);
        gaConfig.setFileName(XMLConstants.FILE_RR);
        gaConfig.setValidating(true);
        gaConfig.setAdminRoleName(XMLRoleService.DEFAULT_LOCAL_ADMIN_ROLE);
        gaConfig.setGroupAdminRoleName(XMLRoleService.DEFAULT_LOCAL_GROUP_ADMIN_ROLE);
        saveRoleService(gaConfig);
        roleService = loadRoleService(XMLRoleService.DEFAULT_NAME);
    }

    String filterName = GeoServerSecurityFilterChain.BASIC_AUTH_FILTER;
    GeoServerSecurityFilter filter = loadFilter(filterName);
    if (filter == null) {
        BasicAuthenticationFilterConfig bfConfig = new BasicAuthenticationFilterConfig();
        bfConfig.setName(filterName);
        bfConfig.setClassName(GeoServerBasicAuthenticationFilter.class.getName());
        bfConfig.setUseRememberMe(true);
        saveFilter(bfConfig);
    }
    /*filterName = GeoServerSecurityFilterChain.BASIC_AUTH_NO_REMEMBER_ME_FILTER;
    filter = loadFilter(filterName);                  
    if (filter==null) {
    BasicAuthenticationFilterConfig bfConfig = new BasicAuthenticationFilterConfig();
    bfConfig.setClassName(GeoServerBasicAuthenticationFilter.class.getName());
    bfConfig.setName(filterName);
    bfConfig.setUseRememberMe(false);
    saveFilter(bfConfig);
    }*/
    filterName = GeoServerSecurityFilterChain.FORM_LOGIN_FILTER;
    filter = loadFilter(filterName);
    if (filter == null) {
        UsernamePasswordAuthenticationFilterConfig upConfig = new UsernamePasswordAuthenticationFilterConfig();
        upConfig.setClassName(GeoServerUserNamePasswordAuthenticationFilter.class.getName());
        upConfig.setName(filterName);
        upConfig.setUsernameParameterName(UsernamePasswordAuthenticationFilterConfig.DEFAULT_USERNAME_PARAM);
        upConfig.setPasswordParameterName(UsernamePasswordAuthenticationFilterConfig.DEFAULT_PASSWORD_PARAM);
        saveFilter(upConfig);
    }
    filterName = GeoServerSecurityFilterChain.SECURITY_CONTEXT_ASC_FILTER;
    filter = loadFilter(filterName);
    if (filter == null) {
        SecurityContextPersistenceFilterConfig pConfig = new SecurityContextPersistenceFilterConfig();
        pConfig.setClassName(GeoServerSecurityContextPersistenceFilter.class.getName());
        pConfig.setName(filterName);
        pConfig.setAllowSessionCreation(true);
        saveFilter(pConfig);
    }
    filterName = GeoServerSecurityFilterChain.SECURITY_CONTEXT_NO_ASC_FILTER;
    filter = loadFilter(filterName);
    if (filter == null) {
        SecurityContextPersistenceFilterConfig pConfig = new SecurityContextPersistenceFilterConfig();
        pConfig.setClassName(GeoServerSecurityContextPersistenceFilter.class.getName());
        pConfig.setName(filterName);
        pConfig.setAllowSessionCreation(false);
        saveFilter(pConfig);
    }
    filterName = GeoServerSecurityFilterChain.ANONYMOUS_FILTER;
    filter = loadFilter(filterName);
    if (filter == null) {
        AnonymousAuthenticationFilterConfig aConfig = new AnonymousAuthenticationFilterConfig();
        aConfig.setClassName(GeoServerAnonymousAuthenticationFilter.class.getName());
        aConfig.setName(filterName);
        saveFilter(aConfig);
    }
    filterName = GeoServerSecurityFilterChain.REMEMBER_ME_FILTER;
    filter = loadFilter(filterName);
    if (filter == null) {
        RememberMeAuthenticationFilterConfig rConfig = new RememberMeAuthenticationFilterConfig();
        rConfig.setClassName(GeoServerRememberMeAuthenticationFilter.class.getName());
        rConfig.setName(filterName);
        saveFilter(rConfig);
    }
    filterName = GeoServerSecurityFilterChain.FILTER_SECURITY_INTERCEPTOR;
    filter = loadFilter(filterName);
    if (filter == null) {
        SecurityInterceptorFilterConfig siConfig = new SecurityInterceptorFilterConfig();
        siConfig.setClassName(GeoServerSecurityInterceptorFilter.class.getName());
        siConfig.setName(filterName);
        siConfig.setAllowIfAllAbstainDecisions(false);
        siConfig.setSecurityMetadataSource("geoserverMetadataSource");
        saveFilter(siConfig);
    }
    filterName = GeoServerSecurityFilterChain.FILTER_SECURITY_REST_INTERCEPTOR;
    filter = loadFilter(filterName);
    if (filter == null) {
        SecurityInterceptorFilterConfig siConfig = new SecurityInterceptorFilterConfig();
        siConfig.setClassName(GeoServerSecurityInterceptorFilter.class.getName());
        siConfig.setName(filterName);
        siConfig.setAllowIfAllAbstainDecisions(false);
        siConfig.setSecurityMetadataSource("restFilterDefinitionMap");
        saveFilter(siConfig);
    }
    filterName = GeoServerSecurityFilterChain.FORM_LOGOUT_FILTER;
    filter = loadFilter(filterName);
    if (filter == null) {
        LogoutFilterConfig loConfig = new LogoutFilterConfig();
        loConfig.setClassName(GeoServerLogoutFilter.class.getName());
        loConfig.setName(filterName);
        saveFilter(loConfig);
    }
    filterName = GeoServerSecurityFilterChain.DYNAMIC_EXCEPTION_TRANSLATION_FILTER;
    filter = loadFilter(filterName);
    if (filter == null) {
        ExceptionTranslationFilterConfig bfConfig = new ExceptionTranslationFilterConfig();
        bfConfig.setClassName(GeoServerExceptionTranslationFilter.class.getName());
        bfConfig.setName(filterName);
        bfConfig.setAuthenticationFilterName(null);
        bfConfig.setAccessDeniedErrorPage("/accessDenied.jsp");
        saveFilter(bfConfig);
    }
    filterName = GeoServerSecurityFilterChain.GUI_EXCEPTION_TRANSLATION_FILTER;
    filter = loadFilter(filterName);
    if (filter == null) {
        ExceptionTranslationFilterConfig bfConfig = new ExceptionTranslationFilterConfig();
        bfConfig.setClassName(GeoServerExceptionTranslationFilter.class.getName());
        bfConfig.setName(filterName);
        bfConfig.setAuthenticationFilterName(GeoServerSecurityFilterChain.FORM_LOGIN_FILTER);
        bfConfig.setAccessDeniedErrorPage("/accessDenied.jsp");
        saveFilter(bfConfig);
    }

    //check for the default auth provider, create if necessary
    GeoServerAuthenticationProvider authProvider = (GeoServerAuthenticationProvider) loadAuthenticationProvider(
            GeoServerAuthenticationProvider.DEFAULT_NAME);
    if (authProvider == null) {
        UsernamePasswordAuthenticationProviderConfig upAuthConfig = new UsernamePasswordAuthenticationProviderConfig();
        upAuthConfig.setName(GeoServerAuthenticationProvider.DEFAULT_NAME);
        upAuthConfig.setClassName(UsernamePasswordAuthenticationProvider.class.getName());
        upAuthConfig.setUserGroupServiceName(userGroupService.getName());

        saveAuthenticationProvider(upAuthConfig);
        authProvider = loadAuthenticationProvider(GeoServerAuthenticationProvider.DEFAULT_NAME);
    }

    //save the top level config
    SecurityManagerConfig config = new SecurityManagerConfig();
    config.setRoleServiceName(roleService.getName());
    config.getAuthProviderNames().add(authProvider.getName());
    config.setEncryptingUrlParams(false);

    // start with weak encryption
    config.setConfigPasswordEncrypterName(
            loadPasswordEncoder(GeoServerPBEPasswordEncoder.class, true, false).getName());

    // setup the default remember me service
    RememberMeServicesConfig rememberMeConfig = new RememberMeServicesConfig();
    rememberMeConfig.setClassName(GeoServerTokenBasedRememberMeServices.class.getName());
    config.setRememberMeService(rememberMeConfig);

    config.setFilterChain(GeoServerSecurityFilterChain.createInitialChain());
    saveSecurityConfig(config);

    //TODO: just call initializeFrom
    userGroupService.setSecurityManager(this);
    roleService.setSecurityManager(this);

    //populate the user group and role service
    GeoServerUserGroupStore userGroupStore = userGroupService.createStore();
    GeoServerRoleStore roleStore = roleService.createStore();

    //migrate from users.properties
    File usersFile = new File(getSecurityRoot(), "users.properties");
    if (usersFile.exists()) {
        //load user.properties populate the services 
        Properties props = Util.loadPropertyFile(usersFile);

        UserAttributeEditor configAttribEd = new UserAttributeEditor();

        for (Iterator<Object> iter = props.keySet().iterator(); iter.hasNext();) {
            // the attribute editors parses the list of strings into password, username and enabled
            // flag
            String username = (String) iter.next();
            configAttribEd.setAsText(props.getProperty(username));

            // if the parsing succeeded turn that into a user object
            UserAttribute attr = (UserAttribute) configAttribEd.getValue();
            if (attr != null) {
                GeoServerUser user = userGroupStore.createUserObject(username, attr.getPassword(),
                        attr.isEnabled());
                userGroupStore.addUser(user);

                for (GrantedAuthority auth : attr.getAuthorities()) {
                    String roleName = GeoServerRole.ADMIN_ROLE.getAuthority().equals(auth.getAuthority())
                            ? XMLRoleService.DEFAULT_LOCAL_ADMIN_ROLE
                            : auth.getAuthority();
                    GeoServerRole role = roleStore.getRoleByName(roleName);
                    if (role == null) {
                        role = roleStore.createRoleObject(roleName);
                        roleStore.addRole(role);
                    }
                    roleStore.associateRoleToUser(role, username);
                }
            }
        }
    } else {
        // no user.properties, populate with default user and roles
        if (userGroupService.getUserByUsername(GeoServerUser.ADMIN_USERNAME) == null) {
            userGroupStore.addUser(GeoServerUser.createDefaultAdmin());
            GeoServerRole localAdminRole = roleStore.createRoleObject(XMLRoleService.DEFAULT_LOCAL_ADMIN_ROLE);
            roleStore.addRole(localAdminRole);
            roleStore.associateRoleToUser(localAdminRole, GeoServerUser.ADMIN_USERNAME);
        }
    }

    //add the local group administrator role
    if (roleStore.getRoleByName(XMLRoleService.DEFAULT_LOCAL_GROUP_ADMIN_ROLE) == null) {
        roleStore.addRole(roleStore.createRoleObject(XMLRoleService.DEFAULT_LOCAL_GROUP_ADMIN_ROLE));
    }

    // replace all occurrences of ROLE_ADMINISTRATOR  in the property files
    // TODO Justin, a little bit brute force, is this ok ?
    for (String filename : new String[] { "services.properties", "layers.properties", "rest.properties" }) {
        File file = new File(getSecurityRoot(), filename);
        if (file.exists() == false)
            continue;
        List<String> lines = new ArrayList<String>();
        BufferedReader reader = new BufferedReader(new FileReader(file));
        String line;
        while ((line = reader.readLine()) != null)
            lines.add(line.replace(GeoServerRole.ADMIN_ROLE.getAuthority(),
                    XMLRoleService.DEFAULT_LOCAL_ADMIN_ROLE));
        reader.close();
        PrintWriter writer = new PrintWriter(new FileWriter(file));
        for (String s : lines) {
            writer.println(s);
        }
        writer.close();
    }

    // check for roles in services.properties but not in user.properties 
    serviceFile = new File(getSecurityRoot(), "services.properties");
    if (serviceFile.exists()) {
        Properties props = Util.loadPropertyFile(serviceFile);
        for (Entry<Object, Object> entry : props.entrySet()) {
            StringTokenizer tokenizer = new StringTokenizer((String) entry.getValue(), ",");
            while (tokenizer.hasMoreTokens()) {
                String roleName = tokenizer.nextToken().trim();
                if (roleName.length() > 0) {
                    if (roleStore.getRoleByName(roleName) == null)
                        roleStore.addRole(roleStore.createRoleObject(roleName));
                }
            }
        }
    }

    // check for  roles in data.properties but not in user.properties
    File dataFile = new File(getSecurityRoot(), "layers.properties");
    if (dataFile.exists()) {
        Properties props = Util.loadPropertyFile(dataFile);
        for (Entry<Object, Object> entry : props.entrySet()) {
            if ("mode".equals(entry.getKey().toString()))
                continue; // skip mode directive
            StringTokenizer tokenizer = new StringTokenizer((String) entry.getValue(), ",");
            while (tokenizer.hasMoreTokens()) {
                String roleName = tokenizer.nextToken().trim();
                if (roleName.length() > 0 && roleName.equals("*") == false) {
                    if (roleStore.getRoleByName(roleName) == null)
                        roleStore.addRole(roleStore.createRoleObject(roleName));
                }
            }
        }
    }

    //persist the changes
    roleStore.store();
    userGroupStore.store();

    // first part of migration finished, rename old file
    if (usersFile.exists()) {
        File oldUserFile = new File(usersFile.getCanonicalPath() + ".old");
        usersFile.renameTo(oldUserFile);
        LOGGER.info("Renamed " + usersFile.getCanonicalPath() + " to " + oldUserFile.getCanonicalPath());
    }

    LOGGER.info("End security migration");
    return true;
}

From source file:org.pentaho.platform.plugin.services.security.userrole.memory.PentahoUserMapEditor.java

public static PentahoUserMap addUsersFromProperties(PentahoUserMap userMap, Properties props) {
    // Now we have properties, process each one individually
    PentahoUserAttributeEditor configAttribEd = new PentahoUserAttributeEditor();

    for (Object o : props.keySet()) {
        String username = (String) o;
        String value = props.getProperty(username);

        // Convert value to a password, enabled setting, and list of granted authorities
        configAttribEd.setAsText(value);

        UserAttribute attr = (UserAttribute) configAttribEd.getValue();

        // Make a user object, assuming the properties were properly provided
        if (attr != null) {
            UserDetails user = new User(username, attr.getPassword(), attr.isEnabled(), true, true, true,
                    attr.getAuthorities());
            userMap.addUser(user);//from ww  w. j av a2s.  c  o m
        }
    }
    return userMap;
}

From source file:org.springframework.security.provisioning.InMemoryUserDetailsManager.java

public InMemoryUserDetailsManager(Properties users) {
    Enumeration<?> names = users.propertyNames();
    UserAttributeEditor editor = new UserAttributeEditor();

    while (names.hasMoreElements()) {
        String name = (String) names.nextElement();
        editor.setAsText(users.getProperty(name));
        UserAttribute attr = (UserAttribute) editor.getValue();
        UserDetails user = new User(name, attr.getPassword(), attr.isEnabled(), true, true, true,
                attr.getAuthorities());
        createUser(user);//from   w w  w  . j av a2 s.  com
    }
}