Example usage for org.springframework.security.oauth2.provider AuthorizationRequest getExtensions

List of usage examples for org.springframework.security.oauth2.provider AuthorizationRequest getExtensions

Introduction

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

Prototype

public Map<String, Serializable> getExtensions() 

Source Link

Usage

From source file:net.shibboleth.idp.oidc.flow.PreAuthorizeUserApprovalAction.java

/**
 * Store authentication time into authorization request.
 *
 * @param authentication the authentication
 * @param authRequest    the auth request
 *//*from   w w  w  .  ja  v a2 s  .  co  m*/
private static void storeAuthenticationTimeIntoAuthorizationRequest(final Authentication authentication,
        final AuthorizationRequest authRequest) {
    authRequest.getExtensions().put(OIDCConstants.AUTH_TIME,
            ((SpringSecurityAuthenticationToken) authentication).getAuthenticationDateTime().getMillis());
}

From source file:net.shibboleth.idp.oidc.flow.BuildAuthenticationContextAction.java

/**
 * Process requested acr values if any.//from ww w.ja  v a  2 s  .  c  o  m
 *
 * @param authorizationRequest the authorization request
 * @param principals           the principals
 */
private void processRequestedAcrValuesIfAny(final AuthorizationRequest authorizationRequest,
        final List<Principal> principals) {
    if (authorizationRequest.getExtensions().containsKey(OIDCConstants.ACR_VALUES)) {
        final String[] acrValues = authorizationRequest.getExtensions().get(OIDCConstants.ACR_VALUES).toString()
                .split(" ");
        for (final String acrValue : acrValues) {
            final AuthnContextClassRefPrincipal requestedPrincipal = new AuthnContextClassRefPrincipal(
                    acrValue.trim());
            for (final AuthenticationFlowDescriptor flow : this.availableAuthenticationFlows) {
                if (!principals.contains(requestedPrincipal)
                        && flow.getSupportedPrincipals().contains(requestedPrincipal)) {
                    principals.add(requestedPrincipal);
                }
            }
        }

    }
}

From source file:net.shibboleth.idp.oidc.config.ShibbolethOAuth2RequestFactory.java

@Override
public AuthorizationRequest createAuthorizationRequest(final Map<String, String> inputParams) {
    final AuthorizationRequest request = super.createAuthorizationRequest(inputParams);
    if (inputParams.containsKey(OIDCConstants.ACR_VALUES)) {
        try {//from w  w  w  .j  a v a2  s.c  o  m
            log.debug("Authorization request contains {}. Decoding and storing values into the request",
                    OIDCConstants.ACR_VALUES);
            request.getExtensions().put(OIDCConstants.ACR_VALUES,
                    URLDecoder.decode(inputParams.get(OIDCConstants.ACR_VALUES), "UTF-8"));
        } catch (final Exception e) {
            log.warn("Unable to decode acr_values in the authorization request", e);
        }
    }
    return request;
}

From source file:org.mitre.oauth2.web.OAuthConfirmationController.java

@PreAuthorize("hasRole('ROLE_USER')")
@RequestMapping("/oauth/confirm_access")
public String confimAccess(Map<String, Object> model,
        @ModelAttribute("authorizationRequest") AuthorizationRequest authRequest, Principal p) {

    // Check the "prompt" parameter to see if we need to do special processing

    String prompt = (String) authRequest.getExtensions().get(PROMPT);
    List<String> prompts = Splitter.on(PROMPT_SEPARATOR).splitToList(Strings.nullToEmpty(prompt));
    ClientDetailsEntity client = null;/*from   w ww .  ja  v  a2 s  . c o  m*/

    try {
        client = clientService.loadClientByClientId(authRequest.getClientId());
    } catch (OAuth2Exception e) {
        logger.error("confirmAccess: OAuth2Exception was thrown when attempting to load client", e);
        model.put(HttpCodeView.CODE, HttpStatus.BAD_REQUEST);
        return HttpCodeView.VIEWNAME;
    } catch (IllegalArgumentException e) {
        logger.error("confirmAccess: IllegalArgumentException was thrown when attempting to load client", e);
        model.put(HttpCodeView.CODE, HttpStatus.BAD_REQUEST);
        return HttpCodeView.VIEWNAME;
    }

    if (client == null) {
        logger.error("confirmAccess: could not find client " + authRequest.getClientId());
        model.put(HttpCodeView.CODE, HttpStatus.NOT_FOUND);
        return HttpCodeView.VIEWNAME;
    }

    if (prompts.contains("none")) {
        // if we've got a redirect URI then we'll send it

        String url = redirectResolver.resolveRedirect(authRequest.getRedirectUri(), client);

        try {
            URIBuilder uriBuilder = new URIBuilder(url);

            uriBuilder.addParameter("error", "interaction_required");
            if (!Strings.isNullOrEmpty(authRequest.getState())) {
                uriBuilder.addParameter("state", authRequest.getState()); // copy the state parameter if one was given
            }

            return "redirect:" + uriBuilder.toString();

        } catch (URISyntaxException e) {
            logger.error("Can't build redirect URI for prompt=none, sending error instead", e);
            model.put("code", HttpStatus.FORBIDDEN);
            return HttpCodeView.VIEWNAME;
        }
    }

    model.put("auth_request", authRequest);
    model.put("client", client);

    String redirect_uri = authRequest.getRedirectUri();

    model.put("redirect_uri", redirect_uri);

    // pre-process the scopes
    Set<SystemScope> scopes = scopeService.fromStrings(authRequest.getScope());

    Set<SystemScope> sortedScopes = new LinkedHashSet<>(scopes.size());
    Set<SystemScope> systemScopes = scopeService.getAll();

    // sort scopes for display based on the inherent order of system scopes
    for (SystemScope s : systemScopes) {
        if (scopes.contains(s)) {
            sortedScopes.add(s);
        }
    }

    // add in any scopes that aren't system scopes to the end of the list
    sortedScopes.addAll(Sets.difference(scopes, systemScopes));

    model.put("scopes", sortedScopes);

    // get the userinfo claims for each scope
    UserInfo user = userInfoService.getByUsername(p.getName());
    Map<String, Map<String, String>> claimsForScopes = new HashMap<>();
    if (user != null) {
        JsonObject userJson = user.toJson();

        for (SystemScope systemScope : sortedScopes) {
            Map<String, String> claimValues = new HashMap<>();

            Set<String> claims = scopeClaimTranslationService.getClaimsForScope(systemScope.getValue());
            for (String claim : claims) {
                if (userJson.has(claim) && userJson.get(claim).isJsonPrimitive()) {
                    // TODO: this skips the address claim
                    claimValues.put(claim, userJson.get(claim).getAsString());
                }
            }

            claimsForScopes.put(systemScope.getValue(), claimValues);
        }
    }

    model.put("claims", claimsForScopes);

    // client stats
    Integer count = statsService.getCountForClientId(client.getId());
    model.put("count", count);

    // contacts
    if (client.getContacts() != null) {
        String contacts = Joiner.on(", ").join(client.getContacts());
        model.put("contacts", contacts);
    }

    // if the client is over a week old and has more than one registration, don't give such a big warning
    // instead, tag as "Generally Recognized As Safe" (gras)
    Date lastWeek = new Date(System.currentTimeMillis() - (60 * 60 * 24 * 7 * 1000));
    if (count > 1 && client.getCreatedAt() != null && client.getCreatedAt().before(lastWeek)) {
        model.put("gras", true);
    } else {
        model.put("gras", false);
    }

    return "approve";
}

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

@Override
public OAuth2Request createOAuth2Request(AuthorizationRequest request) {
    return new OAuth2Request(request.getRequestParameters(), request.getClientId(), request.getAuthorities(),
            request.isApproved(), request.getScope(), request.getResourceIds(), request.getRedirectUri(),
            request.getExtensions());
}

From source file:org.mitre.openid.connect.token.TofuUserApprovalHandler.java

/**
 * Check if the user has already stored a positive approval decision for this site; or if the
 * site is whitelisted, approve it automatically.
 * /* w  ww.  j  av a 2 s  .c  o  m*/
 * Otherwise the user will be directed to the approval page and can make their own decision.
 * 
 * @param authorizationRequest   the incoming authorization request
 * @param userAuthentication   the Principal representing the currently-logged-in user
 * 
 * @return                   the updated AuthorizationRequest
 */
@Override
public AuthorizationRequest checkForPreApproval(AuthorizationRequest authorizationRequest,
        Authentication userAuthentication) {

    //First, check database to see if the user identified by the userAuthentication has stored an approval decision

    String userId = userAuthentication.getName();
    String clientId = authorizationRequest.getClientId();

    //lookup ApprovedSites by userId and clientId
    boolean alreadyApproved = false;

    // find out if we're supposed to force a prompt on the user or not
    String prompt = (String) authorizationRequest.getExtensions().get(PROMPT);
    List<String> prompts = Splitter.on(PROMPT_SEPARATOR).splitToList(Strings.nullToEmpty(prompt));
    if (!prompts.contains(PROMPT_CONSENT)) {
        // if the prompt parameter is set to "consent" then we can't use approved sites or whitelisted sites
        // otherwise, we need to check them below

        Collection<ApprovedSite> aps = approvedSiteService.getByClientIdAndUserId(clientId, userId);
        for (ApprovedSite ap : aps) {

            if (!ap.isExpired()) {

                // if we find one that fits...
                if (systemScopes.scopesMatch(ap.getAllowedScopes(), authorizationRequest.getScope())) {

                    //We have a match; update the access date on the AP entry and return true.
                    ap.setAccessDate(new Date());
                    approvedSiteService.save(ap);

                    String apId = ap.getId().toString();
                    authorizationRequest.getExtensions().put(APPROVED_SITE, apId);
                    authorizationRequest.setApproved(true);
                    alreadyApproved = true;

                    setAuthTime(authorizationRequest);
                }
            }
        }

        if (!alreadyApproved) {
            WhitelistedSite ws = whitelistedSiteService.getByClientId(clientId);
            if (ws != null
                    && systemScopes.scopesMatch(ws.getAllowedScopes(), authorizationRequest.getScope())) {
                authorizationRequest.setApproved(true);

                setAuthTime(authorizationRequest);
            }
        }
    }

    return authorizationRequest;

}

From source file:org.smartplatforms.openid.connect.token.SmartTofuUserApprovalHandler.java

/**
 * Check if the user has already stored a positive approval decision for this site; or if the
 * site is whitelisted, approve it automatically.
 * //from   w w w .j  av a2  s  .  co  m
 * Otherwise the user will be directed to the approval page and can make their own decision.
 * 
 * @param authorizationRequest   the incoming authorization request
 * @param userAuthentication   the Principal representing the currently-logged-in user
 * 
 * @return                   the updated AuthorizationRequest
 */
@Override
public AuthorizationRequest checkForPreApproval(AuthorizationRequest authorizationRequest,
        Authentication userAuthentication) {

    //First, check database to see if the user identified by the userAuthentication has stored an approval decision

    String userId = userAuthentication.getName();
    String clientId = authorizationRequest.getClientId();

    //lookup ApprovedSites by userId and clientId
    boolean alreadyApproved = false;

    // find out if we're supposed to force a prompt on the user or not
    String prompt = (String) authorizationRequest.getExtensions().get(PROMPT);
    List<String> prompts = Splitter.on(PROMPT_SEPARATOR).splitToList(Strings.nullToEmpty(prompt));
    if (!prompts.contains(PROMPT_SEPARATOR)) {
        // if the prompt parameter is set to "consent" then we can't use approved sites or whitelisted sites
        // otherwise, we need to check them below

        Collection<ApprovedSite> aps = approvedSiteService.getByClientIdAndUserId(clientId, userId);
        for (ApprovedSite ap : aps) {

            if (!ap.isExpired()) {

                // if we find one that fits...
                if (systemScopes.scopesMatch(ap.getAllowedScopes(), authorizationRequest.getScope())) {

                    //We have a match; update the access date on the AP entry and return true.
                    ap.setAccessDate(new Date());
                    approvedSiteService.save(ap);

                    String apId = ap.getId().toString();
                    authorizationRequest.getExtensions().put(APPROVED_SITE, apId);
                    authorizationRequest.setApproved(true);
                    alreadyApproved = true;

                    setAuthTime(authorizationRequest);
                }
            }
        }

        if (!alreadyApproved) {
            WhitelistedSite ws = whitelistedSiteService.getByClientId(clientId);
            if (ws != null
                    && systemScopes.scopesMatch(ws.getAllowedScopes(), authorizationRequest.getScope())) {
                authorizationRequest.setApproved(true);

                setAuthTime(authorizationRequest);
            }
        }
    }

    return authorizationRequest;

}

From source file:org.smartplatforms.openid.connect.token.SmartTofuUserApprovalHandler.java

@Override
public AuthorizationRequest updateAfterApproval(AuthorizationRequest authorizationRequest,
        Authentication userAuthentication) {

    String userId = userAuthentication.getName();
    String clientId = authorizationRequest.getClientId();
    ClientDetails client = clientDetailsService.loadClientByClientId(clientId);

    // This must be re-parsed here because SECOAUTH forces us to call things in a strange order
    if (Boolean.parseBoolean(authorizationRequest.getApprovalParameters().get("user_oauth_approval"))
            && authorizationRequest.getExtensions().get(CSRF) != null && authorizationRequest.getExtensions()
                    .get(CSRF).equals(authorizationRequest.getApprovalParameters().get(CSRF))) {

        authorizationRequest.setApproved(true);

        // process scopes from user input
        Set<String> allowedScopes = Sets.newHashSet();
        Map<String, String> approvalParams = authorizationRequest.getApprovalParameters();

        Set<String> keys = approvalParams.keySet();

        for (String key : keys) {
            if (key.startsWith("scope_")) {
                //This is a scope parameter from the approval page. The value sent back should
                //be the scope string. Check to make sure it is contained in the client's
                //registered allowed scopes.

                String scope = approvalParams.get(key);
                Set<String> approveSet = Sets.newHashSet(scope);

                //Make sure this scope is allowed for the given client
                if (systemScopes.scopesMatch(client.getScope(), approveSet)) {

                    // If it's structured, assign the user-specified parameter
                    SystemScope systemScope = systemScopes.getByValue(scope);
                    if (systemScope != null && systemScope.isStructured()) {
                        String paramValue = approvalParams.get("scopeparam_" + scope);
                        if (!Strings.isNullOrEmpty(paramValue)) {
                            allowedScopes.add(scope + ":" + paramValue);
                        } else {
                            allowedScopes.add(scope);
                        }// w  w w . java 2  s.c  o m
                        // .. and if it's unstructured, we're all set
                    } else {
                        allowedScopes.add(scope);
                    }
                }

            }
        }

        // inject the user-allowed scopes into the auth request
        authorizationRequest.setScope(allowedScopes);

        //Only store an ApprovedSite if the user has checked "remember this decision":
        String remember = authorizationRequest.getApprovalParameters().get("remember");
        if (!Strings.isNullOrEmpty(remember) && !remember.equals("none")) {

            Date timeout = null;
            if (remember.equals("one-hour")) {
                // set the timeout to one hour from now
                Calendar cal = Calendar.getInstance();
                cal.add(Calendar.HOUR, 1);
                timeout = cal.getTime();
            }

            ApprovedSite newSite = approvedSiteService.createApprovedSite(clientId, userId, timeout,
                    allowedScopes);
            String newSiteId = newSite.getId().toString();
            authorizationRequest.getExtensions().put(APPROVED_SITE, newSiteId);
        }

        setAuthTime(authorizationRequest);

    }

    return authorizationRequest;
}

From source file:org.mitre.openid.connect.token.TofuUserApprovalHandler.java

/**
 * Get the auth time out of the current session and add it to the
 * auth request in the extensions map./*from ww w  .j  ava2 s.  c  o  m*/
 * 
 * @param authorizationRequest
 */
private void setAuthTime(AuthorizationRequest authorizationRequest) {
    // Get the session auth time, if we have it, and store it in the request
    ServletRequestAttributes attr = (ServletRequestAttributes) RequestContextHolder.currentRequestAttributes();
    if (attr != null) {
        HttpSession session = attr.getRequest().getSession();
        if (session != null) {
            Date authTime = (Date) session.getAttribute(AuthenticationTimeStamper.AUTH_TIMESTAMP);
            if (authTime != null) {
                String authTimeString = Long.toString(authTime.getTime());
                authorizationRequest.getExtensions().put(AuthenticationTimeStamper.AUTH_TIMESTAMP,
                        authTimeString);
            }
        }
    }
}

From source file:org.smartplatforms.openid.connect.token.SmartTofuUserApprovalHandler.java

/**
 * Check if the user has already stored a positive approval decision for this site; or if the
 * site is whitelisted, approve it automatically.
 * //from  w w  w . j av  a2 s . c  om
 * Otherwise, return false so that the user will see the approval page and can make their own decision.
 * 
 * @param authorizationRequest   the incoming authorization request
 * @param userAuthentication   the Principal representing the currently-logged-in user
 * 
 * @return                   true if the site is approved, false otherwise
 */
@Override
public boolean isApproved(AuthorizationRequest authorizationRequest, Authentication userAuthentication) {

    // if this request is already approved, pass that info through
    // (this flag may be set by updateBeforeApproval, which can also do funny things with scopes, etc)
    if (authorizationRequest.isApproved()) {
        return true;
    } else {
        // if not, check to see if the user has approved it
        if (Boolean.parseBoolean(authorizationRequest.getApprovalParameters().get("user_oauth_approval"))) { // TODO: make parameter name configurable?

            // check the value of the CSRF parameter

            if (authorizationRequest.getExtensions().get(CSRF) != null) {
                if (authorizationRequest.getExtensions().get(CSRF)
                        .equals(authorizationRequest.getApprovalParameters().get(CSRF))) {

                    // make sure the user is actually authenticated
                    return userAuthentication.isAuthenticated();
                }
            }
        }

        // if the above doesn't pass, it's not yet approved
        return false;
    }

}