Example usage for org.springframework.security.core Authentication getAuthorities

List of usage examples for org.springframework.security.core Authentication getAuthorities

Introduction

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

Prototype

Collection<? extends GrantedAuthority> getAuthorities();

Source Link

Document

Set by an AuthenticationManager to indicate the authorities that the principal has been granted.

Usage

From source file:de.uni_koeln.spinfo.maalr.login.PostLoginHandler.java

@Override
public void onAuthenticationSuccess(HttpServletRequest request, HttpServletResponse response,
        Authentication authentication) throws IOException, ServletException {

    String dictContext = Configuration.getInstance().getDictContext();

    // Set Session Timeout to one hour
    request.getSession().setMaxInactiveInterval(60 * 60);
    if (authentication != null && authentication instanceof JaasAuthenticationToken) {
        // TODO: Implement something similar for ldap...
        request.getSession().setAttribute("uname", authentication.getName());
    }/*from  w w w .j  ava  2  s .c  om*/
    if (authentication != null && authentication instanceof OpenIDAuthenticationToken) {
        // TODO: Optimize this - inefficient to query for each request...
        MaalrUserInfo userInfo = backend.getByLogin(authentication.getName());
        if (userInfo == null) {
            OpenIDAuthenticationToken token = (OpenIDAuthenticationToken) SecurityContextHolder.getContext()
                    .getAuthentication();
            List<OpenIDAttribute> attributes = token.getAttributes();
            userInfo = new MaalrUserInfo(authentication.getName(), Role.OPENID_2);
            for (OpenIDAttribute openIDAttribute : attributes) {
                if (openIDAttribute.getValues() != null && openIDAttribute.getValues().size() > 0) {
                    if ("axContactEmail".equals(openIDAttribute.getName()) && userInfo.getEmail() == null) {
                        userInfo.setEmail(openIDAttribute.getValues().get(0));
                    }
                    if ("oiContactEmail".equals(openIDAttribute.getName()) && userInfo.getEmail() == null) {
                        userInfo.setEmail(openIDAttribute.getValues().get(0));
                    }
                    if ("axNamePersonFirstName".equals(openIDAttribute.getName())
                            && userInfo.getFirstname() == null) {
                        userInfo.setFirstname(openIDAttribute.getValues().get(0));
                    }
                    if ("axNamePersonLastName".equals(openIDAttribute.getName())
                            && userInfo.getLastname() == null) {
                        userInfo.setLastname(openIDAttribute.getValues().get(0));
                    }
                }
            }
            try {
                backend.insert(userInfo);
            } catch (InvalidUserException e) {
                e.printStackTrace();
            }
        }
        request.getSession().setAttribute("uname", userInfo.getFirstname());
    }
    if (authentication != null) {
        Set<String> roles = AuthorityUtils.authorityListToSet(authentication.getAuthorities());
        if (roles.contains(Constants.Roles.ADMIN_5)) {
            response.sendRedirect(dictContext + "/admin/admin.html");
            return;
        } else if (roles.contains(Constants.Roles.TRUSTED_IN_4)) {
            response.sendRedirect(dictContext + "/editor/editor.html");
            return;
        }
    }
    response.sendRedirect(dictContext + "/index.html");
}

From source file:com.companyname.filters.Oauth2ReAuthenticationFilter.java

public void performFilter(ServletRequest req, ServletResponse res, FilterChain chain)
        throws IOException, ServletException {

    logger.info("Oauth2 Re-Authentication filter starts.");

    HttpServletRequest request = (HttpServletRequest) req;

    Boolean authenticated = true;

    Authentication authentication = SecurityContextHolder.getContext().getAuthentication();

    if (authentication == null) {
        logger.info("user needs to be re-authenticated via oauth2 token stored in cookies");

        logger.info("get access token cookie");
        Cookie accessTokenCookie = getCookie(request, getAccessTokenCookieName());
        logger.info("get refresh token cookie");
        Cookie refreshTokenCookie = getCookie(request, getRefreshTokenCookieName());

        String accessTokenValue = null;
        String refreshTokenValue = null;

        if (refreshTokenCookie != null) {
            refreshTokenValue = accessTokenCookie.getValue();
            logger.info("refresh token cookie is retrieved from cookie with value = " + refreshTokenValue);
        }//from ww  w.  java 2  s  . c  o m

        if (accessTokenCookie != null) {
            accessTokenValue = accessTokenCookie.getValue();
            logger.info("access token cookie is retrieved from cookie with value = " + accessTokenValue);
        }

        if (accessTokenValue != null) {
            authentication = getAuthenticationFromAccessToken(accessTokenValue);
            logger.info("authentication object is obtained successfully via the access token");
        }

        if (authentication != null) {
            /**
            PlatAuthentication appAuthentication
                = (PlatAuthentication) authentication;
            PlatformTokens tokens = new PlatformTokens();
            tokens.setAccessToken(accessTokenValue);
            tokens.setRefreshToken(refreshTokenValue);
            appAuthentication.setTokens(tokens);
            SecurityContextHolder.getContext().setAuthentication(appAuthentication);
            * **/

            if (!authentication.isAuthenticated()) {
                logger.info("Although the authentication object is retrieved via the access token "
                        + " however, it's marked as not authenticated.");
            }

            SecurityContextHolder.getContext().setAuthentication(authentication);
            logger.info("security context is loaded with the user's authentication object");
        } else {
            authenticated = false;
            logger.info("Authentication failure, no authentication is loaded into the security context");
        }

    }

    if (authenticated) {
        Set<String> roles = AuthorityUtils.authorityListToSet(authentication.getAuthorities());

        for (String role : roles) {
            logger.info("role found: " + role);
        }

        if (roles.contains("ROLE_USER")) {
            logger.info("This user has role of ROLE_USER");
            request.getSession().setAttribute("myVale", "myvalue");
        }
        //chain.doFilter(req, res);
    } //else {            
      //HttpServletResponse response = (HttpServletResponse) res;
      //response.sendRedirect("http://localhost.drillmap.com:8080"); // hardcoded for now        
      //}

    chain.doFilter(req, res);

}

From source file:com.liangc.hq.base.service.permissions.BaseSessionInitializationStrategy.java

public void onAuthentication(Authentication authentication, HttpServletRequest request,
        HttpServletResponse response) throws SessionAuthenticationException {
    final boolean debug = log.isDebugEnabled();

    if (debug)/* w ww. j a  va 2s.c o m*/
        log.debug("Initializing UI session parameters...");
    boolean updateRoles = false;
    String username = authentication.getName();

    //If this is an organization authentication (ldap\kerberos) we will add a 'org\' prefix to the
    //user name so we will know it's an organization user
    if (null != authentication.getDetails()
            && (authentication.getDetails() instanceof HQAuthenticationDetails)) {
        HQAuthenticationDetails authDetails = (HQAuthenticationDetails) authentication.getDetails();
        if (authDetails.isUsingExternalAuth()) {
            username = HQConstants.ORG_AUTH_PREFIX + username;
            //If this is a Ldap user we will update his roles
            if (null != authentication.getPrincipal()
                    && authentication.getPrincipal().getClass().getName().contains("Ldap")) {
                updateRoles = true;
            }
        }
    }
    try {
        // The following is logic taken from the old HQ Authentication Filter
        int sessionId = sessionManager.put(authzSubjectManager.findSubjectByName(username));
        HttpSession session = request.getSession();
        ServletContext ctx = session.getServletContext();

        // look up the subject record
        AuthzSubject subj = authzBoss.getCurrentSubject(sessionId);
        boolean needsRegistration = false;

        if (subj == null || updateRoles) {
            try {
                AuthzSubject overlord = authzSubjectManager.getOverlordPojo();
                if (null == subj) {
                    needsRegistration = true;
                    subj = authzSubjectManager.createSubject(overlord, username, true,
                            HQConstants.ApplicationName, "", "", "", "", "", "", false);
                }
                //For LDAP users we first want to remove all the existing 'LDAP' roles and then add the current roles he belongs to.
                //We are doing that because for LDAP users we do an automatic mapping of the roles according to the group the
                //user belongs to, and if the user has been removed or added from some group we want this to be reflected in his roles.
                if (updateRoles) {
                    Collection<RoleValue> roles = roleManager.getRoles(subj, PageControl.PAGE_ALL);
                    for (RoleValue role : roles) {
                        String roleName = role.getName().toLowerCase();
                        if (roleName.startsWith(HQConstants.ORG_AUTH_PREFIX)) {
                            roleManager.removeSubjects(authzSubjectManager.getOverlordPojo(), role.getId(),
                                    new Integer[] { subj.getId() });
                        }
                    }
                }
                //every user has ROLE_HQ_USER.  If other roles assigned, automatically assign them to new user
                if (authentication.getAuthorities().size() > 1) {
                    Collection<Role> roles = roleManager.getAllRoles();
                    for (GrantedAuthority authority : authentication.getAuthorities()) {
                        if (authority.getAuthority().equals("ROLE_HQ_USER")) {
                            continue;
                        }
                        for (Role role : roles) {
                            String roleName = role.getName().toLowerCase();
                            String ldapRoleName = "";
                            if (roleName.startsWith(HQConstants.ORG_AUTH_PREFIX)) {
                                ldapRoleName = roleName.substring(roleName.indexOf(HQConstants.ORG_AUTH_PREFIX)
                                        + HQConstants.ORG_AUTH_PREFIX.length()).trim();
                            }
                            if ((("ROLE_" + role.getName()).equalsIgnoreCase(authority.getAuthority()))
                                    || (("ROLE_" + ldapRoleName).equalsIgnoreCase(authority.getAuthority()))) {
                                roleManager.addSubjects(authzSubjectManager.getOverlordPojo(), role.getId(),
                                        new Integer[] { subj.getId() });
                            }
                        }
                    }
                }
            } catch (ApplicationException e) {
                throw new SessionAuthenticationException("Unable to add user to authorization system");
            }

            sessionId = sessionManager.put(subj);
        } else {
            needsRegistration = subj.getEmailAddress() == null || subj.getEmailAddress().length() == 0;
        }

        userAuditFactory.loginAudit(subj);
        AuthzSubjectValue subject = subj.getAuthzSubjectValue();

        // figure out if the user has a principal
        boolean hasPrincipal = authBoss.isUser(sessionId, subject.getName());
        ConfigResponse preferences = needsRegistration ? new ConfigResponse()
                : getUserPreferences(ctx, sessionId, subject.getId(), authzBoss);
        WebUser webUser = new WebUser(subject, sessionId, preferences, hasPrincipal);

        // Add WebUser to Session
        session.setAttribute(Constants.WEBUSER_SES_ATTR, webUser);

        if (debug)
            log.debug("WebUser object created and stashed in the session");

        // TODO - We should use Spring Security for handling user
        // permissions...
        Map<String, Boolean> userOperationsMap = new HashMap<String, Boolean>();

        if (webUser.getPreferences().getKeys().size() > 0) {
            userOperationsMap = loadUserPermissions(webUser.getSessionId(), authzBoss);
        }

        session.setAttribute(Constants.USER_OPERATIONS_ATTR, userOperationsMap);

        if (debug)
            log.debug("Stashing user operations in the session");

        if (debug && needsRegistration) {
            log.debug("Authentic user but no HQ entity, must have authenticated outside of "
                    + "HQ...needs registration");
        }
    } catch (SessionException e) {
        if (debug) {
            log.debug("Authentication of user {" + username + "} failed due to an session error.");
        }

        throw new SessionAuthenticationException("login.error.application");
    } catch (PermissionException e) {
        if (debug) {
            log.debug("Authentication of user {" + username + "} failed due to an permissions error.");
        }

        throw new SessionAuthenticationException("login.error.application");
    }
}

From source file:de.hska.ld.core.config.security.openidconnect.OIDCSecurityConfig.java

@Override
@SuppressWarnings("unchecked")
protected void configure(HttpSecurity http) throws Exception {
    OIDCAuthenticationFilter oidcFilter = openIdConnectAuthenticationFilter();
    oidcFilter.setAuthenticationSuccessHandler(new AuthenticationSuccessHandler() {
        @Override/* w ww. j  a  v a  2  s .c  o  m*/
        public void onAuthenticationSuccess(HttpServletRequest request, HttpServletResponse response,
                Authentication authentication) throws IOException, ServletException {
            response.sendRedirect(env.getProperty("module.core.oidc.redirect.to.client"));
        }
    });
    oidcFilter.setApplicationEventPublisher(new ApplicationEventPublisher() {
        @Override
        public void publishEvent(ApplicationEvent event) {
            Object source = event.getSource();
            OIDCAuthenticationToken token = null;
            if (source != null) {
                token = (OIDCAuthenticationToken) source;
            }
            if (token != null) {
                Map map = (Map) token.getPrincipal();
                Iterator iterator = map.entrySet().iterator();
                String subId = null;
                String issuer = null;
                if (iterator.hasNext()) {
                    Map.Entry<String, String> entry = (Map.Entry<String, String>) iterator.next();
                    if ("sub".equals(entry.getKey())) {
                        // check if sub id is already present in the database
                        subId = entry.getValue();
                        if (subId == null) {
                            throw new UnsupportedOperationException("No subId found!");
                        }
                    }
                }
                if (iterator.hasNext()) {
                    Map.Entry<String, String> entry = (Map.Entry<String, String>) iterator.next();
                    if ("iss".equals(entry.getKey())) {
                        issuer = entry.getValue();
                        if (!env.getProperty("module.core.oidc.identity.provider.url").equals(issuer)) {
                            throw new UnsupportedOperationException("Wrong or no issuer found!");
                        }
                    }
                }

                User currentUserInDb = userService.findBySubIdAndIssuer(subId, issuer);
                UserInfo oidcUserInfo = ((OIDCAuthenticationToken) source).getUserInfo();

                if (currentUserInDb == null && oidcUserInfo != null) {
                    User savedUser = createNewUserFirstLogin(token, subId, issuer, oidcUserInfo);
                    try {
                        userEventsPublisher.sendUserLoginEvent(savedUser);
                        userEventsPublisher.sendUserFirstLoginEvent(savedUser);
                    } catch (Exception e) {
                        //
                    }
                    LoggingContext.put("user_email", EscapeUtil.escapeJsonForLogging(savedUser.getEmail()));
                    Logger.trace("User logs in for the first time.");
                    LoggingContext.clear();
                } else if (oidcUserInfo != null) {
                    User savedUser = updateUserInformationFromOIDC(token, currentUserInDb, oidcUserInfo);
                    try {
                        userEventsPublisher.sendUserLoginEvent(savedUser);
                    } catch (Exception e) {
                        //
                    }
                    LoggingContext.put("user_email", EscapeUtil.escapeJsonForLogging(savedUser.getEmail()));
                    Logger.trace("User logs in.");
                    LoggingContext.clear();
                } else {
                    // oidc information is null
                    throw new UnsupportedOperationException("No OIDC information found!");
                }
            }
        }

        private User updateUserInformationFromOIDC(OIDCAuthenticationToken token, User currentUserInDb,
                UserInfo oidcUserInfo) {
            // get the current authentication details of the user
            Authentication auth = SecurityContextHolder.getContext().getAuthentication();
            enrichAuthoritiesWithStoredAuthorities(currentUserInDb, auth);

            // check for profile updates since the last login
            String oidcUpdatedTime = token.getUserInfo().getUpdatedTime();
            // oidc time: "20150701_090039"
            // oidc format: "yyyyMMdd_HHmmss"
            SimpleDateFormat sdf = new SimpleDateFormat("yyyyMMdd_HHmmss");
            User savedUser = null;
            try {
                Date date = sdf.parse(oidcUpdatedTime);
                if (currentUserInDb.getEmail() == null
                        || currentUserInDb.getLastupdatedAt().getTime() > date.getTime()) {
                    currentUserInDb.setFullName(oidcUserInfo.getName());
                    currentUserInDb.setEmail(oidcUserInfo.getEmail());
                    savedUser = userService.save(currentUserInDb);
                } else {
                    savedUser = currentUserInDb;
                }
            } catch (ParseException e) {
                e.printStackTrace();
            }
            return savedUser;
        }

        private User createNewUserFirstLogin(OIDCAuthenticationToken token, String subId, String issuer,
                UserInfo oidcUserInfo) {
            // create a new user
            User user = new User();
            // check for colliding user names (via preferred user name)
            String prefferedUsername = oidcUserInfo.getPreferredUsername();
            User userWithGivenPreferredUserName = userService.findByUsername(prefferedUsername);
            int i = 0;
            if (userWithGivenPreferredUserName != null) {
                while (userWithGivenPreferredUserName != null) {
                    prefferedUsername = oidcUserInfo.getPreferredUsername() + "#" + i;
                    userWithGivenPreferredUserName = userService.findByUsername(prefferedUsername);
                }
            }
            user.setUsername(prefferedUsername);

            user.setFullName(oidcUserInfo.getName());
            user.setEmail(oidcUserInfo.getEmail());
            user.setEnabled(true);
            // apply roles
            List<Role> roleList = new ArrayList<Role>();
            Role userRole = roleService.findByName("ROLE_USER");
            if (userRole == null) {
                // create initial roles
                String newUserRoleName = "ROLE_USER";
                userRole = createNewUserRole(newUserRoleName);
                String newAdminRoleName = "ROLE_ADMIN";
                Role adminRole = createNewUserRole(newAdminRoleName);
                // For the first user add the admin role
                roleList.add(adminRole);
            } else {
                roleList.add(userRole);
            }
            user.setRoleList(roleList);
            // A password is required so we set a uuid generated one
            if ("development".equals(env.getProperty("lds.app.instance"))) {
                user.setPassword("pass");
            } else {
                user.setPassword(UUID.randomUUID().toString());
            }
            user.setSubId(subId);
            user.setIssuer(issuer);
            String oidcUpdatedTime = token.getUserInfo().getUpdatedTime();
            // oidc time: "20150701_090039"
            // oidc format: "yyyyMMdd_HHmmss"
            SimpleDateFormat sdf = new SimpleDateFormat("yyyyMMdd_HHmmss");
            try {
                Date date = sdf.parse(oidcUpdatedTime);
                user.setLastupdatedAt(date);
            } catch (ParseException e) {
                e.printStackTrace();
            }

            User savedUser = userService.save(user);

            // update security context
            Authentication auth = SecurityContextHolder.getContext().getAuthentication();
            enrichAuthoritiesWithStoredAuthorities(user, auth);

            return savedUser;
        }

        @Override
        public void publishEvent(Object event) {
            throw new RuntimeException("Publish event call failed not implemented yet.");
        }

        private void enrichAuthoritiesWithStoredAuthorities(User currentUserInDb, Authentication auth) {
            Collection<? extends GrantedAuthority> authorities = auth.getAuthorities();
            final SubjectIssuerGrantedAuthority[] oidcAuthority = new SubjectIssuerGrantedAuthority[1];
            authorities.forEach(authority -> {
                if (authority instanceof SubjectIssuerGrantedAuthority) {
                    // extract the oidc authority information
                    oidcAuthority[0] = (SubjectIssuerGrantedAuthority) authority;
                }
            });

            // create new authorities that includes the authorities stored in the database
            // as well as the oidc authority
            ArrayList<GrantedAuthority> newAuthorities = new ArrayList<GrantedAuthority>();
            newAuthorities.add(oidcAuthority[0]);
            currentUserInDb.getRoleList().forEach(role -> {
                newAuthorities.add(new SimpleGrantedAuthority(role.getName()));
            });
            try {
                Field authoritiesField = AbstractAuthenticationToken.class.getDeclaredField("authorities");
                authoritiesField.setAccessible(true);
                authoritiesField.set(auth, newAuthorities);
            } catch (NoSuchFieldException | IllegalAccessException e) {
                e.printStackTrace();
            }
            // update the authority information in the security context
            SecurityContextHolder.getContext().setAuthentication(auth);
        }

        private Role createNewUserRole(String newRoleName) {
            Role newUserRole = new Role();
            newUserRole.setName(newRoleName);
            return roleService.save(newUserRole);
        }
    });

    http.addFilterBefore(oidcFilter, AbstractPreAuthenticatedProcessingFilter.class).csrf()
            .requireCsrfProtectionMatcher(new RequestMatcher() {
                private Pattern allowedMethods = Pattern.compile("^(GET|HEAD|TRACE|OPTIONS)$");

                private RegexRequestMatcher apiMatcher = new RegexRequestMatcher("/v[0-9]*/.*", null);

                @Override
                public boolean matches(HttpServletRequest request) {
                    // CSRF disabled on allowedMethod
                    if (allowedMethods.matcher(request.getMethod()).matches())
                        return false;

                    // CSRF disabled on api calls
                    if (apiMatcher.matches(request))
                        return false;

                    // CSRF enables for other requests
                    //TODO change later on
                    return false;
                }
            }).and().exceptionHandling().authenticationEntryPoint(authenticationEntryPoint()).and().logout()
            .logoutSuccessHandler(logoutSuccessHandler()).deleteCookies("JSESSIONID")
            .deleteCookies("sessionID");
}

From source file:org.apache.ambari.server.security.authorization.AmbariAuthorizationFilter.java

@Override
public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain)
        throws IOException, ServletException {
    HttpServletRequest httpRequest = (HttpServletRequest) request;
    HttpServletResponse httpResponse = (HttpServletResponse) response;

    String requestURI = httpRequest.getRequestURI();

    SecurityContext context = getSecurityContext();

    Authentication authentication = context.getAuthentication();

    //  If no explicit authenticated user is set, set it to the default user (if one is specified)
    if (authentication == null || authentication instanceof AnonymousAuthenticationToken) {
        Authentication defaultAuthentication = getDefaultAuthentication();
        if (defaultAuthentication != null) {
            context.setAuthentication(defaultAuthentication);
            authentication = defaultAuthentication;
        }//from  w ww . j av a 2  s.  com
    }

    if (authentication == null || !authentication.isAuthenticated()) {
        String token = httpRequest.getHeader(INTERNAL_TOKEN_HEADER);
        if (token != null) {
            context.setAuthentication(new InternalAuthenticationToken(token));
        } else {
            // for view access, we should redirect to the Ambari login
            if (requestURI.matches(VIEWS_CONTEXT_ALL_PATTERN)) {
                String queryString = httpRequest.getQueryString();
                String requestedURL = queryString == null ? requestURI : (requestURI + '?' + queryString);
                String redirectURL = httpResponse.encodeRedirectURL(LOGIN_REDIRECT_BASE + requestedURL);

                httpResponse.sendRedirect(redirectURL);
                return;
            } else {
                httpResponse.sendError(HttpServletResponse.SC_FORBIDDEN, "Authentication required");
            }
        }
    } else if (!authorizationPerformedInternally(requestURI)) {
        boolean authorized = false;

        for (GrantedAuthority grantedAuthority : authentication.getAuthorities()) {
            if (grantedAuthority instanceof AmbariGrantedAuthority) {

                AmbariGrantedAuthority ambariGrantedAuthority = (AmbariGrantedAuthority) grantedAuthority;

                PrivilegeEntity privilegeEntity = ambariGrantedAuthority.getPrivilegeEntity();
                Integer permissionId = privilegeEntity.getPermission().getId();

                // admin has full access
                if (permissionId.equals(PermissionEntity.AMBARI_ADMINISTRATOR_PERMISSION)) {
                    authorized = true;
                    break;
                }

                // clusters require permission
                if (!"GET".equalsIgnoreCase(httpRequest.getMethod())
                        && requestURI.matches(API_CREDENTIALS_AMBARI_PATTERN)) {
                    // Only the administrator can operate on credentials where the alias starts with "ambari."
                    if (permissionId.equals(PermissionEntity.AMBARI_ADMINISTRATOR_PERMISSION)) {
                        authorized = true;
                        break;
                    }
                } else if (requestURI.matches(API_CLUSTERS_ALL_PATTERN)) {
                    if (permissionId.equals(PermissionEntity.CLUSTER_USER_PERMISSION)
                            || permissionId.equals(PermissionEntity.CLUSTER_ADMINISTRATOR_PERMISSION)) {
                        authorized = true;
                        break;
                    }
                } else if (STACK_ADVISOR_REGEX.matcher(requestURI).matches()) {
                    //TODO permissions model doesn't manage stacks api, but we need access to stack advisor to save configs
                    if (permissionId.equals(PermissionEntity.CLUSTER_USER_PERMISSION)
                            || permissionId.equals(PermissionEntity.CLUSTER_ADMINISTRATOR_PERMISSION)) {
                        authorized = true;
                        break;
                    }
                } else if (requestURI.matches(API_VIEWS_ALL_PATTERN)) {
                    // views require permission
                    if (permissionId.equals(PermissionEntity.VIEW_USER_PERMISSION)) {
                        authorized = true;
                        break;
                    }
                } else if (requestURI.matches(API_PERSIST_ALL_PATTERN)) {
                    if (permissionId.equals(PermissionEntity.CLUSTER_ADMINISTRATOR_PERMISSION)) {
                        authorized = true;
                        break;
                    }
                }
            }
        }

        // allow GET for everything except /views, /api/v1/users, /api/v1/groups, /api/v1/ldap_sync_events
        if (!authorized && (!httpRequest.getMethod().equals("GET")
                || requestURI.matches(API_LDAP_SYNC_EVENTS_ALL_PATTERN))) {

            httpResponse.setHeader("WWW-Authenticate", "Basic realm=\"" + realm + "\"");
            httpResponse.sendError(HttpServletResponse.SC_FORBIDDEN,
                    "You do not have permissions to access this resource.");
            httpResponse.flushBuffer();
            return;
        }
    }

    if (AuthorizationHelper.getAuthenticatedName() != null) {
        httpResponse.setHeader("User", AuthorizationHelper.getAuthenticatedName());
    }
    chain.doFilter(request, response);
}

From source file:org.apache.atlas.web.resources.AdminResource.java

@GET
@Path("session")
@Produces(Servlets.JSON_MEDIA_TYPE)//from  w  w  w.  ja v a 2s. co m
public Response getUserProfile() {
    if (LOG.isDebugEnabled()) {
        LOG.debug("==> AdminResource.getUserProfile()");
    }

    Response response;
    Boolean enableTaxonomy = false;
    try {
        if (atlasProperties != null) {
            enableTaxonomy = atlasProperties.getBoolean(isTaxonomyEnabled, false);
        }

        boolean isEntityUpdateAccessAllowed = false;
        boolean isEntityCreateAccessAllowed = false;
        Authentication auth = SecurityContextHolder.getContext().getAuthentication();
        String userName = null;
        Set<String> groups = new HashSet<>();
        if (auth != null) {
            userName = auth.getName();
            Collection<? extends GrantedAuthority> authorities = auth.getAuthorities();
            for (GrantedAuthority c : authorities) {
                groups.add(c.getAuthority());
            }

            isEntityUpdateAccessAllowed = AtlasAuthorizationUtils.isAccessAllowed(AtlasResourceTypes.ENTITY,
                    AtlasActionTypes.UPDATE, userName, groups, httpServletRequest);
            isEntityCreateAccessAllowed = AtlasAuthorizationUtils.isAccessAllowed(AtlasResourceTypes.ENTITY,
                    AtlasActionTypes.CREATE, userName, groups, httpServletRequest);
        }

        JSONObject responseData = new JSONObject();

        responseData.put(isCSRF_ENABLED, AtlasCSRFPreventionFilter.isCSRF_ENABLED);
        responseData.put(BROWSER_USER_AGENT_PARAM, AtlasCSRFPreventionFilter.BROWSER_USER_AGENTS_DEFAULT);
        responseData.put(CUSTOM_METHODS_TO_IGNORE_PARAM, AtlasCSRFPreventionFilter.METHODS_TO_IGNORE_DEFAULT);
        responseData.put(CUSTOM_HEADER_PARAM, AtlasCSRFPreventionFilter.HEADER_DEFAULT);
        responseData.put(isTaxonomyEnabled, enableTaxonomy);
        responseData.put(isEntityUpdateAllowed, isEntityUpdateAccessAllowed);
        responseData.put(isEntityCreateAllowed, isEntityCreateAccessAllowed);
        responseData.put(editableEntityTypes, getEditableEntityTypes(atlasProperties));
        responseData.put("userName", userName);
        responseData.put("groups", groups);

        response = Response.ok(responseData).build();
    } catch (JSONException e) {
        throw new WebApplicationException(Servlets.getErrorResponse(e, Response.Status.INTERNAL_SERVER_ERROR));
    }

    if (LOG.isDebugEnabled()) {
        LOG.debug("<== AdminResource.getUserProfile()");
    }

    return response;
}

From source file:org.apache.atlas.web.security.FileAuthenticationTest.java

@Test
public void testUserRoleMapping() {

    when(authentication.getName()).thenReturn("admin");
    when(authentication.getCredentials()).thenReturn("admin");

    Authentication auth = authProvider.authenticate(authentication);
    LOG.debug(" {}", auth);

    Assert.assertTrue(auth.isAuthenticated());

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

    String role = "";
    for (GrantedAuthority gauth : authorities) {
        role = gauth.getAuthority();// ww  w  . ja v a  2 s . com
    }
    Assert.assertTrue("ADMIN".equals(role));
}

From source file:org.apache.metron.rest.config.KnoxSSOAuthenticationFilterTest.java

@SuppressWarnings("unchecked")
@Test//from ww w  .ja va  2 s.  c  o  m
public void getAuthenticationShouldProperlyPopulateAuthentication() throws Exception {
    LdapTemplate ldapTemplate = mock(LdapTemplate.class);
    KnoxSSOAuthenticationFilter knoxSSOAuthenticationFilter = spy(
            new KnoxSSOAuthenticationFilter("ou=people,dc=hadoop,dc=apache,dc=org", mock(Path.class),
                    "knoxKeyString", "knoxCookie", ldapTemplate));

    HttpServletRequest request = mock(HttpServletRequest.class);

    when(ldapTemplate.search(any(LdapQuery.class), any(AttributesMapper.class)))
            .thenReturn(Arrays.asList("USER", "ADMIN"));

    Authentication authentication = knoxSSOAuthenticationFilter.getAuthentication("userName", request);
    Object[] grantedAuthorities = authentication.getAuthorities().toArray();
    assertEquals("ROLE_USER", grantedAuthorities[0].toString());
    assertEquals("ROLE_ADMIN", grantedAuthorities[1].toString());
    assertEquals("userName", authentication.getName());
}

From source file:org.apache.syncope.core.misc.security.AuthContextUtils.java

public static void updateAuthenticatedUsername(final String newUsername) {
    Authentication auth = SecurityContextHolder.getContext().getAuthentication();

    Authentication newAuth = new UsernamePasswordAuthenticationToken(
            new User(newUsername, "FAKE_PASSWORD", auth.getAuthorities()), auth.getCredentials(),
            auth.getAuthorities());//from  w  ww .ja  v a 2s. c  o m
    SecurityContextHolder.getContext().setAuthentication(newAuth);
}