Example usage for org.springframework.security.oauth2.common.util OAuth2Utils CLIENT_ID

List of usage examples for org.springframework.security.oauth2.common.util OAuth2Utils CLIENT_ID

Introduction

In this page you can find the example usage for org.springframework.security.oauth2.common.util OAuth2Utils CLIENT_ID.

Prototype

String CLIENT_ID

To view the source code for org.springframework.security.oauth2.common.util OAuth2Utils CLIENT_ID.

Click Source Link

Document

Constant to use while parsing and formatting parameter maps for OAuth2 requests

Usage

From source file:org.cloudfoundry.identity.uaa.login.util.LocalUaaRestTemplate.java

@Override
protected OAuth2AccessToken acquireAccessToken(OAuth2ClientContext oauth2Context)
        throws UserRedirectRequiredException {
    ClientDetails client = clientDetailsService.loadClientByClientId(getClientId());
    Set<String> scopes = new HashSet<>();
    for (GrantedAuthority authority : client.getAuthorities()) {
        scopes.add(authority.getAuthority());
    }/*from   w  w w  .  jav a  2 s  . co  m*/
    Set<String> resourceIds = new HashSet<>();
    resourceIds.add(Origin.UAA);
    Set<String> responseTypes = new HashSet<>();
    responseTypes.add("token");
    Map<String, String> requestParameters = new HashMap<>();
    requestParameters.put(OAuth2Utils.CLIENT_ID, "login");
    requestParameters.put(OAuth2Utils.GRANT_TYPE, "client_credentials");
    OAuth2Request request = new OAuth2Request(requestParameters, "login",
            (Collection<? extends GrantedAuthority>) Collections.EMPTY_SET, true, scopes, resourceIds, null,
            responseTypes, Collections.EMPTY_MAP);
    OAuth2Authentication authentication = new OAuth2Authentication(request, null);
    OAuth2AccessToken result = tokenServices.createAccessToken(authentication);
    oauth2Context.setAccessToken(result);
    return result;
}

From source file:it.smartcommunitylab.aac.controller.LegacyNativeAuthController.java

protected ModelAndView processNativeAuth(Device device, HttpServletRequest request,
        HttpServletResponse response, String authority) throws UnsupportedEncodingException {
    Map<String, Object> model = new HashMap<String, Object>();
    String clientId = request.getParameter(OAuth2Utils.CLIENT_ID);
    if (clientId == null || clientId.isEmpty()) {
        model.put("message", "Missing client_id");
        return new ModelAndView("oauth_error", model);
    }/*  w w  w.  j a  va  2  s.co m*/
    // each time create new OAuth request
    ClientAppBasic client = clientDetailsAdapter.getByClientId(clientId);
    AACOAuthRequest oauthRequest = new AACOAuthRequest(request, device, client.getScope(),
            client.getDisplayName());

    List<NameValuePair> pairs = URLEncodedUtils
            .parse(URI.create(request.getRequestURI() + "?" + request.getQueryString()), "UTF-8");

    String target = prepareRedirect(request, "/oauth/authorize");
    it.smartcommunitylab.aac.model.User userEntity = providerServiceAdapter.updateNativeUser(authority,
            request.getParameter("token"), toMap(pairs));
    List<GrantedAuthority> list = roleManager.buildAuthorities(userEntity);

    UserDetails user = new User(userEntity.getId().toString(), "", list);
    AbstractAuthenticationToken a = new AACAuthenticationToken(user, null, authority, list);
    a.setDetails(oauthRequest);
    SecurityContextHolder.getContext().setAuthentication(a);

    if (rememberMeServices != null) {
        rememberMeServices.loginSuccess(request, response, a);
    }

    return new ModelAndView("redirect:" + target);
}

From source file:org.mitre.openid.connect.ConnectOAuth2RequestFactory.java

@Override
public AuthorizationRequest createAuthorizationRequest(Map<String, String> inputParams) {

    AuthorizationRequest request = new AuthorizationRequest(inputParams, Collections.<String, String>emptyMap(),
            inputParams.get(OAuth2Utils.CLIENT_ID),
            OAuth2Utils.parseParameterList(inputParams.get(OAuth2Utils.SCOPE)), null, null, false,
            inputParams.get(OAuth2Utils.STATE), inputParams.get(OAuth2Utils.REDIRECT_URI),
            OAuth2Utils.parseParameterList(inputParams.get(OAuth2Utils.RESPONSE_TYPE)));

    //Add extension parameters to the 'extensions' map

    if (inputParams.containsKey("prompt")) {
        request.getExtensions().put("prompt", inputParams.get("prompt"));
    }//from www  .  j ava2s .co m
    if (inputParams.containsKey("nonce")) {
        request.getExtensions().put("nonce", inputParams.get("nonce"));
    }

    if (inputParams.containsKey("claims")) {
        JsonObject claimsRequest = parseClaimRequest(inputParams.get("claims"));
        if (claimsRequest != null) {
            request.getExtensions().put("claims", claimsRequest.toString());
        }
    }

    if (inputParams.containsKey("request")) {
        request.getExtensions().put("request", inputParams.get("request"));
        processRequestObject(inputParams.get("request"), request);
    }

    if ((request.getScope() == null || request.getScope().isEmpty())) {
        if (request.getClientId() != null) {
            ClientDetails client = clientDetailsService.loadClientByClientId(request.getClientId());
            Set<String> clientScopes = client.getScope();
            request.setScope(clientScopes);
        }
    }

    return request;
}

From source file:org.mitre.openid.connect.request.ConnectOAuth2RequestFactory.java

@Override
public AuthorizationRequest createAuthorizationRequest(Map<String, String> inputParams) {

    AuthorizationRequest request = new AuthorizationRequest(inputParams, Collections.<String, String>emptyMap(),
            inputParams.get(OAuth2Utils.CLIENT_ID),
            OAuth2Utils.parseParameterList(inputParams.get(OAuth2Utils.SCOPE)), null, null, false,
            inputParams.get(OAuth2Utils.STATE), inputParams.get(OAuth2Utils.REDIRECT_URI),
            OAuth2Utils.parseParameterList(inputParams.get(OAuth2Utils.RESPONSE_TYPE)));

    //Add extension parameters to the 'extensions' map

    if (inputParams.containsKey(PROMPT)) {
        request.getExtensions().put(PROMPT, inputParams.get(PROMPT));
    }// w  ww .j a  va2s . c o m
    if (inputParams.containsKey(NONCE)) {
        request.getExtensions().put(NONCE, inputParams.get(NONCE));
    }

    if (inputParams.containsKey(CLAIMS)) {
        JsonObject claimsRequest = parseClaimRequest(inputParams.get(CLAIMS));
        if (claimsRequest != null) {
            request.getExtensions().put(CLAIMS, claimsRequest.toString());
        }
    }

    if (inputParams.containsKey(MAX_AGE)) {
        request.getExtensions().put(MAX_AGE, inputParams.get(MAX_AGE));
    }

    if (inputParams.containsKey(LOGIN_HINT)) {
        request.getExtensions().put(LOGIN_HINT, inputParams.get(LOGIN_HINT));
    }

    if (inputParams.containsKey(AUD)) {
        request.getExtensions().put(AUD, inputParams.get(AUD));
    }

    if (inputParams.containsKey(REQUEST)) {
        request.getExtensions().put(REQUEST, inputParams.get(REQUEST));
        processRequestObject(inputParams.get(REQUEST), request);
    }

    if (request.getClientId() != null) {
        try {
            ClientDetailsEntity client = clientDetailsService.loadClientByClientId(request.getClientId());

            if ((request.getScope() == null || request.getScope().isEmpty())) {
                Set<String> clientScopes = client.getScope();
                request.setScope(clientScopes);
            }

            if (request.getExtensions().get(MAX_AGE) == null && client.getDefaultMaxAge() != null) {
                request.getExtensions().put(MAX_AGE, client.getDefaultMaxAge().toString());
            }
        } catch (OAuth2Exception e) {
            logger.error("Caught OAuth2 exception trying to test client scopes and max age:", e);
        }
    }

    return request;
}

From source file:it.smartcommunitylab.aac.controller.AuthController.java

/**
 * Redirect to the login type selection page.
 * /* ww w  .ja v a  2s .  co m*/
 * @param req
 * @return
 * @throws Exception
 */
@RequestMapping("/login")
public ModelAndView login(HttpServletRequest req, HttpServletResponse res) throws Exception {
    Map<String, Object> model = new HashMap<String, Object>();
    Map<String, String> authorities = attributesAdapter.getWebAuthorityUrls();

    SavedRequest savedRequest = requestCache.getRequest(req, res);
    String target = savedRequest != null ? savedRequest.getRedirectUrl() : prepareRedirect(req, "/dev");
    req.getSession().setAttribute("redirect", target);

    Map<String, String> resultAuthorities = authorities;
    // If original request has client_id parameter, reduce the authorities to the ones of the client app
    if (savedRequest != null) {
        String[] clientIds = savedRequest.getParameterValues(OAuth2Utils.CLIENT_ID);
        if (clientIds != null && clientIds.length > 0) {
            String clientId = clientIds[0];

            Set<String> idps = clientDetailsAdapter.getIdentityProviders(clientId);
            String[] loginAuthoritiesParam = savedRequest.getParameterValues("authorities");
            String loginAuthorities = "";
            if (loginAuthoritiesParam != null && loginAuthoritiesParam.length > 0) {
                loginAuthorities = StringUtils.arrayToCommaDelimitedString(loginAuthoritiesParam);
            }

            Set<String> all = null;
            if (StringUtils.hasText(loginAuthorities)) {
                all = new HashSet<String>(Arrays.asList(loginAuthorities.split(",")));
            } else {
                all = new HashSet<String>(authorities.keySet());
            }
            resultAuthorities = new HashMap<String, String>();
            for (String idp : all) {
                if (authorities.containsKey(idp) && idps.contains(idp))
                    resultAuthorities.put(idp, authorities.get(idp));
            }

            if (resultAuthorities.isEmpty()) {
                model.put("message", "No Identity Providers assigned to the app");
                return new ModelAndView("oauth_error", model);
            }
            req.getSession().setAttribute(OAuth2Utils.CLIENT_ID, clientId);
            if (resultAuthorities.size() == 1 && !resultAuthorities.containsKey(Config.IDP_INTERNAL)) {
                return new ModelAndView(
                        "redirect:" + Utils.filterRedirectURL(resultAuthorities.keySet().iterator().next()));
            }
        }
    }
    req.getSession().setAttribute("authorities", resultAuthorities);

    return new ModelAndView("login", model);
}

From source file:com.orcid.api.common.server.delegator.impl.OrcidClientCredentialEndPointDelegatorImpl.java

protected OAuth2AccessToken generateToken(Authentication client, Set<String> scopes, String code,
        String redirectUri, String grantType, String refreshToken, String state) {
    String clientId = client.getName();
    Map<String, String> authorizationParameters = new HashMap<String, String>();

    if (scopes != null) {
        String scopesString = StringUtils.join(scopes, ' ');
        authorizationParameters.put(OAuth2Utils.SCOPE, scopesString);
    }//from   w  w  w  .  ja  va  2  s.c  om

    authorizationParameters.put(OAuth2Utils.CLIENT_ID, clientId);
    if (code != null) {
        authorizationParameters.put("code", code);
        OrcidOauth2AuthoriziationCodeDetail authorizationCodeEntity = orcidOauth2AuthoriziationCodeDetailDao
                .find(code);

        if (authorizationCodeEntity != null) {
            if (orcidOauth2AuthoriziationCodeDetailDao.isPersistentToken(code)) {
                authorizationParameters.put(OrcidOauth2Constants.IS_PERSISTENT, "true");
            } else {
                authorizationParameters.put(OrcidOauth2Constants.IS_PERSISTENT, "false");
            }

            if (!authorizationParameters.containsKey(OAuth2Utils.SCOPE)
                    || PojoUtil.isEmpty(authorizationParameters.get(OAuth2Utils.SCOPE))) {
                String scopesString = StringUtils.join(authorizationCodeEntity.getScopes(), ' ');
                authorizationParameters.put(OAuth2Utils.SCOPE, scopesString);
            }
        } else {
            authorizationParameters.put(OrcidOauth2Constants.IS_PERSISTENT, "false");
        }
    }
    if (redirectUri != null) {
        authorizationParameters.put(OAuth2Utils.REDIRECT_URI, redirectUri);
    }
    AuthorizationRequest authorizationRequest = getOAuth2RequestFactory()
            .createAuthorizationRequest(authorizationParameters);

    TokenRequest tokenRequest = getOAuth2RequestFactory().createTokenRequest(authorizationRequest, grantType);

    OAuth2AccessToken token = getTokenGranter().grant(grantType, tokenRequest);
    Object params[] = { grantType };
    if (token == null) {
        LOGGER.info(
                "Unsupported grant type for OAuth2: clientId={}, grantType={}, refreshToken={}, code={}, scopes={}, state={}, redirectUri={}",
                new Object[] { clientId, grantType, refreshToken, code, scopes, state, redirectUri });
        throw new UnsupportedGrantTypeException(
                localeManager.resolveMessage("apiError.unsupported_client_type.exception", params));
    }
    LOGGER.info(
            "OAuth2 access token granted: clientId={}, grantType={}, refreshToken={}, code={}, scopes={}, state={}, redirectUri={}, token={}",
            new Object[] { clientId, grantType, refreshToken, code, scopes, state, redirectUri, token });

    return token;
}

From source file:it.smartcommunitylab.aac.controller.AuthController.java

/**
 * Entry point for resource access authorization request. Redirects to the
 * login page. In addition to standard OAuth parameters, it is possible to
 * specify a comma-separated list of authorities to be used for login as
 * 'authorities' parameter//from www .  jav a 2 s .co m
 * 
 * @param req
 * @return
 * @throws Exception
 */
@RequestMapping("/eauth/authorize")
public ModelAndView authorise(Device device, HttpServletRequest req,
        @RequestParam(value = "authorities", required = false) String loginAuthorities) throws Exception {
    Map<String, Object> model = new HashMap<String, Object>();

    String clientId = req.getParameter(OAuth2Utils.CLIENT_ID);
    if (clientId == null || clientId.isEmpty()) {
        model.put("message", "Missing client_id");
        return new ModelAndView("oauth_error", model);
    }
    // each time create new OAuth request
    ClientAppBasic client = clientDetailsAdapter.getByClientId(clientId);
    AACOAuthRequest oauthRequest = new AACOAuthRequest(req, device, client.getScope(), client.getDisplayName());
    Authentication auth = SecurityContextHolder.getContext().getAuthentication();
    if (auth != null && auth.getAuthorities() != null
            && auth.getAuthorities().stream()
                    .anyMatch(a -> a.getAuthority().equals(AUTHORITY.ROLE_USER.toString()))
            && req.getSession().getAttribute(Config.SESSION_ATTR_AAC_OAUTH_REQUEST) != null) {
        AACOAuthRequest old = (AACOAuthRequest) req.getSession()
                .getAttribute(Config.SESSION_ATTR_AAC_OAUTH_REQUEST);
        oauthRequest.setAuthority(old.getAuthority());
        // update existing session data
        AbstractAuthenticationToken a = new AACAuthenticationToken(auth.getPrincipal(), null,
                oauthRequest.getAuthority(), auth.getAuthorities());
        a.setDetails(oauthRequest);
        SecurityContextHolder.getContext().setAuthentication(a);
    }
    if (StringUtils.isEmpty(oauthRequest.getAuthority()) && loginAuthorities != null) {
        oauthRequest.setAuthority(loginAuthorities.split(",")[0].trim());
    }
    req.getSession().setAttribute(Config.SESSION_ATTR_AAC_OAUTH_REQUEST, oauthRequest);

    String target = prepareRedirect(req, "/eauth/pre-authorize");
    return new ModelAndView("redirect:" + target);
}

From source file:org.cloudfoundry.identity.uaa.mock.token.RefreshTokenMockMvcTests.java

@Test
void refreshTokenGrant_rejectsAccessTokens_ClientCredentialsGrantType() throws Exception {
    createClientAndUserInRandomZone();/*from  w w w .ja v  a 2s .c om*/
    String tokenResponse = mockMvc
            .perform(post("/oauth/token").header("Host", getZoneHostUrl(zone))
                    .accept(MediaType.APPLICATION_JSON).contentType(MediaType.APPLICATION_FORM_URLENCODED_VALUE)
                    .param(OAuth2Utils.GRANT_TYPE, GRANT_TYPE_CLIENT_CREDENTIALS).param("client_secret", SECRET)
                    .param(OAuth2Utils.CLIENT_ID, client.getClientId()))
            .andExpect(status().isOk()).andReturn().getResponse().getContentAsString();
    String accessToken = (String) JsonUtils.readValue(tokenResponse, new TypeReference<Map<String, Object>>() {
    }).get("access_token");

    mockMvc.perform(post("/oauth/token").header("Host", getZoneHostUrl(zone)).accept(MediaType.APPLICATION_JSON)
            .contentType(MediaType.APPLICATION_FORM_URLENCODED_VALUE)
            .param(OAuth2Utils.GRANT_TYPE, REFRESH_TOKEN).param(REFRESH_TOKEN, accessToken)
            .param("client_secret", SECRET).param(OAuth2Utils.CLIENT_ID, client.getClientId()))
            .andExpect(status().isUnauthorized());
}

From source file:org.cloudfoundry.identity.uaa.mock.token.RefreshTokenMockMvcTests.java

@Test
void refreshTokenGrant_rejectsAccessTokens_PasswordGrantType() throws Exception {
    createClientAndUserInRandomZone();//w  ww  .  j  a v  a  2s. co  m
    String body = mockMvc
            .perform(post("/oauth/token").accept(MediaType.APPLICATION_JSON_VALUE)
                    .header("Host", getZoneHostUrl(zone))
                    .header("Authorization",
                            "Basic " + new String(
                                    Base64.encode((client.getClientId() + ":" + SECRET).getBytes())))
                    .param("grant_type", GRANT_TYPE_PASSWORD).param("client_id", client.getClientId())
                    .param("client_secret", SECRET).param("username", user.getUserName())
                    .param("password", SECRET))
            .andExpect(status().isOk()).andReturn().getResponse().getContentAsString();

    Map<String, Object> bodyMap = JsonUtils.readValue(body, new TypeReference<Map<String, Object>>() {
    });
    String accessToken = (String) bodyMap.get("access_token");

    mockMvc.perform(post("/oauth/token").header("Host", getZoneHostUrl(zone)).accept(MediaType.APPLICATION_JSON)
            .contentType(MediaType.APPLICATION_FORM_URLENCODED_VALUE)
            .param(OAuth2Utils.GRANT_TYPE, REFRESH_TOKEN).param(REFRESH_TOKEN, accessToken)
            .param("client_secret", SECRET).param(OAuth2Utils.CLIENT_ID, client.getClientId()))
            .andExpect(status().isUnauthorized());
}

From source file:org.cloudfoundry.identity.uaa.mock.token.RefreshTokenMockMvcTests.java

@Test
void refreshTokenGrant_rejectsIdTokens() throws Exception {
    createClientAndUserInRandomZone();//from   w  w  w  . ja v a 2  s  .  c  o  m
    String body = mockMvc
            .perform(post("/oauth/token").accept(MediaType.APPLICATION_JSON_VALUE)
                    .header("Host", getZoneHostUrl(zone))
                    .header("Authorization",
                            "Basic " + new String(
                                    Base64.encode((client.getClientId() + ":" + SECRET).getBytes())))
                    .param("grant_type", GRANT_TYPE_PASSWORD).param("client_id", client.getClientId())
                    .param("client_secret", SECRET).param("username", user.getUserName())
                    .param("password", SECRET))
            .andExpect(status().isOk()).andReturn().getResponse().getContentAsString();

    Map<String, Object> bodyMap = JsonUtils.readValue(body, new TypeReference<Map<String, Object>>() {
    });
    String idToken = (String) bodyMap.get("id_token");

    mockMvc.perform(post("/oauth/token").header("Host", getZoneHostUrl(zone)).accept(MediaType.APPLICATION_JSON)
            .contentType(MediaType.APPLICATION_FORM_URLENCODED_VALUE)
            .param(OAuth2Utils.GRANT_TYPE, REFRESH_TOKEN).param(REFRESH_TOKEN, idToken)
            .param("client_secret", SECRET).param(OAuth2Utils.CLIENT_ID, client.getClientId()))
            .andExpect(status().isUnauthorized());
}