Java Code Examples for org.apache.cxf.configuration.security.AuthorizationPolicy#getUserName()

The following examples show how to use org.apache.cxf.configuration.security.AuthorizationPolicy#getUserName() . You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example. You may check out the related API usage on the sidebar.
Example 1
Source File: AuthPolicyValidatingInterceptor.java    From cxf with Apache License 2.0 6 votes vote down vote up
public void handleMessage(Message message) throws Fault {

        AuthorizationPolicy policy = message.get(AuthorizationPolicy.class);
        if (policy == null || policy.getUserName() == null || policy.getPassword() == null) {
            String name = null;
            if (policy != null) {
                name = policy.getUserName();
            }
            org.apache.cxf.common.i18n.Message errorMsg =
                new org.apache.cxf.common.i18n.Message("NO_USER_PASSWORD",
                                                       BUNDLE,
                                                       name);
            LOG.warning(errorMsg.toString());
            throw new SecurityException(errorMsg.toString());
        }

        try {
            super.validate(message);
        } catch (Exception ex) {
            throw new Fault(ex);
        }
    }
 
Example 2
Source File: BasicAuthFilter.java    From cxf-fediz with Apache License 2.0 6 votes vote down vote up
public void filter(ContainerRequestContext requestContext) throws IOException {
    Message message = JAXRSUtils.getCurrentMessage();
    AuthorizationPolicy policy = message.get(AuthorizationPolicy.class);

    if (policy == null || policy.getUserName() == null || policy.getPassword() == null) {
        requestContext.abortWith(
            Response.status(401).header("WWW-Authenticate", "Basic realm=\"IdP\"").build());
        return;
    }

    try {
        super.validate(message);
    } catch (Exception ex) {
        throw ExceptionUtils.toInternalServerErrorException(ex, null);
    }
}
 
Example 3
Source File: DefaultLogEventMapper.java    From cxf with Apache License 2.0 6 votes vote down vote up
private String getPrincipal(Message message) {
    String principal = getJAASPrincipal();
    if (principal != null) {
        return principal;
    }
    SecurityContext sc = message.get(SecurityContext.class);
    if (sc != null && sc.getUserPrincipal() != null) {
        return sc.getUserPrincipal().getName();
    }

    AuthorizationPolicy authPolicy = message.get(AuthorizationPolicy.class);
    if (authPolicy != null) {
        return authPolicy.getUserName();
    }
    return null;
}
 
Example 4
Source File: WSS4JBasicAuthFilter.java    From cxf with Apache License 2.0 6 votes vote down vote up
public void filter(ContainerRequestContext requestContext) throws IOException {
    if (requestContext.getUriInfo().getPath().contains(WellKnownService.WELL_KNOWN_PATH)) {
        return;
    }

    Message message = JAXRSUtils.getCurrentMessage();
    AuthorizationPolicy policy = message.get(AuthorizationPolicy.class);

    if (policy == null || policy.getUserName() == null || policy.getPassword() == null) {
        requestContext.abortWith(
            Response.status(401).header("WWW-Authenticate", "Basic realm=\"IdP\"").build());
        return;
    }

    try {
        super.validate(message);
    } catch (Exception ex) {
        throw ExceptionUtils.toInternalServerErrorException(ex, null);
    }
}
 
Example 5
Source File: BasicAuthInInterceptor.java    From yes-cart with Apache License 2.0 5 votes vote down vote up
@Override
public void handleMessage(final SoapMessage message) throws Fault {
    try {
        final Object policy = message.get(AuthorizationPolicy.class);

        if (policy instanceof AuthorizationPolicy) {

            final AuthorizationPolicy auth = (AuthorizationPolicy) policy;

            Authentication authentication = new UsernamePasswordAuthenticationToken(
                    auth.getUserName(),
                    auth.getPassword()
            );
            LOG.debug("Receiving WS request from user {}", auth.getUserName());
            authentication = authenticationManager.authenticate(authentication);
            SecurityContextHolder.getContext().setAuthentication(authentication);

        } else {
            throw new BadCredentialsException("BasicAuth is required");
        }


    } catch (RuntimeException ex) {
        LOG.error(ex.getMessage(), ex);
        throw ex;
    }
}
 
Example 6
Source File: GeofenceAuthenticationInterceptor.java    From geofence with GNU General Public License v2.0 5 votes vote down vote up
@Override
public void handleMessage(Message message) throws Fault
{

    LOGGER.info("In handleMessage");
    LOGGER.info("Message --> " + message);

    String name = null;
    String password = null;

    AuthUser user = null;

    AuthorizationPolicy policy = (AuthorizationPolicy) message.get(AuthorizationPolicy.class);
    if (policy != null)
    {
        name = policy.getUserName();
        password = policy.getPassword();

        LOGGER.info("Requesting user: " + name);
        // TODO: read user from DB
        // if user and pw do not match, throw new AuthenticationException("Unauthorized");

        user = new AuthUser();
        user.setName(name);

    }
    else
    {
        LOGGER.info("No requesting user -- GUEST access");
    }

    GeofenceSecurityContext securityContext = new GeofenceSecurityContext();
    GeofencePrincipal principal = (user != null) ? new GeofencePrincipal(user) : GeofencePrincipal.createGuest();
    securityContext.setPrincipal(principal);

    message.put(SecurityContext.class, securityContext);
}
 
Example 7
Source File: AuthenticationHandler.java    From geofence with GNU General Public License v2.0 5 votes vote down vote up
@Override
public void handleMessage(Message message) throws Fault
{
    AuthorizationPolicy policy = (AuthorizationPolicy) message.get(AuthorizationPolicy.class);

    //
    // TODO: To manage the public access (guest).
    //
    if (policy == null)
    {
        sendErrorResponse(message, HttpURLConnection.HTTP_UNAUTHORIZED);

        return;
    }

    String username = policy.getUserName();
    String password = policy.getPassword();

    if (isAuthenticated(username, password))
    {
        // ////////////////////////////////////////
        // let request to continue
        // ////////////////////////////////////////
        return;
    }
    else
    {
        // /////////////////////////////////////////////////////////////////////
        // authentication failed, request the authetication,
        // add the realm name if needed to the value of WWW-Authenticate
        // /////////////////////////////////////////////////////////////////////
        sendErrorResponse(message, HttpURLConnection.HTTP_UNAUTHORIZED);

        return;
    }
}
 
Example 8
Source File: AuthPolicyValidatingInterceptor.java    From steady with Apache License 2.0 5 votes vote down vote up
public void handleMessage(Message message) throws Fault {

        AuthorizationPolicy policy = message.get(AuthorizationPolicy.class);
        if (policy == null || policy.getUserName() == null || policy.getPassword() == null) {
            String name = null;
            String password = null;
            if (policy != null) {
                name = policy.getUserName();
                password = policy.getPassword();
            }
            org.apache.cxf.common.i18n.Message errorMsg = 
                new org.apache.cxf.common.i18n.Message("NO_USER_PASSWORD", 
                                                       BUNDLE, 
                                                       name, password);
            LOG.warning(errorMsg.toString());
            throw new SecurityException(errorMsg.toString());
        }
        
        try {
            UsernameToken token = convertPolicyToToken(policy);
            Credential credential = new Credential();
            credential.setUsernametoken(token);
            validator.validateWithSTS(credential, message);
        } catch (Exception ex) {
            throw new Fault(ex);
        }
    }
 
Example 9
Source File: AuthPolicyValidatingInterceptor.java    From steady with Apache License 2.0 5 votes vote down vote up
public void handleMessage(Message message) throws Fault {

        AuthorizationPolicy policy = message.get(AuthorizationPolicy.class);
        if (policy == null || policy.getUserName() == null || policy.getPassword() == null) {
            String name = null;
            String password = null;
            if (policy != null) {
                name = policy.getUserName();
                password = policy.getPassword();
            }
            org.apache.cxf.common.i18n.Message errorMsg = 
                new org.apache.cxf.common.i18n.Message("NO_USER_PASSWORD", 
                                                       BUNDLE, 
                                                       name, password);
            LOG.warning(errorMsg.toString());
            throw new SecurityException(errorMsg.toString());
        }
        
        try {
            UsernameToken token = convertPolicyToToken(policy);
            Credential credential = new Credential();
            credential.setUsernametoken(token);
            validator.validateWithSTS(credential, message);
        } catch (Exception ex) {
            throw new Fault(ex);
        }
    }
 
Example 10
Source File: AuthPolicyValidatingInterceptor.java    From steady with Apache License 2.0 5 votes vote down vote up
public void handleMessage(Message message) throws Fault {

        AuthorizationPolicy policy = message.get(AuthorizationPolicy.class);
        if (policy == null || policy.getUserName() == null || policy.getPassword() == null) {
            String name = null;
            String password = null;
            if (policy != null) {
                name = policy.getUserName();
                password = policy.getPassword();
            }
            org.apache.cxf.common.i18n.Message errorMsg = 
                new org.apache.cxf.common.i18n.Message("NO_USER_PASSWORD", 
                                                       BUNDLE, 
                                                       name, password);
            LOG.warning(errorMsg.toString());
            throw new SecurityException(errorMsg.toString());
        }
        
        try {
            UsernameToken token = convertPolicyToToken(policy);
            Credential credential = new Credential();
            credential.setUsernametoken(token);
            validator.validateWithSTS(credential, message);
        } catch (Exception ex) {
            throw new Fault(ex);
        }
    }
 
Example 11
Source File: WSS4JBasicAuthValidator.java    From cxf with Apache License 2.0 5 votes vote down vote up
protected void validate(Message message) throws WSSecurityException {

        AuthorizationPolicy policy = message.get(AuthorizationPolicy.class);
        if (policy == null || policy.getUserName() == null || policy.getPassword() == null) {
            String name = null;
            if (policy != null) {
                name = policy.getUserName();
            }
            String errorMsg = "No user name and/or password is available, name: " + name;
            LOG.warning(errorMsg);
            throw new SecurityException(errorMsg);
        }

        UsernameToken token = convertPolicyToToken(policy);
        Credential credential = new Credential();
        credential.setUsernametoken(token);

        RequestData data = new RequestData();
        data.setMsgContext(message);
        data.setCallbackHandler(callbackHandler);
        credential = getValidator().validate(credential, data);

        // Create a Principal/SecurityContext
        SecurityContext sc = null;
        if (credential != null && credential.getPrincipal() != null) {
            sc = createSecurityContext(message, credential);
        } else {
            Principal p = new WSUsernameTokenPrincipalImpl(policy.getUserName(), false);
            ((WSUsernameTokenPrincipalImpl)p).setPassword(policy.getPassword());
            sc = createSecurityContext(p);
        }

        message.put(SecurityContext.class, sc);
    }
 
Example 12
Source File: BearerAuthSupplier.java    From cxf with Apache License 2.0 5 votes vote down vote up
private boolean refreshAccessToken(AuthorizationPolicy authPolicy) {
    ClientAccessToken at = getClientAccessToken();
    if (at.getRefreshToken() == null) {
        return false;
    }
    // Client id and secret are needed to refresh the tokens
    // AuthorizationPolicy can hold them by default, Consumer can also be injected into this supplier
    // and checked if the policy is null.
    // Client TLS authentication is also fine as an alternative authentication mechanism,
    // how can we check here that a 2-way TLS has been set up ?
    Consumer theConsumer = consumer;
    if (theConsumer == null
        && authPolicy != null && authPolicy.getUserName() != null && authPolicy.getPassword() != null) {
        theConsumer = new Consumer(authPolicy.getUserName(), authPolicy.getPassword());
        return false;
    }
    if (theConsumer == null) {
        return false;
    }
    // Can WebCient be safely constructed at HttpConduit initialization time ?
    // If yes then createAccessTokenServiceClient() can be called inside
    // setAccessTokenServiceUri, though given that the token refreshment would
    // not be done on every request the current approach is quite reasonable

    WebClient accessTokenService = createAccessTokenServiceClient();
    setClientAccessToken(OAuthClientUtils.refreshAccessToken(accessTokenService, theConsumer, at));
    return true;
}
 
Example 13
Source File: DefaultBasicAuthSupplier.java    From cxf with Apache License 2.0 5 votes vote down vote up
public String getAuthorization(AuthorizationPolicy  authPolicy,
                               URI currentURI,
                               Message message,
                               String fullHeader) {
    if (authPolicy.getUserName() != null && authPolicy.getPassword() != null) {
        boolean encodeBasicAuthWithIso8859 = PropertyUtils.isTrue(
            message.getContextualProperty(ENCODE_BASIC_AUTH_WITH_ISO8859));
        return getBasicAuthHeader(authPolicy.getUserName(),
                                  authPolicy.getPassword(),
                                  encodeBasicAuthWithIso8859);
    }
    return null;
}
 
Example 14
Source File: CallbackHandlerProviderAuthPol.java    From cxf with Apache License 2.0 5 votes vote down vote up
@Override
public CallbackHandler create(Message message) {
    AuthorizationPolicy policy = message.get(AuthorizationPolicy.class);
    if (policy == null) {
        return null;
    }
    return new NamePasswordCallbackHandler(policy.getUserName(), policy.getPassword());
}
 
Example 15
Source File: BasicAuthFilter.java    From cxf-fediz with Apache License 2.0 5 votes vote down vote up
public void filter(ContainerRequestContext requestContext) throws IOException {
    Message message = JAXRSUtils.getCurrentMessage();
    AuthorizationPolicy policy = message.get(AuthorizationPolicy.class);

    if (policy == null || policy.getUserName() == null || policy.getPassword() == null) {
        requestContext.abortWith(
            Response.status(401).header("WWW-Authenticate", "Basic realm=\"IdP\"").build());
        return;
    }

    try {
        UsernameToken token = convertPolicyToToken(policy);
        Credential credential = new Credential();
        credential.setUsernametoken(token);

        RequestData data = new RequestData();
        data.setMsgContext(message);
        data.setCallbackHandler(callbackHandler);
        UsernameTokenValidator validator = new UsernameTokenValidator();
        credential = validator.validate(credential, data);

        // Create a Principal/SecurityContext
        Principal p = null;
        if (credential != null && credential.getPrincipal() != null) {
            p = credential.getPrincipal();
        } else {
            p = new WSUsernameTokenPrincipalImpl(policy.getUserName(), false);
            ((WSUsernameTokenPrincipalImpl)p).setPassword(policy.getPassword());
        }
        message.put(SecurityContext.class, createSecurityContext(p));
    } catch (Exception ex) {
        requestContext.abortWith(
            Response.status(401).header("WWW-Authenticate", "Basic realm=\"IdP\"").build());
    }
}
 
Example 16
Source File: AuthPolicyValidatingInterceptor.java    From steady with Apache License 2.0 5 votes vote down vote up
public void handleMessage(Message message) throws Fault {

        AuthorizationPolicy policy = message.get(AuthorizationPolicy.class);
        if (policy == null || policy.getUserName() == null || policy.getPassword() == null) {
            String name = null;
            String password = null;
            if (policy != null) {
                name = policy.getUserName();
                password = policy.getPassword();
            }
            org.apache.cxf.common.i18n.Message errorMsg = 
                new org.apache.cxf.common.i18n.Message("NO_USER_PASSWORD", 
                                                       BUNDLE, 
                                                       name, password);
            LOG.warning(errorMsg.toString());
            throw new SecurityException(errorMsg.toString());
        }
        
        try {
            UsernameToken token = convertPolicyToToken(policy);
            Credential credential = new Credential();
            credential.setUsernametoken(token);
            validator.validateWithSTS(credential, message);
        } catch (Exception ex) {
            throw new Fault(ex);
        }
    }
 
Example 17
Source File: AbstractAuthFilter.java    From cxf with Apache License 2.0 4 votes vote down vote up
/**
 * Authenticates the third-party consumer and returns
 * {@link OAuthInfo} bean capturing the information about the request.
 * @param req http request
 * @return OAuth info
 * @see OAuthInfo
 * @throws Exception
 * @throws OAuthProblemException
 */
protected OAuthInfo handleOAuthRequest(HttpServletRequest req) throws
    Exception, OAuthProblemException {
    if (LOG.isLoggable(Level.FINE)) {
        LOG.log(Level.FINE, "OAuth security filter for url: {0}", req.getRequestURL());
    }

    AccessToken accessToken = null;
    Client client = null;

    OAuthMessage oAuthMessage = OAuthServlet.getMessage(new CustomHttpServletWrapper(req),
                                                        OAuthServlet.getRequestURL(req));
    if (oAuthMessage.getParameter(OAuth.OAUTH_TOKEN) != null) {
        oAuthMessage.requireParameters(REQUIRED_PARAMETERS);

        accessToken = dataProvider.getAccessToken(oAuthMessage.getToken());

        //check if access token is not null
        if (accessToken == null) {
            LOG.warning("Access token is unavailable");
            throw new OAuthProblemException(OAuth.Problems.TOKEN_REJECTED);
        }
        client = accessToken.getClient();

        OAuthUtils.validateMessage(oAuthMessage, client, accessToken,
                                   dataProvider, validator);
    } else {
        String consumerKey = null;
        String consumerSecret = null;

        String authHeader = oAuthMessage.getHeader("Authorization");
        if (authHeader != null) {
            if (authHeader.startsWith("OAuth")) {
                consumerKey = oAuthMessage.getParameter(OAuth.OAUTH_CONSUMER_KEY);
                consumerSecret = oAuthMessage.getParameter(OAuthConstants.OAUTH_CONSUMER_SECRET);
            } else if (authHeader.startsWith("Basic")) {
                AuthorizationPolicy policy = getAuthorizationPolicy(authHeader);
                if (policy != null) {
                    consumerKey = policy.getUserName();
                    consumerSecret = policy.getPassword();
                }
            }
        }

        if (consumerKey != null) {
            client = dataProvider.getClient(consumerKey);
        }
        if (client == null) {
            LOG.warning("Client is invalid");
            throw new OAuthProblemException(OAuth.Problems.CONSUMER_KEY_UNKNOWN);
        }

        if (consumerSecret != null && !consumerSecret.equals(client.getSecretKey())) {
            LOG.warning("Client secret is invalid");
            throw new OAuthProblemException(OAuth.Problems.CONSUMER_KEY_UNKNOWN);
        }
        OAuthUtils.validateMessage(oAuthMessage, client, null,
                                   dataProvider, validator);
        accessToken = client.getPreAuthorizedToken();
        if (accessToken == null || !accessToken.isPreAuthorized()) {
            LOG.warning("Preauthorized access token is unavailable");
            throw new OAuthProblemException(OAuth.Problems.TOKEN_REJECTED);
        }
    }

    List<OAuthPermission> permissions = accessToken.getScopes();
    List<OAuthPermission> matchingPermissions = new ArrayList<>();

    for (OAuthPermission perm : permissions) {
        boolean uriOK = checkRequestURI(req, perm.getUris());
        boolean verbOK = checkHttpVerb(req, perm.getHttpVerbs());
        if (uriOK && verbOK) {
            matchingPermissions.add(perm);
        }
    }

    if (!permissions.isEmpty() && matchingPermissions.isEmpty()) {
        String message = "Client has no valid permissions";
        LOG.warning(message);
        throw new OAuthProblemException(message);
    }
    return new OAuthInfo(accessToken, matchingPermissions);

}