Example usage for org.springframework.security.core GrantedAuthority getAuthority

List of usage examples for org.springframework.security.core GrantedAuthority getAuthority

Introduction

In this page you can find the example usage for org.springframework.security.core GrantedAuthority getAuthority.

Prototype

String getAuthority();

Source Link

Document

If the GrantedAuthority can be represented as a String and that String is sufficient in precision to be relied upon for an access control decision by an AccessDecisionManager (or delegate), this method should return such a String.

Usage

From source file:com.hp.autonomy.frontend.find.core.web.FindController.java

@RequestMapping(value = APP_PATH, method = RequestMethod.GET)
public ModelAndView mainPage() throws JsonProcessingException {
    final String username = authenticationInformationRetriever.getAuthentication().getName();

    final Collection<String> roles = new LinkedList<>();

    for (final GrantedAuthority authority : authenticationInformationRetriever.getAuthentication()
            .getAuthorities()) {//from  w w  w .ja  va2s .co m
        roles.add(authority.getAuthority());
    }

    final Map<String, Object> config = new HashMap<>();
    config.put(MvcConstants.USERNAME.value(), username);
    config.put(MvcConstants.ROLES.value(), roles);
    config.put(MvcConstants.GIT_COMMIT.value(), gitCommit);
    config.put(MvcConstants.RELEASE_VERSION.value(), releaseVersion);
    config.put(MvcConstants.MAP.value(), configService.getConfig().getMap());
    config.put(MvcConstants.SAVED_SEARCH_CONFIG.value(), configService.getConfig().getSavedSearchConfig());
    config.put(MvcConstants.MIN_SCORE.value(), configService.getConfig().getMinScore());
    config.put(MvcConstants.FIELDS_INFO.value(), configService.getConfig().getFieldsInfo().getFieldConfig());
    config.put(MvcConstants.TOPIC_MAP_MAX_RESULTS.value(), configService.getConfig().getTopicMapMaxResults());
    config.putAll(getPublicConfig());

    final Map<String, Object> attributes = new HashMap<>();
    attributes.put(MvcConstants.GIT_COMMIT.value(), gitCommit);
    attributes.put(MvcConstants.CONFIG.value(), controllerUtils.convertToJson(config));

    return new ModelAndView(ViewNames.APP.viewName(), attributes);
}

From source file:com.camel.action.base.LoginAction.java

public boolean hasRole(String role) {
    for (GrantedAuthority auth : SecurityContextHolder.getContext().getAuthentication().getAuthorities()) {
        if (role.contains(auth.getAuthority()))
            return true;

    }//from   w  w  w.  java2  s.com

    return false;
}

From source file:com.linuxbox.enkive.permissions.SpringContextPermissionService.java

@Override
public Collection<String> getCurrentUserAuthorities() throws CannotGetPermissionsException {
    Collection<String> authorityStrings = new HashSet<String>();
    for (GrantedAuthority auth : SecurityContextHolder.getContext().getAuthentication().getAuthorities()) {
        authorityStrings.add(auth.getAuthority());
    }/*from www .j a v  a2s . c  o  m*/
    return authorityStrings;
}

From source file:com.sibvisions.rad.server.security.spring.handler.DefaultAuthenticationMetaDataHandler.java

/**
 * {@inheritDoc}// w w w  .  j  a v  a2 s .co m
 */
public String[] getRoles() {
    if (sRoles == null) {
        ArrayUtil<String> auRoles = new ArrayUtil<String>();

        Collection<? extends GrantedAuthority> authorities = authentication.getAuthorities();

        for (GrantedAuthority authority : authorities) {
            if (!auRoles.contains(authority.getAuthority())) {
                String sAuthority = authority.getAuthority().trim();

                if (sAuthority.startsWith("[") && sAuthority.endsWith("]")) {
                    sAuthority = sAuthority.substring(1, sAuthority.length() - 1).trim();
                }

                auRoles.add(sAuthority);
            }
        }

        sRoles = new String[auRoles.size()];
        auRoles.toArray(sRoles);
    }

    return sRoles;
}

From source file:eionet.transfer.controller.UserController.java

/**
 * Form for editing existing user./*  w  w  w .j  a  va  2  s .c  om*/
 * @param userName
 * @param model - contains attributes for the view
 * @param message
 * @return view name
 */
@RequestMapping("/existing")
public String existingUser(@RequestParam String userName, Model model,
        @RequestParam(required = false) String message) {
    model.addAttribute("userName", userName);
    BreadCrumbs.set(model, "Modify user");
    UserDetails userDetails = userManagementService.loadUserByUsername(userName);

    ArrayList<String> userRoles = new ArrayList<String>();
    for (GrantedAuthority authority : userDetails.getAuthorities()) {
        userRoles.add(authority.getAuthority());
    }
    Authorisation user = new Authorisation(userName, userRoles);
    model.addAttribute("user", user);
    if (message != null)
        model.addAttribute("message", message);
    return EXISTING_USER_HTML;
}

From source file:fi.helsinki.opintoni.security.SAMLUserDetailsServiceTest.java

@Test
public void thatStudentAppUserIsReturned() {
    SAMLCredential credential = samlStudentCredential();

    AppUser appUser = (AppUser) userDetailsService.loadUserBySAML(credential);

    assertThat(appUser.getUsername()).isEqualTo(SAML_PRINCIPAL_NAME);
    assertThat(appUser.getEmail()).isEqualTo(SAML_EMAIL);
    assertThat(appUser.getCommonName()).isEqualTo(SAML_COMMON_NAME);
    assertThat(appUser.getOodiPersonId()).isEqualTo(OODI_PERSON_ID);
    assertThat(appUser.getStudentNumber().get()).isEqualTo(SAML_STUDENT_NUMBER_FINAL);
    assertThat(appUser.getPreferredLanguage()).isEqualTo(SAML_PREFERRED_LANGUAGE);
    assertThat(appUser.getEduPersonAffiliations().contains(SAMLEduPersonAffiliation.STUDENT)).isTrue();
    assertThat(appUser.getEduPersonPrimaryAffiliation()).isEqualTo(SAMLEduPersonAffiliation.STUDENT);
    assertThat(appUser.getTeacherNumber().isPresent()).isFalse();
    assertThat(appUser.getAuthorities()).hasSize(1);

    GrantedAuthority grantedAuthority = Iterables.getOnlyElement(appUser.getAuthorities());
    assertThat(grantedAuthority.getAuthority()).isEqualTo(AppUser.Role.STUDENT.name());
}

From source file:fi.helsinki.opintoni.security.SAMLUserDetailsServiceTest.java

@Test
public void thatTeacherAppUserIsReturned() {
    SAMLCredential credential = samlTeacherCredential();

    AppUser appUser = (AppUser) userDetailsService.loadUserBySAML(credential);

    assertThat(appUser.getUsername()).isEqualTo(SAML_PRINCIPAL_NAME);
    assertThat(appUser.getEmail()).isEqualTo(SAML_EMAIL);
    assertThat(appUser.getCommonName()).isEqualTo(SAML_COMMON_NAME);
    assertThat(appUser.getOodiPersonId()).isEqualTo(OODI_PERSON_ID);
    assertThat(appUser.getTeacherNumber().get()).isEqualTo(SAML_TEACHER_NUMBER);
    assertThat(appUser.getPreferredLanguage()).isEqualTo(SAML_PREFERRED_LANGUAGE);
    assertThat(appUser.getEduPersonAffiliations().contains(SAMLEduPersonAffiliation.FACULTY)).isTrue();
    assertThat(appUser.getEduPersonPrimaryAffiliation()).isEqualTo(SAMLEduPersonAffiliation.FACULTY);
    assertThat(appUser.getStudentNumber().isPresent()).isFalse();
    assertThat(appUser.getAuthorities()).hasSize(1);

    GrantedAuthority grantedAuthority = Iterables.getOnlyElement(appUser.getAuthorities());
    assertThat(grantedAuthority.getAuthority()).isEqualTo(AppUser.Role.TEACHER.name());
}

From source file:nz.net.orcon.kanban.security.SecurityToolImpl.java

@Override
public boolean isAuthorised(Map<String, String> roles, String filter) {

    if (roles == null) {
        return false;
    }/* w  w w .j  av  a2  s .co  m*/

    SecurityContext context = SecurityContextHolder.getContext();

    if (context == null || context.getAuthentication() == null) {
        return false;
    }

    String username = (String) context.getAuthentication().getPrincipal();

    Set<String> teams = new HashSet<String>();
    for (GrantedAuthority authority : context.getAuthentication().getAuthorities()) {
        teams.add(authority.getAuthority());
    }

    for (Entry<String, String> entry : roles.entrySet()) {
        if (filter == null || filter.contains((entry.getValue()))) {
            if (username.equals(entry.getKey())) {
                return true;
            }
            if (teams.contains(entry.getKey())) {
                return true;
            }
        }
    }
    LOG.warn("Unauthorized: " + username);
    return false;
}

From source file:de.forsthaus.UserWorkspace.java

/**
 * Copied the grantedAuthorities to a Set of strings <br>
 * for a faster searching in it.//w w w .j  av a2 s. com
 * 
 * @return String set of GrantedAuthorities (rightNames)
 */
private Set<String> getGrantedAuthoritySet() {

    if (this.grantedAuthoritySet == null) {

        final Collection<GrantedAuthority> list = getAuthentication().getAuthorities();
        this.grantedAuthoritySet = new HashSet<String>(list.size());

        for (final GrantedAuthority grantedAuthority : list) {
            this.grantedAuthoritySet.add(grantedAuthority.getAuthority());
        }
    }
    return this.grantedAuthoritySet;
}

From source file:se.kth.csc.auth.UserService.java

@Transactional
@Override//  ww  w. j  a  v  a  2s.co  m
public UserDetails loadUserDetails(Authentication token) throws UsernameNotFoundException {
    if (!token.getName().startsWith("u1")) {
        // See http://intra.kth.se/it/driftsinformation-webbtjanster/anstallda/inloggning-maste-ske-med-sma-bokstaver-1.475521
        // which allows an exploit. Counter-measured by only allowing usernames starting with "u1"
        throw new UsernameNotFoundException("This username is not in the u1 realm and was probably forged");
    }

    Account account = accountStore.fetchAccountWithPrincipalName(token.getName());

    if (account == null) {
        account = new Account();
        account.setPrincipalName(token.getName());
        for (GrantedAuthority grantedAuthority : token.getAuthorities()) {
            if (Role.ADMIN.getAuthority().equals(grantedAuthority.getAuthority())) {
                account.setAdmin(true);
                break;
            }
        }
        accountStore.storeAccount(account);

        log.info("Created user called \"{}\" with id {} and principal {}", account.getName(), account.getId(),
                account.getPrincipalName());
    }
    String name = nameService.nameUser(token.getName());

    if (account.getName() == null || !account.getName().equals(name)) {
        account.setName(name);
        log.info("User with id {} and principal {} is now called \"{}\"", account.getId(),
                account.getPrincipalName(), name);
    }

    return createUser(account);
}