Search in sources :

Example 1 with UserInfo

use of org.mitre.openid.connect.model.UserInfo in project OpenID-Connect-Java-Spring-Server by mitreid-connect.

the class DefaultUserInfoService method getByUsernameAndClientId.

@Override
public UserInfo getByUsernameAndClientId(String username, String clientId) {
    ClientDetailsEntity client = clientService.loadClientByClientId(clientId);
    UserInfo userInfo = getByUsername(username);
    if (client == null || userInfo == null) {
        return null;
    }
    if (SubjectType.PAIRWISE.equals(client.getSubjectType())) {
        String pairwiseSub = pairwiseIdentifierService.getIdentifier(userInfo, client);
        userInfo.setSub(pairwiseSub);
    }
    return userInfo;
}
Also used : ClientDetailsEntity(org.mitre.oauth2.model.ClientDetailsEntity) UserInfo(org.mitre.openid.connect.model.UserInfo)

Example 2 with UserInfo

use of org.mitre.openid.connect.model.UserInfo in project OpenID-Connect-Java-Spring-Server by mitreid-connect.

the class UserInfoView method renderMergedOutputModel.

/*
	 * (non-Javadoc)
	 *
	 * @see
	 * org.springframework.web.servlet.view.AbstractView#renderMergedOutputModel
	 * (java.util.Map, javax.servlet.http.HttpServletRequest,
	 * javax.servlet.http.HttpServletResponse)
	 */
@Override
protected void renderMergedOutputModel(Map<String, Object> model, HttpServletRequest request, HttpServletResponse response) {
    UserInfo userInfo = (UserInfo) model.get(USER_INFO);
    Set<String> scope = (Set<String>) model.get(SCOPE);
    response.setContentType(MediaType.APPLICATION_JSON_VALUE);
    response.setCharacterEncoding("UTF-8");
    JsonObject authorizedClaims = null;
    JsonObject requestedClaims = null;
    if (model.get(AUTHORIZED_CLAIMS) != null) {
        authorizedClaims = jsonParser.parse((String) model.get(AUTHORIZED_CLAIMS)).getAsJsonObject();
    }
    if (model.get(REQUESTED_CLAIMS) != null) {
        requestedClaims = jsonParser.parse((String) model.get(REQUESTED_CLAIMS)).getAsJsonObject();
    }
    JsonObject json = toJsonFromRequestObj(userInfo, scope, authorizedClaims, requestedClaims);
    writeOut(json, model, request, response);
}
Also used : Set(java.util.Set) HashSet(java.util.HashSet) JsonObject(com.google.gson.JsonObject) UserInfo(org.mitre.openid.connect.model.UserInfo)

Example 3 with UserInfo

use of org.mitre.openid.connect.model.UserInfo in project OpenID-Connect-Java-Spring-Server by mitreid-connect.

the class EndSessionEndpoint method endSession.

@RequestMapping(value = "/" + URL, method = RequestMethod.GET)
public String endSession(@RequestParam(value = "id_token_hint", required = false) String idTokenHint, @RequestParam(value = "post_logout_redirect_uri", required = false) String postLogoutRedirectUri, @RequestParam(value = STATE_KEY, required = false) String state, HttpServletRequest request, HttpServletResponse response, HttpSession session, Authentication auth, Model m) {
    // conditionally filled variables
    // pulled from the parsed and validated ID token
    JWTClaimsSet idTokenClaims = null;
    // pulled from ID token's audience field
    ClientDetailsEntity client = null;
    if (!Strings.isNullOrEmpty(postLogoutRedirectUri)) {
        session.setAttribute(REDIRECT_URI_KEY, postLogoutRedirectUri);
    }
    if (!Strings.isNullOrEmpty(state)) {
        session.setAttribute(STATE_KEY, state);
    }
    // parse the ID token hint to see if it's valid
    if (!Strings.isNullOrEmpty(idTokenHint)) {
        try {
            JWT idToken = JWTParser.parse(idTokenHint);
            if (validator.isValid(idToken)) {
                // we issued this ID token, figure out who it's for
                idTokenClaims = idToken.getJWTClaimsSet();
                String clientId = Iterables.getOnlyElement(idTokenClaims.getAudience());
                client = clientService.loadClientByClientId(clientId);
                // save a reference in the session for us to pick up later
                // session.setAttribute("endSession_idTokenHint_claims", idTokenClaims);
                session.setAttribute(CLIENT_KEY, client);
            }
        } catch (ParseException e) {
            // it's not a valid ID token, ignore it
            logger.debug("Invalid id token hint", e);
        } catch (InvalidClientException e) {
            // couldn't find the client, ignore it
            logger.debug("Invalid client", e);
        }
    }
    // are we logged in or not?
    if (auth == null || !request.isUserInRole("ROLE_USER")) {
        // we're not logged in anyway, process the final redirect bits if needed
        return processLogout(null, request, response, session, auth, m);
    } else {
        // we are logged in, need to prompt the user before we log out
        // see who the current user is
        UserInfo ui = userInfoService.getByUsername(auth.getName());
        if (idTokenClaims != null) {
            String subject = idTokenClaims.getSubject();
            // TODO: should we do anything different in these cases?
            if (!Strings.isNullOrEmpty(subject) && subject.equals(ui.getSub())) {
            // it's the same user
            } else {
            // it's not the same user
            }
        }
        m.addAttribute("client", client);
        m.addAttribute("idToken", idTokenClaims);
        // display the log out confirmation page
        return "logoutConfirmation";
    }
}
Also used : ClientDetailsEntity(org.mitre.oauth2.model.ClientDetailsEntity) JWTClaimsSet(com.nimbusds.jwt.JWTClaimsSet) JWT(com.nimbusds.jwt.JWT) InvalidClientException(org.springframework.security.oauth2.common.exceptions.InvalidClientException) UserInfo(org.mitre.openid.connect.model.UserInfo) ParseException(java.text.ParseException) RequestMapping(org.springframework.web.bind.annotation.RequestMapping)

Example 4 with UserInfo

use of org.mitre.openid.connect.model.UserInfo in project OpenID-Connect-Java-Spring-Server by mitreid-connect.

the class UserInfoEndpoint method getInfo.

/**
 * Get information about the user as specified in the accessToken included in this request
 */
@PreAuthorize("hasRole('ROLE_USER') and #oauth2.hasScope('" + SystemScopeService.OPENID_SCOPE + "')")
@RequestMapping(method = { RequestMethod.GET, RequestMethod.POST }, produces = { MediaType.APPLICATION_JSON_VALUE, UserInfoJWTView.JOSE_MEDIA_TYPE_VALUE })
public String getInfo(@RequestParam(value = "claims", required = false) String claimsRequestJsonString, @RequestHeader(value = HttpHeaders.ACCEPT, required = false) String acceptHeader, OAuth2Authentication auth, Model model) {
    if (auth == null) {
        logger.error("getInfo failed; no principal. Requester is not authorized.");
        model.addAttribute(HttpCodeView.CODE, HttpStatus.FORBIDDEN);
        return HttpCodeView.VIEWNAME;
    }
    String username = auth.getName();
    UserInfo userInfo = userInfoService.getByUsernameAndClientId(username, auth.getOAuth2Request().getClientId());
    if (userInfo == null) {
        logger.error("getInfo failed; user not found: " + username);
        model.addAttribute(HttpCodeView.CODE, HttpStatus.NOT_FOUND);
        return HttpCodeView.VIEWNAME;
    }
    model.addAttribute(UserInfoView.SCOPE, auth.getOAuth2Request().getScope());
    model.addAttribute(UserInfoView.AUTHORIZED_CLAIMS, auth.getOAuth2Request().getExtensions().get("claims"));
    if (!Strings.isNullOrEmpty(claimsRequestJsonString)) {
        model.addAttribute(UserInfoView.REQUESTED_CLAIMS, claimsRequestJsonString);
    }
    model.addAttribute(UserInfoView.USER_INFO, userInfo);
    // content negotiation
    // start off by seeing if the client has registered for a signed/encrypted JWT from here
    ClientDetailsEntity client = clientService.loadClientByClientId(auth.getOAuth2Request().getClientId());
    model.addAttribute(UserInfoJWTView.CLIENT, client);
    List<MediaType> mediaTypes = MediaType.parseMediaTypes(acceptHeader);
    MediaType.sortBySpecificityAndQuality(mediaTypes);
    if (client.getUserInfoSignedResponseAlg() != null || client.getUserInfoEncryptedResponseAlg() != null || client.getUserInfoEncryptedResponseEnc() != null) {
        // client has a preference, see if they ask for plain JSON specifically on this request
        for (MediaType m : mediaTypes) {
            if (!m.isWildcardType() && m.isCompatibleWith(UserInfoJWTView.JOSE_MEDIA_TYPE)) {
                return UserInfoJWTView.VIEWNAME;
            } else if (!m.isWildcardType() && m.isCompatibleWith(MediaType.APPLICATION_JSON)) {
                return UserInfoView.VIEWNAME;
            }
        }
        // otherwise return JWT
        return UserInfoJWTView.VIEWNAME;
    } else {
        // client has no preference, see if they asked for JWT specifically on this request
        for (MediaType m : mediaTypes) {
            if (!m.isWildcardType() && m.isCompatibleWith(MediaType.APPLICATION_JSON)) {
                return UserInfoView.VIEWNAME;
            } else if (!m.isWildcardType() && m.isCompatibleWith(UserInfoJWTView.JOSE_MEDIA_TYPE)) {
                return UserInfoJWTView.VIEWNAME;
            }
        }
        // otherwise return JSON
        return UserInfoView.VIEWNAME;
    }
}
Also used : ClientDetailsEntity(org.mitre.oauth2.model.ClientDetailsEntity) MediaType(org.springframework.http.MediaType) UserInfo(org.mitre.openid.connect.model.UserInfo) PreAuthorize(org.springframework.security.access.prepost.PreAuthorize) RequestMapping(org.springframework.web.bind.annotation.RequestMapping)

Example 5 with UserInfo

use of org.mitre.openid.connect.model.UserInfo in project OpenID-Connect-Java-Spring-Server by mitreid-connect.

the class ClaimsCollectionEndpoint method collectClaims.

@RequestMapping(method = RequestMethod.GET)
public String collectClaims(@RequestParam("client_id") String clientId, @RequestParam(value = "redirect_uri", required = false) String redirectUri, @RequestParam("ticket") String ticketValue, @RequestParam(value = "state", required = false) String state, Model m, OIDCAuthenticationToken auth) {
    ClientDetailsEntity client = clientService.loadClientByClientId(clientId);
    PermissionTicket ticket = permissionService.getByTicket(ticketValue);
    if (client == null || ticket == null) {
        logger.info("Client or ticket not found: " + clientId + " :: " + ticketValue);
        m.addAttribute(HttpCodeView.CODE, HttpStatus.NOT_FOUND);
        return HttpCodeView.VIEWNAME;
    }
    // we've got a client and ticket, let's attach the claims that we have from the token and userinfo
    // subject
    Set<Claim> claimsSupplied = Sets.newHashSet(ticket.getClaimsSupplied());
    String issuer = auth.getIssuer();
    UserInfo userInfo = auth.getUserInfo();
    claimsSupplied.add(mkClaim(issuer, "sub", new JsonPrimitive(auth.getSub())));
    if (userInfo.getEmail() != null) {
        claimsSupplied.add(mkClaim(issuer, "email", new JsonPrimitive(userInfo.getEmail())));
    }
    if (userInfo.getEmailVerified() != null) {
        claimsSupplied.add(mkClaim(issuer, "email_verified", new JsonPrimitive(userInfo.getEmailVerified())));
    }
    if (userInfo.getPhoneNumber() != null) {
        claimsSupplied.add(mkClaim(issuer, "phone_number", new JsonPrimitive(auth.getUserInfo().getPhoneNumber())));
    }
    if (userInfo.getPhoneNumberVerified() != null) {
        claimsSupplied.add(mkClaim(issuer, "phone_number_verified", new JsonPrimitive(auth.getUserInfo().getPhoneNumberVerified())));
    }
    if (userInfo.getPreferredUsername() != null) {
        claimsSupplied.add(mkClaim(issuer, "preferred_username", new JsonPrimitive(auth.getUserInfo().getPreferredUsername())));
    }
    if (userInfo.getProfile() != null) {
        claimsSupplied.add(mkClaim(issuer, "profile", new JsonPrimitive(auth.getUserInfo().getProfile())));
    }
    ticket.setClaimsSupplied(claimsSupplied);
    PermissionTicket updatedTicket = permissionService.updateTicket(ticket);
    if (Strings.isNullOrEmpty(redirectUri)) {
        if (client.getClaimsRedirectUris().size() == 1) {
            // get the first (and only) redirect URI to use here
            redirectUri = client.getClaimsRedirectUris().iterator().next();
            logger.info("No redirect URI passed in, using registered value: " + redirectUri);
        } else {
            throw new RedirectMismatchException("Unable to find redirect URI and none passed in.");
        }
    } else {
        if (!client.getClaimsRedirectUris().contains(redirectUri)) {
            throw new RedirectMismatchException("Claims redirect did not match the registered values.");
        }
    }
    UriComponentsBuilder template = UriComponentsBuilder.fromUriString(redirectUri);
    template.queryParam("authorization_state", "claims_submitted");
    if (!Strings.isNullOrEmpty(state)) {
        template.queryParam("state", state);
    }
    String uriString = template.toUriString();
    logger.info("Redirecting to " + uriString);
    return "redirect:" + uriString;
}
Also used : ClientDetailsEntity(org.mitre.oauth2.model.ClientDetailsEntity) PermissionTicket(org.mitre.uma.model.PermissionTicket) JsonPrimitive(com.google.gson.JsonPrimitive) UriComponentsBuilder(org.springframework.web.util.UriComponentsBuilder) RedirectMismatchException(org.springframework.security.oauth2.common.exceptions.RedirectMismatchException) UserInfo(org.mitre.openid.connect.model.UserInfo) Claim(org.mitre.uma.model.Claim) RequestMapping(org.springframework.web.bind.annotation.RequestMapping)

Aggregations

UserInfo (org.mitre.openid.connect.model.UserInfo)27 Test (org.junit.Test)10 ClientDetailsEntity (org.mitre.oauth2.model.ClientDetailsEntity)8 DefaultUserInfo (org.mitre.openid.connect.model.DefaultUserInfo)7 RequestMapping (org.springframework.web.bind.annotation.RequestMapping)7 Date (java.util.Date)5 OAuth2AccessTokenEntity (org.mitre.oauth2.model.OAuth2AccessTokenEntity)5 ImmutableMap (com.google.common.collect.ImmutableMap)4 OIDCAuthenticationToken (org.mitre.openid.connect.model.OIDCAuthenticationToken)4 JsonObject (com.google.gson.JsonObject)3 JWT (com.nimbusds.jwt.JWT)3 HashMap (java.util.HashMap)3 OAuth2RefreshTokenEntity (org.mitre.oauth2.model.OAuth2RefreshTokenEntity)3 JWTClaimsSet (com.nimbusds.jwt.JWTClaimsSet)2 HashSet (java.util.HashSet)2 Map (java.util.Map)2 PreAuthorize (org.springframework.security.access.prepost.PreAuthorize)2 OAuth2Authentication (org.springframework.security.oauth2.provider.OAuth2Authentication)2 ImmutableSet (com.google.common.collect.ImmutableSet)1 JsonPrimitive (com.google.gson.JsonPrimitive)1