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

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

Introduction

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

Prototype

@HotSpotIntrinsicCandidate
public final native Class<?> getClass();

Source Link

Document

Returns the runtime class of this Object .

Usage

From source file:com.devicehive.auth.JwtPermissionEvaluator.java

@Override
public boolean hasPermission(Authentication authentication, Object targetDomainObject, Object permission) {
    if (authentication != null && authentication instanceof HiveAuthentication) {
        HiveAuthentication hiveAuthentication = (HiveAuthentication) authentication;
        HivePrincipal hivePrincipal = (HivePrincipal) hiveAuthentication.getPrincipal();
        HiveAction action = HiveAction.valueOf(permission.toString().trim());
        logger.debug("Checking {} for permissions {}", authentication.getName(), hivePrincipal.getActions());
        boolean permissionAllowed = jwtCheckPermissionsHelper.checkPermissions(hivePrincipal, action,
                targetDomainObject);//from w  ww . ja  v  a  2 s .  c o  m
        if (!permissionAllowed) {
            logger.warn("Principal doesn't have required permission {}. Access denied", permission);
            return false;
        }
        logger.info("Successfully checked for permission {}", permission);
        return true;
    }
    logger.error("Can't check access key permission for jwt '{}'", authentication.getClass().getName());
    return true;
}

From source file:sk.lazyman.gizmo.security.GizmoAuthProvider.java

private Authentication authenticateUsingDb(Authentication authentication) throws AuthenticationException {
    String principal = (String) authentication.getPrincipal();
    String password = (String) ((UsernamePasswordAuthenticationToken) authentication).getCredentials();
    User user = userRepository.findUserByName(principal);
    if (user == null) {
        throw new BadCredentialsException("web.security.provider.invalid");
    }//from   ww  w. ja v  a2s . c  o m

    if (user.getPassword() == null || !user.getPassword().equals(GizmoUtils.toSha1(password))) {
        throw new BadCredentialsException("GizmoAuthenticationProvider.userPasswordIncorrect");
    }

    if (!user.isEnabled()) {
        throw new BadCredentialsException("GizmoAuthenticationProvider.userDisabled");
    }

    GizmoPrincipal gizmoPrincipal = new GizmoPrincipal(user);

    LOGGER.debug("User '{}' authenticated ({}), authorities: {}", new Object[] { authentication.getPrincipal(),
            authentication.getClass().getSimpleName(), gizmoPrincipal.getAuthorities() });
    return new UsernamePasswordAuthenticationToken(gizmoPrincipal, null, gizmoPrincipal.getAuthorities());
}

From source file:net.maritimecloud.identityregistry.utils.AccessControlUtil.java

public static boolean hasPermission(String permission) {
    Authentication auth = SecurityContextHolder.getContext().getAuthentication();
    if (auth instanceof KeycloakAuthenticationToken) {
        log.debug("OIDC permission lookup");
        // Keycloak authentication
        KeycloakAuthenticationToken kat = (KeycloakAuthenticationToken) auth;
        KeycloakSecurityContext ksc = (KeycloakSecurityContext) kat.getCredentials();
        Map<String, Object> otherClaims = ksc.getToken().getOtherClaims();
        if (otherClaims.containsKey(AccessControlUtil.PERMISSIONS_PROPERTY_NAME)) {
            String usersPermissions = (String) otherClaims.get(AccessControlUtil.PERMISSIONS_PROPERTY_NAME);
            String[] permissionList = usersPermissions.split(",");
            for (String per : permissionList) {
                if (per.equalsIgnoreCase(permission)) {
                    return true;
                }/*from ww  w . j  a va2s . co m*/
            }
        }
    } else if (auth instanceof PreAuthenticatedAuthenticationToken) {
        log.debug("Certificate permission lookup");
        // Certificate authentication
        PreAuthenticatedAuthenticationToken token = (PreAuthenticatedAuthenticationToken) auth;
        // Check that the permission is granted to this user
        InetOrgPerson person = ((InetOrgPerson) token.getPrincipal());
        Collection<GrantedAuthority> authorities = person.getAuthorities();
        for (GrantedAuthority authority : authorities) {
            String usersPermissions = authority.getAuthority();
            String[] permissionList = usersPermissions.split(",");
            for (String per : permissionList) {
                if (per.equalsIgnoreCase(permission)) {
                    return true;
                }
            }
        }
    } else {
        if (auth != null) {
            log.debug("Unknown authentication method: " + auth.getClass());
        }
    }
    return false;
}

From source file:net.maritimecloud.endorsement.utils.AccessControlUtil.java

public static boolean hasPermission(String permission) {
    Authentication auth = SecurityContextHolder.getContext().getAuthentication();
    if (auth instanceof KeycloakAuthenticationToken) {
        logger.debug("OIDC permission lookup");
        // Keycloak authentication
        KeycloakAuthenticationToken kat = (KeycloakAuthenticationToken) auth;
        KeycloakSecurityContext ksc = (KeycloakSecurityContext) kat.getCredentials();
        Map<String, Object> otherClaims = ksc.getToken().getOtherClaims();
        if (otherClaims.containsKey(AccessControlUtil.PERMISSIONS_PROPERTY_NAME)) {
            String usersPermissions = (String) otherClaims.get(AccessControlUtil.PERMISSIONS_PROPERTY_NAME);
            String[] permissionList = usersPermissions.split(",");
            for (String per : permissionList) {
                if (per.equalsIgnoreCase(permission)) {
                    return true;
                }//from   ww w  .j a  va  2 s.  c om
            }
        }
        /*} else if (auth instanceof PreAuthenticatedAuthenticationToken) {
            logger.debug("Certificate permission lookup");
            // Certificate authentication
            PreAuthenticatedAuthenticationToken token = (PreAuthenticatedAuthenticationToken) auth;
            // Check that the permission is granted to this user
            InetOrgPerson person = ((InetOrgPerson) token.getPrincipal());
            Collection<GrantedAuthority> authorities = person.getAuthorities();
            for (GrantedAuthority authority : authorities) {
        String usersPermissions = authority.getAuthority();
        String[] permissionList = usersPermissions.split(",");
        for (String per : permissionList) {
            if (per.equalsIgnoreCase(permission)) {
                return true;
            }
        }
            }*/
    } else {
        if (auth != null) {
            logger.debug("Unknown authentication method: " + auth.getClass());
        }
    }
    return false;
}

From source file:org.mitre.provenance.openid.OpenIDInterceptorFilter.java

public void doFilter(ServletRequest request, ServletResponse response, FilterChain filterChain)
        throws IOException, ServletException {
    HttpServletRequest httpRequest = (HttpServletRequest) request;
    HttpSession session = httpRequest.getSession();

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

    //Only proceed if we have a logged-in user AND there is no PlusUser in the request
    //already. /*from  w  ww  .  j ava 2s.  c  o m*/
    if (auth != null && session.getAttribute(PLUS_USER) == null) {
        System.err.println("FILTER: checking auth type");
        //If OpenID Connect:
        if (auth instanceof OIDCAuthenticationToken) {
            System.err.println("FILTER: OIDC");
            User user = handle((OIDCAuthenticationToken) auth);
            session.setAttribute(PLUS_USER, user);
        } else if (auth instanceof OpenIDAuthenticationToken) {
            OpenIDAuthenticationToken oidToken = (OpenIDAuthenticationToken) auth;
            String oid2UniqueId = oidToken.getName();

            System.err.println("FILTER: OpenID2 Token ID " + oid2UniqueId + " cred " + oidToken.getCredentials()
                    + " details " + oidToken.getDetails() + " principal " + oidToken.getPrincipal()
                    + " message " + oidToken.getMessage());

            User user = handle(oidToken);
            session.setAttribute(PLUS_USER, user);
        } else
            log.warning("Unrecognized token " + auth.getClass().getName());
    }

    //Continue the filter chain
    filterChain.doFilter(httpRequest, response);
}

From source file:net.maritimecloud.identityregistry.utils.AccessControlUtil.java

public static boolean hasAccessToOrg(String orgMrn) {
    if (orgMrn == null || orgMrn.trim().isEmpty()) {
        log.debug("The orgMrn was empty!");
        return false;
    }//from w w w.j  a  v a 2 s. com
    Authentication auth = SecurityContextHolder.getContext().getAuthentication();
    // First check if the user is a SITE_ADMIN, in which case he gets access.
    for (GrantedAuthority authority : auth.getAuthorities()) {
        String role = authority.getAuthority();
        log.debug("User has role: " + role);
        if ("ROLE_SITE_ADMIN".equals(role)) {
            return true;
        }
    }
    log.debug("User not a SITE_ADMIN");
    // Check if the user is part of the organization
    if (auth instanceof KeycloakAuthenticationToken) {
        log.debug("OIDC authentication in process");
        // Keycloak authentication
        KeycloakAuthenticationToken kat = (KeycloakAuthenticationToken) auth;
        KeycloakSecurityContext ksc = (KeycloakSecurityContext) kat.getCredentials();
        Map<String, Object> otherClaims = ksc.getToken().getOtherClaims();
        if (otherClaims.containsKey(AccessControlUtil.ORG_PROPERTY_NAME)
                && ((String) otherClaims.get(AccessControlUtil.ORG_PROPERTY_NAME)).toLowerCase()
                        .equals(orgMrn.toLowerCase())) {
            log.debug("Entity from org: " + otherClaims.get(AccessControlUtil.ORG_PROPERTY_NAME) + " is in "
                    + orgMrn);
            return true;
        }
        log.debug("Entity from org: " + otherClaims.get(AccessControlUtil.ORG_PROPERTY_NAME) + " is not in "
                + orgMrn);
    } else if (auth instanceof PreAuthenticatedAuthenticationToken) {
        log.debug("Certificate authentication in process");
        // Certificate authentication
        PreAuthenticatedAuthenticationToken token = (PreAuthenticatedAuthenticationToken) auth;
        // Check that the Organization name of the accessed organization and the organization in the certificate is equal
        InetOrgPerson person = ((InetOrgPerson) token.getPrincipal());
        // The O(rganization) value in the certificate is an MRN
        String certOrgMrn = person.getO();
        if (orgMrn.equals(certOrgMrn)) {
            log.debug("Entity with O=" + certOrgMrn + " is in " + orgMrn);
            return true;
        }
        log.debug("Entity with O=" + certOrgMrn + " is not in " + orgMrn);
    } else {
        log.debug("Unknown authentication method: " + auth.getClass());
    }
    return false;
}

From source file:net.maritimecloud.endorsement.utils.AccessControlUtil.java

public static boolean hasAccessToOrg(String orgMrn) {
    if (orgMrn == null || orgMrn.trim().isEmpty()) {
        logger.debug("The orgMrn was empty!");
        return false;
    }//w  w w  .  j  a  v  a 2  s  .co  m
    Authentication auth = SecurityContextHolder.getContext().getAuthentication();
    // First check if the user is a SITE_ADMIN, in which case he gets access.
    /*for (GrantedAuthority authority : auth.getAuthorities()) {
    String role = authority.getAuthority();
    logger.debug("User has role: " + role);
    if ("ROLE_SITE_ADMIN".equals(role)) {
        return true;
    }
    }
    logger.debug("User not a SITE_ADMIN");*/
    // Check if the user is part of the organization
    if (auth instanceof KeycloakAuthenticationToken) {
        logger.debug("OIDC authentication in process");
        // Keycloak authentication
        KeycloakAuthenticationToken kat = (KeycloakAuthenticationToken) auth;
        KeycloakSecurityContext ksc = (KeycloakSecurityContext) kat.getCredentials();
        Map<String, Object> otherClaims = ksc.getToken().getOtherClaims();
        if (otherClaims.containsKey(AccessControlUtil.ORG_PROPERTY_NAME)
                && ((String) otherClaims.get(AccessControlUtil.ORG_PROPERTY_NAME)).toLowerCase()
                        .equals(orgMrn.toLowerCase())) {
            logger.debug("Entity from org: " + otherClaims.get(AccessControlUtil.ORG_PROPERTY_NAME) + " is in "
                    + orgMrn);
            return true;
        }
        logger.debug("Entity from org: " + otherClaims.get(AccessControlUtil.ORG_PROPERTY_NAME) + " is not in "
                + orgMrn);
        /*} else if (auth instanceof PreAuthenticatedAuthenticationToken) {
            logger.debug("Certificate authentication in process");
            // Certificate authentication
            PreAuthenticatedAuthenticationToken token = (PreAuthenticatedAuthenticationToken) auth;
            // Check that the Organization name of the accessed organization and the organization in the certificate is equal
            InetOrgPerson person = ((InetOrgPerson) token.getPrincipal());
            // The O(rganization) value in the certificate is an MRN
            String certOrgMrn = person.getO();
            if (orgMrn.equals(certOrgMrn)) {
        logger.debug("Entity with O=" + certOrgMrn + " is in " + orgMrn);
        return true;
            }
            logger.debug("Entity with O=" + certOrgMrn + " is not in " + orgMrn);*/
    } else {
        if (auth != null) {
            logger.debug("Unknown authentication method: " + auth.getClass());
        }
    }
    return false;
}

From source file:com.evolveum.midpoint.web.security.MidPointAuthenticationProvider.java

@Override
public Authentication authenticate(Authentication authentication) throws AuthenticationException {
    if (StringUtils.isBlank((String) authentication.getPrincipal())) {
        throw new BadCredentialsException("web.security.provider.invalid");
    }/* w  w w. j  a v a  2s .co  m*/

    MidPointPrincipal principal = null;
    try {
        principal = userProfileService.getPrincipal((String) authentication.getPrincipal());
    } catch (ObjectNotFoundException ex) {
        LOGGER.debug("Authentication of user with username '{}' failed: not found: {}", ex.getMessage(), ex);
        throw new BadCredentialsException("web.security.provider.access.denied");
    } catch (Exception ex) {
        LOGGER.error("Can't get user with username '{}'. Unknown error occured, reason {}.",
                new Object[] { authentication.getPrincipal(), ex.getMessage(), ex });
        throw new AuthenticationServiceException("web.security.provider.unavailable");
    }

    Authentication token = null;
    try {
        token = authenticateUser(principal, authentication);
    } catch (BadCredentialsException ex) {
        LOGGER.debug("Authentication of user with username '{}' failed: bad credentials: {}", ex.getMessage(),
                ex);
        throw ex;
    } catch (Exception ex) {
        LOGGER.error("Can't authenticate user '{}': {}",
                new Object[] { authentication.getPrincipal(), ex.getMessage(), ex });
        throw new AuthenticationServiceException("web.security.provider.unavailable");
    }

    LOGGER.debug("User '{}' authenticated ({}), authorities: {}", new Object[] { authentication.getPrincipal(),
            authentication.getClass().getSimpleName(), principal.getAuthorities() });
    return token;
}

From source file:nl.surfnet.coin.api.oauth.OpenConextOauth1TokenServices.java

@Override
protected void storeToken(String value, OAuthProviderTokenImpl token) {
    Assert.notNull(token, "Token cannot be null");
    Assert.notNull(value, "token value cannot be null");
    Authentication userAuthentication = token.getUserAuthentication();
    String userId = null;//from   ww  w  . j  ava 2 s . c o  m
    if (token.isAccessToken()) {
        String consumerKey = token.getConsumerKey();
        /*
         * get the client detail from Janus as we are unable to store them
         * somewhere along the 'road' and we cache this call anyway
         */
        ConsumerDetails consumerDetails = consumerDetailsService.loadConsumerByConsumerKey(consumerKey);
        if (consumerDetails instanceof OpenConextConsumerDetails) {
            OpenConextConsumerDetails extendedBaseConsumerDetails = (OpenConextConsumerDetails) consumerDetails;
            if (userAuthentication instanceof PreAuthenticatedAuthenticationToken) {
                PreAuthenticatedAuthenticationToken pre = (PreAuthenticatedAuthenticationToken) userAuthentication;
                Object principal = pre.getPrincipal();
                if (principal instanceof ClientMetaDataUser) {
                    ((ClientMetaDataUser) principal)
                            .setClientMetaData(extendedBaseConsumerDetails.getClientMetaData());
                    userId = ((ClientMetaDataUser) principal).getUsername();
                } else if (principal instanceof SAMLAuthenticationToken) {
                    ((SAMLAuthenticationToken) principal)
                            .setClientMetaData(extendedBaseConsumerDetails.getClientMetaData());
                    userId = ((SAMLAuthenticationToken) principal).getName();
                } else {
                    throw new RuntimeException(
                            "The principal on the PreAuthenticatedAuthenticationToken is of the type '"
                                    + (principal != null ? principal.getClass() : "null")
                                    + "'. Required is a (sub)class of ClientMetaDataUser or a (sub)class of SAMLAuthenticationToken");
                }
            } else if (userAuthentication instanceof SAMLAuthenticationToken) {
                SAMLAuthenticationToken samlToken = (SAMLAuthenticationToken) userAuthentication;
                samlToken.setClientMetaData(extendedBaseConsumerDetails.getClientMetaData());
                userId = samlToken.getName();
            } else {
                throw new RuntimeException("The userAuthentication is of the type '"
                        + (userAuthentication != null ? userAuthentication.getClass() : "null")
                        + "'. Required is a (sub)class of PreAuthenticatedAuthenticationToken or SAMLAuthenticationToken");
            }
        } else {
            throw new RuntimeException("The consumerDetails is of the type '"
                    + (consumerDetails != null ? consumerDetails.getClass() : "null")
                    + "'. Required is a (sub)class of ExtendedBaseConsumerDetails");
        }
    }
    jdbcTemplate.update(deleteTokenSql, value);
    jdbcTemplate.update(insertTokenSql, value, token.getCallbackUrl(), token.getVerifier(), token.getSecret(),
            token.getConsumerKey(), userId, token.isAccessToken(), token.getTimestamp(),
            SerializationUtils.serialize(userAuthentication));
}

From source file:nl.surfnet.coin.api.AbstractApiController.java

protected ClientMetaData getClientMetaData() {
    Authentication authentication = SecurityContextHolder.getContext().getAuthentication();
    ClientMetaData metaData = null;//from   w  w  w .  j av  a 2s . c  o m
    // oauth2
    if (authentication instanceof OAuth2Authentication) {
        OAuth2Authentication oauth2 = (OAuth2Authentication) authentication;
        String clientId = oauth2.getAuthorizationRequest().getClientId();
        ClientDetails clientDetails = janusClientDetailsService.loadClientByClientId(clientId);
        metaData = ((OpenConextClientDetails) clientDetails).getClientMetaData();
        registerApiVersion("oauth2");
    }
    // oauth1 3-legged
    else if (authentication instanceof PreAuthenticatedAuthenticationToken) {
        PreAuthenticatedAuthenticationToken preAuth = (PreAuthenticatedAuthenticationToken) authentication;
        Object principal = preAuth.getPrincipal();
        if (principal instanceof ClientMetaDataUser) {
            ClientMetaDataUser user = (ClientMetaDataUser) principal;
            metaData = user.getClientMetaData();
            if (metaData == null) {
                Object details = preAuth.getDetails();
                if (details instanceof OAuthAuthenticationDetails) {
                    OAuthAuthenticationDetails authDetails = (OAuthAuthenticationDetails) details;
                    ConsumerDetails consumerDetails = authDetails.getConsumerDetails();
                    if (consumerDetails instanceof OpenConextConsumerDetails) {
                        OpenConextConsumerDetails base = (OpenConextConsumerDetails) consumerDetails;
                        metaData = base.getClientMetaData();
                    }
                }
            }
            registerApiVersion("oauth1-3legged");
        }
    } // oauth1 2-legged
    else if (authentication instanceof ConsumerAuthentication) {
        ConsumerAuthentication conAuth = (ConsumerAuthentication) authentication;
        ConsumerDetails consumerDetails = conAuth.getConsumerDetails();
        if (consumerDetails instanceof OpenConextConsumerDetails) {
            OpenConextConsumerDetails details = (OpenConextConsumerDetails) consumerDetails;
            metaData = details.getClientMetaData();
            registerApiVersion("oauth1-2legged");
        }
    } else if (authentication instanceof SAMLAuthenticationToken) {
        SAMLAuthenticationToken samlToken = (SAMLAuthenticationToken) authentication;
        metaData = samlToken.getClientMetaData();
        registerApiVersion("oauth2");
    } else {
        throw new IllegalArgumentException("Authentication is of unknown class ('"
                + (authentication != null ? authentication.getClass() : "null") + "')");
    }
    Assert.notNull(metaData, "ClientMetaData may not be null for checking ACL's. Authentication is of class ('"
            + (authentication != null ? authentication.getClass() : "null") + "')");
    return metaData;
}