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:eu.trentorise.smartcampus.permissionprovider.oauth.UserApprovalHandler.java

/**
 * Allows automatic approval for trusted clients.
 * //from ww w  . j  a v a2  s .c  om
 * @param authorizationRequest The authorization request.
 * @param userAuthentication the current user authentication
 * 
 * @return Whether the specified request has been approved by the current user.
 */
@Override
public boolean isApproved(AuthorizationRequest authorizationRequest, Authentication userAuthentication) {

    // If we are allowed to check existing approvals this will short circuit the decision
    if (super.isApproved(authorizationRequest, userAuthentication)) {
        return true;
    }

    if (!userAuthentication.isAuthenticated()) {
        return false;
    }

    String flag = authorizationRequest.getApprovalParameters().get(AuthorizationRequest.USER_OAUTH_APPROVAL);
    boolean approved = flag != null && flag.toLowerCase().equals("true");
    if (approved)
        return true;

    // or trusted client
    if (authorizationRequest.getAuthorities() != null) {
        for (GrantedAuthority ga : authorizationRequest.getAuthorities())
            if (Config.AUTHORITY.ROLE_CLIENT_TRUSTED.toString().equals(ga.getAuthority()))
                return true;
    }
    // or test token redirect uri
    // or accesses only own resources
    return authorizationRequest.getRedirectUri().equals(ExtRedirectResolver.testTokenPath(servletContext))
            || useOwnResourcesOnly(authorizationRequest.getClientId(), authorizationRequest.getScope());
}

From source file:org.openinfinity.sso.identityprovisioning.bpmn.ProcessEngineBridgeImpl.java

public Collection<org.openinfinity.sso.identityprovisioning.bpmn.Task> queryForTasksByUserRoles() {
    SecurityContext securityContext = SecurityContextHolder.getContext();
    Authentication authentication = securityContext.getAuthentication();
    IdentityService identityService = processEngine.getIdentityService();
    identityService.setAuthenticatedUserId(authentication.getName());
    TaskService taskService = processEngine.getTaskService();
    Collection<? extends GrantedAuthority> grantedAuthorities = authentication.getAuthorities();
    List<String> candidateGroups = new ArrayList<String>();
    for (GrantedAuthority grantedAuthority : grantedAuthorities) {
        if (grantedAuthority.getAuthority() != null)
            candidateGroups.add(grantedAuthority.getAuthority());
    }/* ww w  .j a  v a  2s .  c o  m*/
    List<Task> tasks = taskService.createTaskQuery().taskCandidateGroupIn(candidateGroups).list();
    Collection<org.openinfinity.sso.identityprovisioning.bpmn.Task> simpleTasks = mapTasks(tasks);
    return Collections.unmodifiableCollection(simpleTasks);
}

From source file:com.traffitruck.web.JsonController.java

@RequestMapping(value = "/deleteLoadAdmin", method = RequestMethod.POST)
String deleteLoad(@RequestParam("loadId") String loadId) {
    Authentication authentication = SecurityContextHolder.getContext().getAuthentication();
    for (GrantedAuthority auth : authentication.getAuthorities()) {
        if (Role.ADMIN.toString().equals(auth.getAuthority())) {
            dao.deleteLoadByAdmin(loadId);
        }//from  w  ww. j av  a  2s  .  com
    }
    return "Success!";
}

From source file:com.traffitruck.web.JsonController.java

@RequestMapping(value = "/allow_load_details", method = RequestMethod.POST)
String allowUserToSeeLoadsWithoutTrucks(@RequestParam("username") String username) {
    Authentication authentication = SecurityContextHolder.getContext().getAuthentication();
    for (GrantedAuthority auth : authentication.getAuthorities()) {
        if (Role.ADMIN.toString().equals(auth.getAuthority())) {
            dao.enableViewingLoads(username);
        }//w w  w . j a  v  a  2s  .  co m
    }
    return "Success!";
}

From source file:eu.supersede.fe.rest.ApplicationRest.java

@RequestMapping("/page")
public List<ApplicationGrouped> getUserAuthenticatedApplicationsPage(Authentication auth, Locale locale) {
    String lang = locale.getLanguage();

    Map<String, ApplicationGrouped> appsMap = new HashMap<>();
    Map<String, Map<String, Page>> appsPagesMap = new HashMap<>();
    List<ApplicationGrouped> applications = new ArrayList<>();

    List<String> authNames = new ArrayList<>();
    Collection<? extends GrantedAuthority> authorities = auth.getAuthorities();

    for (GrantedAuthority ga : authorities) {
        authNames.add(ga.getAuthority().substring(5));
    }/*from  w  ww  . j  a  va2s  .  c o m*/

    List<Profile> profList = profiles.findByNameIn(authNames);

    // make data nicer for frontend
    for (Profile p : profList) {
        Set<ApplicationPage> apps = applicationUtil.getApplicationsPagesByProfileName(p.getName());

        for (ApplicationPage app : apps) {
            ApplicationGrouped ag;

            if (!appsMap.containsKey(app.getApplicationName())) {
                Application a = applicationUtil.getApplication(app.getApplicationName());
                String appLabel = a.getLocalizedApplicationLabel(lang);
                ag = new ApplicationGrouped(app.getApplicationName(), appLabel);
                ag.setHomePage(a.getHomePage());
                applications.add(ag);
                appsMap.put(app.getApplicationName(), ag);
                appsPagesMap.put(app.getApplicationName(), new HashMap<String, Page>());
            } else {
                ag = appsMap.get(app.getApplicationName());
            }

            Page page;

            if (!appsPagesMap.get(app.getApplicationName()).containsKey(app.getApplicationPage())) {
                page = new Page(app.getApplicationPage(), app.getLocalizedApplicationPageLabel(lang));
                ag.getPages().add(page);
                appsPagesMap.get(app.getApplicationName()).put(app.getApplicationPage(), page);
            }
        }
    }

    return applications;
}

From source file:fi.vm.sade.organisaatio.auth.PermissionChecker.java

private boolean checkCRUDRyhma(OrganisaatioContext authContext) {
    Set<OrganisaatioTyyppi> tyypit = authContext.getOrgTypes();
    if (tyypit.size() == 1 && tyypit.contains(OrganisaatioTyyppi.RYHMA)) {
        Authentication auth = SecurityContextHolder.getContext().getAuthentication();
        for (GrantedAuthority ga : auth.getAuthorities()) {
            if (ga.getAuthority().startsWith("ROLE_APP_ORGANISAATIOHALLINTA_RYHMA_")) {
                return true;
            }/*from   w  ww.  j  a va 2s  .  co  m*/
        }
    }
    return false;
}

From source file:org.apigw.authserver.web.controller.AccessConfirmationController.java

@RequestMapping("/oauth/confirm_access")
public ModelAndView getAccessConfirmation(
        @ModelAttribute("authorizationRequest") AuthorizationRequest clientAuth) throws Exception {
    log.debug("getAccessConfirmation");
    CertifiedClient client = (CertifiedClient) clientDetailsService
            .loadClientByClientId(clientAuth.getClientId());
    TreeMap<String, Object> model = new TreeMap<String, Object>();
    UserDetails user = (UserDetails) SecurityContextHolder.getContext().getAuthentication().getPrincipal();
    log.debug("Logged in user is: {}", citizenLoggingUtil.getLogsafeSSN(user.getUsername()));
    for (GrantedAuthority role : user.getAuthorities()) {
        log.debug("---> User has role: {}", role.getAuthority());
    }//from ww  w. j  a v a 2 s . c  om
    if (clientAuth.getClientId() != null) {
        log.debug("The request holds the following client id:{}", clientAuth.getClientId());
    } else {
        log.warn("No client id on the request");
    }
    if (clientAuth.getResourceIds() != null) {
        log.debug("The following resourceIds were requested:");
        for (String resourceId : clientAuth.getResourceIds()) {
            log.debug("Resource id:{}", resourceId);
        }
    } else {
        log.warn("No resource ids on the request");
    }

    int validity = 0;

    List<String> scopes = new ArrayList<String>();
    if (clientAuth.getScope() != null) {
        log.debug("The following scopes were requested:");
        for (String permissionName : clientAuth.getScope()) {
            log.debug("Scope:{}", permissionName);
            Permission permission = permissionServices.getPermissionByName(permissionName);
            if (permission != null) {
                scopes.add(permission.getDescription());

                if (validity == 0 || permission.getAccessTokenValiditySeconds() < validity) {
                    validity = permission.getAccessTokenValiditySeconds();
                }

            } else {
                log.warn("Unknown permission provided for client {}: {}", clientAuth.getClientId(),
                        permissionName);
            }
        }
    } else {
        log.warn("The request holds no scope parameter");
    }

    String clientName = client.getName();

    model.put("hsaId", clientAuth.getClientId());
    model.put("auth_request", clientAuth);
    model.put("scopes", scopes);
    model.put("client", client);
    model.put("clientName", clientName);
    model.put("organization", client.getOrganization());
    log.debug("returning from getAccessConfirmation");
    return new ModelAndView(".access_confirmation", model);
}

From source file:org.musicrecital.service.UserSecurityAdvice.java

/**
 * Method to enforce security and only allow administrators to modify users. Regular
 * users are allowed to modify themselves.
 *
 * @param method the name of the method executed
 * @param args   the arguments to the method
 * @param target the target class/*w  w  w  .j a  v a 2 s. c o m*/
 * @throws Throwable thrown when args[0] is null or not a User object
 */
public void before(Method method, Object[] args, Object target) throws Throwable {
    SecurityContext ctx = SecurityContextHolder.getContext();

    if (ctx.getAuthentication() != null) {
        Authentication auth = ctx.getAuthentication();
        boolean administrator = false;
        Collection<? extends GrantedAuthority> roles = auth.getAuthorities();
        for (GrantedAuthority role : roles) {
            if (role.getAuthority().equals(Constants.ADMIN_ROLE)) {
                administrator = true;
                break;
            }
        }

        User user = (User) args[0];

        AuthenticationTrustResolver resolver = new AuthenticationTrustResolverImpl();
        // allow new users to signup - this is OK b/c Signup doesn't allow setting of roles
        boolean signupUser = resolver.isAnonymous(auth);

        if (!signupUser) {
            UserManager userManager = (UserManager) target;
            User currentUser = getCurrentUser(auth, userManager);

            if (user.getId() != null && !user.getId().equals(currentUser.getId()) && !administrator) {
                log.warn("Access Denied: '" + currentUser.getUsername() + "' tried to modify '"
                        + user.getUsername() + "'!");
                throw new AccessDeniedException(ACCESS_DENIED);
            } else if (user.getId() != null && user.getId().equals(currentUser.getId()) && !administrator) {
                // get the list of roles the user is trying add
                Set<String> userRoles = new HashSet<String>();
                if (user.getRoles() != null) {
                    for (Object o : user.getRoles()) {
                        Role role = (Role) o;
                        userRoles.add(role.getName());
                    }
                }

                // get the list of roles the user currently has
                Set<String> authorizedRoles = new HashSet<String>();
                for (GrantedAuthority role : roles) {
                    authorizedRoles.add(role.getAuthority());
                }

                // if they don't match - access denied
                // regular users aren't allowed to change their roles
                if (!CollectionUtils.isEqualCollection(userRoles, authorizedRoles)) {
                    log.warn("Access Denied: '" + currentUser.getUsername()
                            + "' tried to change their role(s)!");
                    throw new AccessDeniedException(ACCESS_DENIED);
                }
            }
        } else {
            if (log.isDebugEnabled()) {
                log.debug("Registering new user '" + user.getUsername() + "'");
            }
        }
    }
}

From source file:org.devgateway.toolkit.forms.wicket.SSAuthenticatedWebSession.java

/**
 * Adds effective roles to Wicket {@link Roles} object. It does so by
 * getting authorities from {@link Authentication#getAuthorities()} and
 * building effective roles list by taking in account role hierarchy.
 *
 * @param roles/*from   w w  w .j av  a2 s  .c o m*/
 * @param authentication
 */
private void addRolesFromAuthentication(final Roles roles, final Authentication authentication) {
    Collection<? extends GrantedAuthority> authorities = authentication.getAuthorities();
    for (GrantedAuthority authority : roleHierarchy.getReachableGrantedAuthorities(authorities)) {
        roles.add(authority.getAuthority());
    }
}

From source file:com.goodhuddle.huddle.web.HuddleGlobalInterceptor.java

@Override
public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler)
        throws Exception {

    // anything under '/_huddles/' is not specific to a Huddle and is allowed at any time
    if (request.getRequestURI().startsWith("/_huddles")
            || request.getRequestURI().startsWith("/error/huddle-not-found")
            || request.getRequestURI().startsWith("/webhooks")) {
        return true;
    }//from   ww  w.  j  a v a  2s  .co  m

    Huddle huddle = huddleService.getHuddle();
    if (huddle == null) {
        if (huddleService.getHuddles().size() == 0) {
            response.sendRedirect("/_huddles/create");
        } else {
            response.sendRedirect("/error/huddle-not-found");
        }
        return false;
    }

    // check if admin setup wizard has been completed
    if (!huddle.isSetupWizardComplete()) {
        if (StringUtils.isNotBlank(request.getRequestURI()) && (request.getRequestURI().endsWith("/not-setup")
                || request.getRequestURI().startsWith("/admin")
                || request.getRequestURI().startsWith("/api"))) {
            return true;
        } else {
            response.sendRedirect("/not-setup");
            return false;
        }
    }

    // check if in coming soon mode
    Authentication auth = SecurityContextHolder.getContext().getAuthentication();
    boolean isAdmin = false;
    if (auth != null) {
        for (GrantedAuthority grantedAuthority : auth.getAuthorities()) {
            if (Permissions.Admin.access.equals(grantedAuthority.getAuthority())) {
                isAdmin = true;
                break;
            }
        }
    }

    if (huddle.isComingSoon() && !isAdmin) {
        if (StringUtils.isNotBlank(request.getRequestURI()) && (request.getRequestURI().endsWith("/not-setup")
                || request.getRequestURI().startsWith("/coming-soon")
                || request.getRequestURI().startsWith("/admin") || request.getRequestURI().startsWith("/error")
                || request.getRequestURI().startsWith("/api"))) {
            return true;
        } else {
            response.sendRedirect("/coming-soon");
            return false;
        }
    }

    return true;
}