Example usage for org.springframework.security.oauth2.provider OAuth2Authentication isClientOnly

List of usage examples for org.springframework.security.oauth2.provider OAuth2Authentication isClientOnly

Introduction

In this page you can find the example usage for org.springframework.security.oauth2.provider OAuth2Authentication isClientOnly.

Prototype

public boolean isClientOnly() 

Source Link

Document

Convenience method to check if there is a user associated with this token, or just a client application.

Usage

From source file:ch.hortis.mongodb.training.blog.oauth.AdminResource.java

private void checkResourceOwner(String user, Principal principal) {
    if (principal instanceof OAuth2Authentication) {
        OAuth2Authentication authentication = (OAuth2Authentication) principal;
        if (!authentication.isClientOnly() && !user.equals(principal.getName())) {
            throw new AccessDeniedException(
                    String.format("User '%s' cannot obtain tokens for user '%s'", principal.getName(), user));
        }//  w  w w . j  av a 2s.c o m
    }
}

From source file:org.cloudfoundry.identity.uaa.security.DefaultSecurityContextAccessor.java

@Override
public String getAuthenticationInfo() {
    Authentication a = SecurityContextHolder.getContext().getAuthentication();

    if (a instanceof OAuth2Authentication) {
        OAuth2Authentication oauth = ((OAuth2Authentication) a);

        String info = getClientId();
        if (!oauth.isClientOnly()) {
            info = info + "; " + a.getName() + "; " + getUserId();
        }/*from   w  w w .jav  a  2 s .co  m*/

        return info;
    } else {
        return a.getName();
    }
}

From source file:org.openlmis.fulfillment.util.AuthenticationHelper.java

/**
 * Method returns current user based on Spring context
 * and fetches his data from reference-data service.
 *
 * @return UserDto entity of current user.
 * @throws AuthenticationException if user cannot be found.
 *///from   w  ww.  j a v  a  2s.  c  o  m
public UserDto getCurrentUser() {
    OAuth2Authentication authentication = (OAuth2Authentication) SecurityContextHolder.getContext()
            .getAuthentication();
    UserDto user = null;

    if (!authentication.isClientOnly()) {
        UUID userId = (UUID) authentication.getPrincipal();
        user = userReferenceDataService.findOne(userId);

        if (user == null) {
            throw new AuthenticationException(USER_NOT_FOUND, userId.toString());
        }
    }

    return user;
}

From source file:org.cloudfoundry.identity.uaa.oauth.DefaultTokenConverter.java

@Override
public Map<String, ?> convertAccessToken(OAuth2AccessToken token, OAuth2Authentication authentication) {
    Map<String, Object> response = new HashMap<String, Object>();
    AuthorizationRequest clientToken = authentication.getAuthorizationRequest();

    if (!authentication.isClientOnly()) {
        response.putAll(userTokenConverter.convertUserAuthentication(authentication.getUserAuthentication()));
    }/*from   www  .j  a  v  a2 s. c o m*/

    response.put(OAuth2AccessToken.SCOPE, token.getScope());
    if (token.getAdditionalInformation().containsKey(JwtTokenEnhancer.TOKEN_ID)) {
        response.put(JwtTokenEnhancer.TOKEN_ID,
                token.getAdditionalInformation().get(JwtTokenEnhancer.TOKEN_ID));
    }

    if (token.getExpiration() != null) {
        response.put("exp", token.getExpiration().getTime() / 1000);
    }

    response.putAll(token.getAdditionalInformation());

    response.put("client_id", clientToken.getClientId());
    if (clientToken.getResourceIds() != null && !clientToken.getResourceIds().isEmpty()) {
        response.put("aud", clientToken.getResourceIds());
    }
    return response;
}

From source file:org.cloudfoundry.identity.uaa.oauth.TokenAdminEndpoints.java

private void checkClient(String client, Principal principal) {
    if (principal instanceof OAuth2Authentication) {
        OAuth2Authentication authentication = (OAuth2Authentication) principal;
        if (!authentication.isClientOnly() || !client.equals(principal.getName()) && !isAdmin(principal)) {
            throw new AccessDeniedException(String.format("Client '%s' cannot obtain tokens for client '%s'",
                    principal.getName(), client));
        }/*  ww  w. j a  v a 2s. c  o m*/
    }
}

From source file:org.cloudfoundry.identity.uaa.oauth.TokenAdminEndpoints.java

private void checkResourceOwner(String user, Principal principal) {
    if (principal instanceof OAuth2Authentication) {
        OAuth2Authentication authentication = (OAuth2Authentication) principal;
        if (!authentication.isClientOnly() && !user.equals(principal.getName())) {
            throw new AccessDeniedException(
                    String.format("User '%s' cannot obtain tokens for user '%s'", principal.getName(), user));
        }//www  . j  a v  a 2  s  .  c  o  m
    } else if (!user.equals(principal.getName())) {
        throw new AccessDeniedException(
                String.format("User '%s' cannot obtain tokens for user '%s'", principal.getName(), user));
    }

}

From source file:org.osiam.resources.controller.MeController.java

/**
 * This method is used to get information about the user who initialised the authorization process.
 * <p/>//from w  ww  .  j  a va 2s. c  om
 * The result should be in json format and look like:
 * <p/>
 * {
 * "id": "73821979327912",
 * "name": "Arthur Dent",
 * "first_name": "Arthur",
 * "last_name": "Dent",
 * "link": "https://www.facebook.com/arthur.dent.167",
 * "username": "arthur.dent.167",
 * "gender": "male",
 * "email": "arthur@dent.de",
 * "timezone": 2,
 * "locale": "en_US",
 * "verified": true,
 * "updated_time": "2012-08-20T08:03:30+0000"
 * }
 * <p/>
 * if some information are not available then ... will happen.
 *
 * @return an object to represent the json format.
 */
@RequestMapping(value = "/**", method = { RequestMethod.GET, RequestMethod.POST })
@ResponseBody
public FacebookInformationConstruct getInformation(HttpServletRequest request) {
    String accessToken = getAccessToken(request);

    OAuth2Authentication oAuth = accessTokenValidationService.loadAuthentication(accessToken);
    if (oAuth.isClientOnly()) {
        throw new ConflictException("Can't return an user. This access token belongs to a client.");
    }

    Authentication userAuthentication = oAuth.getUserAuthentication();

    Object principal = userAuthentication.getPrincipal();
    if (principal instanceof User) {
        User user = (User) principal;
        UserEntity userEntity = userDao.getById(user.getId());
        return new FacebookInformationConstruct(userEntity);
    } else {
        throw new IllegalArgumentException("User was not authenticated with OSIAM.");
    }
}

From source file:org.cloudfoundry.identity.uaa.oauth.UaaAuthenticationKeyGenerator.java

@Override
public String extractKey(OAuth2Authentication authentication) {
    Map<String, Object> values = new LinkedHashMap<String, Object>();
    AuthorizationRequest authorizationRequest = authentication.getAuthorizationRequest();
    if (!authentication.isClientOnly()) {
        values.putAll(userTokenConverter.convertUserAuthentication(authentication.getUserAuthentication()));
    }//from w ww.j a  v  a 2 s  .  c om
    ClientDetails client = clientDetailsService.loadClientByClientId(authorizationRequest.getClientId());
    values.put(CLIENT_ID, client.getClientId());
    if (authorizationRequest.getScope() != null) {
        values.put(SCOPE, OAuth2Utils.formatParameterList(authorizationRequest.getScope()));
    }
    Integer validity = client.getAccessTokenValiditySeconds();
    if (validity != null) {
        values.put(ACCESS_TOKEN_VALIDITY, validity);
    }
    validity = client.getRefreshTokenValiditySeconds();
    if (validity != null && client.getAuthorizedGrantTypes().contains("refresh_token")) {
        values.put(REFRESH_TOKEN_VALIDITY, validity);
    }
    MessageDigest digest;
    try {
        digest = MessageDigest.getInstance("MD5");
    } catch (NoSuchAlgorithmException e) {
        throw new IllegalStateException("MD5 algorithm not available.  Fatal (should be in the JDK).");
    }

    try {
        byte[] bytes = digest.digest(values.toString().getBytes("UTF-8"));
        return String.format("%032x", new BigInteger(1, bytes));
    } catch (UnsupportedEncodingException e) {
        throw new IllegalStateException("UTF-8 encoding not available.  Fatal (should be in the JDK).");
    }
}

From source file:org.cloudfoundry.identity.uaa.audit.event.AbstractUaaEvent.java

protected String getOrigin(Principal principal) {

    if (principal instanceof Authentication) {

        Authentication caller = (Authentication) principal;
        StringBuilder builder = new StringBuilder();
        if (caller instanceof OAuth2Authentication) {
            OAuth2Authentication oAuth2Authentication = (OAuth2Authentication) caller;
            builder.append("client=").append(oAuth2Authentication.getAuthorizationRequest().getClientId());
            if (!oAuth2Authentication.isClientOnly()) {
                builder.append(", ").append("user=").append(oAuth2Authentication.getName());
            }// w  ww  .  jav a  2s .c  o m
        } else {
            builder.append("caller=").append(caller.getName()).append(", ");
        }

        if (caller.getDetails() != null) {
            builder.append(", details=(");
            try {
                @SuppressWarnings("unchecked")
                Map<String, Object> map = mapper.convertValue(caller.getDetails(), Map.class);
                if (map.containsKey("remoteAddress")) {
                    builder.append("remoteAddress=").append(map.get("remoteAddress")).append(", ");
                }
                builder.append("type=").append(caller.getDetails().getClass().getSimpleName());
            } catch (Exception e) {
                // ignore
                builder.append(caller.getDetails());
            }
            builder.append(")");
        }
        return builder.toString();

    }

    return principal == null ? null : principal.getName();

}

From source file:no.imr.common.security.jwt.DefaultAccessTokenConverter.java

public Map<String, ?> convertAccessToken(OAuth2AccessToken token, OAuth2Authentication authentication) {
    Map<String, Object> response = new HashMap<String, Object>();
    OAuth2Request clientToken = authentication.getOAuth2Request();

    if (!authentication.isClientOnly()) {
        response.putAll(userTokenConverter.convertUserAuthentication(authentication.getUserAuthentication()));
    } else {//from w  ww .j  a  va 2  s  .c o m
        if (clientToken.getAuthorities() != null && !clientToken.getAuthorities().isEmpty()) {
            response.put(UserAuthenticationConverter.AUTHORITIES,
                    AuthorityUtils.authorityListToSet(clientToken.getAuthorities()));
        }
    }

    if (token.getScope() != null) {
        response.put(SCOPE, token.getScope());
    }
    if (token.getAdditionalInformation().containsKey(JTI)) {
        response.put(JTI, token.getAdditionalInformation().get(JTI));
    }

    if (token.getExpiration() != null) {
        response.put(EXP, token.getExpiration().getTime() / 1000);
    }

    if (includeGrantType && authentication.getOAuth2Request().getGrantType() != null) {
        response.put(GRANT_TYPE, authentication.getOAuth2Request().getGrantType());
    }

    response.putAll(token.getAdditionalInformation());

    response.put(CLIENT_ID, clientToken.getClientId());
    if (clientToken.getResourceIds() != null && !clientToken.getResourceIds().isEmpty()) {
        response.put(AUD, clientToken.getResourceIds());
    }
    return response;
}