org.apache.cxf.rs.security.oidc.common.UserInfo Java Examples

The following examples show how to use org.apache.cxf.rs.security.oidc.common.UserInfo. 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: OidcUserInfoProvider.java    From cxf with Apache License 2.0 6 votes vote down vote up
@Override
public UserInfoContext createContext(Message m) {
    final OidcClientTokenContext ctx = (OidcClientTokenContext)
        m.getContent(ClientTokenContext.class);
    final UserInfo userInfo = ctx != null ? ctx.getUserInfo() : m.getContent(UserInfo.class);
    if (userInfo != null) {
        final IdToken idToken = ctx != null ? ctx.getIdToken() : m.getContent(IdToken.class);
        return new UserInfoContext() {

            @Override
            public UserInfo getUserInfo() {
                return userInfo;
            }

            @Override
            public IdToken getIdToken() {
                return idToken;
            }

        };
    }
    return null;

}
 
Example #2
Source File: OIDCClientLogic.java    From syncope with Apache License 2.0 6 votes vote down vote up
private static UserInfo getUserInfo(
    final String endpoint,
    final String accessToken,
    final IdToken idToken,
    final Consumer consumer) {

    WebClient userInfoServiceClient = WebClient.create(endpoint, List.of(new JsonMapObjectProvider())).
            accept(MediaType.APPLICATION_JSON);
    ClientAccessToken clientAccessToken =
            new ClientAccessToken(OAuthConstants.BEARER_AUTHORIZATION_SCHEME, accessToken);
    UserInfoClient userInfoClient = new UserInfoClient();
    userInfoClient.setUserInfoServiceClient(userInfoServiceClient);
    UserInfo userInfo = null;
    try {
        userInfo = userInfoClient.getUserInfo(clientAccessToken, idToken, consumer);
    } catch (Exception e) {
        LOG.error("While getting the userInfo", e);
        SyncopeClientException sce = SyncopeClientException.build(ClientExceptionType.Unknown);
        sce.getElements().add(e.getMessage());
        throw sce;
    }
    return userInfo;
}
 
Example #3
Source File: UserAccountService.java    From g-suite-identity-sync with Apache License 2.0 6 votes vote down vote up
@PUT
public Response updateAccount(@Valid UpdateAccountData data) {
    ResponseBuilder response;
    UserInfo userInfo = oidcContext.getUserInfo();
    String subject = userInfo.getSubject();
    if (ldapService.accountExists(subject)) {
        String gsuiteDomain = gsuiteDirService.getDomainName();
        Set<String> emails = Collections.singleton(userInfo.getEmail());
        LdapAccount account = toLdapAccount(gsuiteDomain, userInfo, emails, data);
        ldapService.updateAccount(account);
        response = Response.ok();
        if (data.isSaveGSuitePassword() && isInternalAccount(userInfo, gsuiteDomain)) {
            try {
                gsuiteDirService.updateUserPassword(subject, data.getPassword());
            } catch (InvalidPasswordException e) {
                log.warn("Can't update gsuite password", e);
            }
        }
    } else {
        response = Response.ok().status(Response.Status.CONFLICT);
    }
    return response.build();
}
 
Example #4
Source File: UserAccountService.java    From g-suite-identity-sync with Apache License 2.0 6 votes vote down vote up
@GET
@Path("prepare")
public PrepareAccountData prepareAccount() {
    final UserInfo userInfo = oidcContext.getUserInfo();
    String gsuiteDomain = gsuiteDirService.getDomainName();
    PrepareAccountData detail = new PrepareAccountData();
    detail.setGivenName(userInfo.getGivenName());
    detail.setFamilyName(userInfo.getFamilyName());
    detail.setName(userInfo.getName());
    detail.setEmail(userInfo.getEmail());
    detail.setEmails(getAccountAliases(userInfo, gsuiteDomain));
    detail.setEmailVerified(userInfo.getEmailVerified());
    detail.setRole(getAccountRole(userInfo, gsuiteDomain));
    detail.setSaveGSuitePassword(detail.getRole() == Role.INTERNAL && config.isGsuiteSyncPassword());
    GroupList userGroups = gsuiteDirService.getUserGroups(userInfo.getSubject());
    if (userGroups.getGroups() != null) {
        detail.setGroups(userGroups.getGroups().stream().map(PrepareAccountData.Group::map).collect(Collectors.toList()));
    }
    return detail;
}
 
Example #5
Source File: UserInfoClient.java    From cxf with Apache License 2.0 5 votes vote down vote up
public void validateUserInfo(UserInfo profile, IdToken idToken, Consumer client) {
    validateJwtClaims(profile, client.getClientId(), false);
    // validate subject
    if (!idToken.getSubject().equals(profile.getSubject())) {
        throw new OAuthServiceException("Invalid subject");
    }
}
 
Example #6
Source File: UserInfoProviderImpl.java    From cxf with Apache License 2.0 5 votes vote down vote up
@Override
public UserInfo getUserInfo(String clientId, UserSubject authenticatedUser, List<String> scopes) {
    UserInfo userInfo = new UserInfo();
    userInfo.setSubject(authenticatedUser.getLogin());
    userInfo.setAudience(clientId);
    userInfo.setIssuer("xyz");
    return userInfo;
}
 
Example #7
Source File: UserAccountService.java    From g-suite-identity-sync with Apache License 2.0 5 votes vote down vote up
private Set<String> getAccountAliases(UserInfo userInfo, String gsuiteDomain) {
    Set<String> result = new HashSet<>();
    result.add(userInfo.getEmail());
    if (isInternalAccount(userInfo, gsuiteDomain)) {
        GSuiteUser user = gsuiteDirService.getUser(userInfo.getSubject());
        result.addAll(user.getAliases());
    }
    return result;
}
 
Example #8
Source File: AccountUtil.java    From g-suite-identity-sync with Apache License 2.0 5 votes vote down vote up
public final static LdapAccount toLdapAccount(String gsuiteDomain, UserInfo userInfo, Set<String> emails,
        UpdateAccountData updateData) {
    LdapAccount account = new LdapAccount();
    account.setSubject(userInfo.getSubject());
    account.setGivenName(userInfo.getGivenName());
    account.setFamilyName(userInfo.getFamilyName());
    account.setName(userInfo.getName());
    account.setPassword(updateData.getPassword());
    account.setRole(getLdapRole(userInfo, gsuiteDomain));
    account.setEmails(emails);
    return account;
}
 
Example #9
Source File: AccountUtil.java    From g-suite-identity-sync with Apache License 2.0 5 votes vote down vote up
public final static LdapAccount toLdapAccount(String gsuiteDomain, UserInfo userInfo, Set<String> emails,
        CreateAccountData createData) {
    LdapAccount account = new LdapAccount();
    account.setSubject(userInfo.getSubject());
    account.setGivenName(userInfo.getGivenName());
    account.setFamilyName(userInfo.getFamilyName());
    account.setName(userInfo.getName());
    account.setPassword(createData.getPassword());
    account.setUsername(createData.getEmail());
    account.setRole(getLdapRole(userInfo, gsuiteDomain));
    account.setEmails(emails);
    return account;
}
 
Example #10
Source File: UserInfoService.java    From cxf with Apache License 2.0 5 votes vote down vote up
protected UserInfo createFromIdToken(IdToken idToken) {
    UserInfo userInfo = new UserInfo();
    userInfo.setSubject(idToken.getSubject());

    if (super.isJwsRequired()) {
        userInfo.setIssuer(idToken.getIssuer());
        userInfo.setAudience(idToken.getAudience());
    }
    if (idToken.getPreferredUserName() != null) {
        userInfo.setPreferredUserName(idToken.getPreferredUserName());
    }
    if (idToken.getName() != null) {
        userInfo.setName(idToken.getName());
    }
    if (idToken.getGivenName() != null) {
        userInfo.setGivenName(idToken.getGivenName());
    }
    if (idToken.getFamilyName() != null) {
        userInfo.setFamilyName(idToken.getFamilyName());
    }
    if (idToken.getEmail() != null) {
        userInfo.setEmail(idToken.getEmail());
    }
    if (idToken.getNickName() != null) {
        userInfo.setNickName(idToken.getNickName());
    }

    if (additionalClaims != null && !additionalClaims.isEmpty()) {
        for (String additionalClaim : additionalClaims) {
            if (idToken.containsProperty(additionalClaim)) {
                userInfo.setClaim(additionalClaim, idToken.getClaim(additionalClaim));
            }
        }
    }

    //etc
    return userInfo;
}
 
Example #11
Source File: UserInfoService.java    From cxf with Apache License 2.0 4 votes vote down vote up
@GET
@Produces({"application/json", "application/jwt" })
public Response getUserInfo() {
    OAuthContext oauth = OAuthContextUtils.getContext(mc);

    // Check the access token has the "openid" scope
    if (!oauth.getPermissions().stream()
        .map(OAuthPermission::getPermission)
        .anyMatch(OidcUtils.OPENID_SCOPE::equals)) {
        return Response.status(Status.UNAUTHORIZED).build();
    }

    UserInfo userInfo = null;
    if (userInfoProvider != null) {
        userInfo = userInfoProvider.getUserInfo(oauth.getClientId(), oauth.getSubject(),
            OAuthUtils.convertPermissionsToScopeList(oauth.getPermissions()));
    } else if (oauth.getSubject() instanceof OidcUserSubject) {
        OidcUserSubject oidcUserSubject = (OidcUserSubject)oauth.getSubject();
        userInfo = oidcUserSubject.getUserInfo();
        if (userInfo == null) {
            userInfo = createFromIdToken(oidcUserSubject.getIdToken());
        }
    }
    if (userInfo == null) {
        // Consider customizing the error code in case of UserInfo being not available
        return Response.serverError().build();
    }

    final Object responseEntity;
    // UserInfo may be returned in a clear form as JSON
    if (super.isJwsRequired() || super.isJweRequired()) {
        Client client = null;
        if (oauthDataProvider != null) {
            client = oauthDataProvider.getClient(oauth.getClientId());
        }
        responseEntity = super.processJwt(new JwtToken(userInfo), client);
    } else {
        responseEntity = convertUserInfoToResponseEntity(userInfo);
    }
    return Response.ok(responseEntity).build();

}
 
Example #12
Source File: OidcClientTokenContextImpl.java    From cxf with Apache License 2.0 4 votes vote down vote up
public void setUserInfo(UserInfo userInfo) {
    this.userInfo = userInfo;
}
 
Example #13
Source File: UserInfoService.java    From cxf with Apache License 2.0 4 votes vote down vote up
protected Object convertUserInfoToResponseEntity(UserInfo userInfo) {
    // By default a JAX-RS MessageBodyWriter is expected to serialize UserInfo.
    return convertClearUserInfoToString ? JwtUtils.claimsToJson(userInfo) : userInfo;
}
 
Example #14
Source File: OidcUserSubject.java    From cxf with Apache License 2.0 4 votes vote down vote up
@Lob
@Basic(fetch = FetchType.EAGER)
public UserInfo getUserInfo() {
    return userInfo;
}
 
Example #15
Source File: OidcClientTokenContextImpl.java    From cxf with Apache License 2.0 4 votes vote down vote up
public UserInfo getUserInfo() {
    return userInfo;
}
 
Example #16
Source File: OidcUserSubject.java    From cxf with Apache License 2.0 4 votes vote down vote up
public void setUserInfo(UserInfo userInfo) {
    this.userInfo = userInfo;
}
 
Example #17
Source File: UserInfoTest.java    From cxf with Apache License 2.0 4 votes vote down vote up
@org.junit.Test
public void testPlainUserInfo() throws Exception {
    URL busFile = UserInfoTest.class.getResource("client.xml");

    String address = "https://localhost:" + port + "/services/oidc";
    WebClient client = WebClient.create(address, OAuth2TestUtils.setupProviders(),
                                        "alice", "security", busFile.toString());

    // Save the Cookie for the second request...
    WebClient.getConfig(client).getRequestContext().put(
        org.apache.cxf.message.Message.MAINTAIN_SESSION, Boolean.TRUE);

    // Get Authorization Code
    String code = OAuth2TestUtils.getAuthorizationCode(client, "openid");
    assertNotNull(code);

    // Now get the access token
    client = WebClient.create(address, OAuth2TestUtils.setupProviders(),
                              "consumer-id", "this-is-a-secret", busFile.toString());
    // Save the Cookie for the second request...
    WebClient.getConfig(client).getRequestContext().put(
        org.apache.cxf.message.Message.MAINTAIN_SESSION, Boolean.TRUE);

    ClientAccessToken accessToken =
        OAuth2TestUtils.getAccessTokenWithAuthorizationCode(client, code);
    assertNotNull(accessToken.getTokenKey());
    assertTrue(accessToken.getApprovedScope().contains("openid"));

    String idToken = accessToken.getParameters().get("id_token");
    assertNotNull(idToken);
    validateIdToken(idToken, null);

    // Now invoke on the UserInfo service with the access token
    String userInfoAddress = "https://localhost:" + port + "/services/plain/userinfo";
    WebClient userInfoClient = WebClient.create(userInfoAddress, OAuth2TestUtils.setupProviders(),
                                                busFile.toString());
    userInfoClient.accept("application/json");
    userInfoClient.header("Authorization", "Bearer " + accessToken.getTokenKey());

    Response serviceResponse = userInfoClient.get();
    assertEquals(serviceResponse.getStatus(), 200);

    UserInfo userInfo = serviceResponse.readEntity(UserInfo.class);
    assertNotNull(userInfo);

    assertEquals("alice", userInfo.getSubject());
    assertEquals("consumer-id", userInfo.getAudience());
}
 
Example #18
Source File: UserInfoClient.java    From cxf with Apache License 2.0 4 votes vote down vote up
public UserInfo getUserInfoFromJwt(JwtToken jwt, IdToken idToken, Consumer client) {
    UserInfo profile = new UserInfo(jwt.getClaims().asMap());
    validateUserInfo(profile, idToken, client);
    return profile;
}
 
Example #19
Source File: UserInfoClient.java    From cxf with Apache License 2.0 4 votes vote down vote up
public UserInfo getUserInfoFromJwt(String profileJwtToken,
                                   IdToken idToken,
                                   Consumer client) {
    JwtToken jwt = getUserInfoJwt(profileJwtToken, client);
    return getUserInfoFromJwt(jwt, idToken, client);
}
 
Example #20
Source File: OIDCNegativeTest.java    From cxf with Apache License 2.0 4 votes vote down vote up
@org.junit.Test
public void testUserInfoRefreshToken() throws Exception {
    URL busFile = UserInfoTest.class.getResource("client.xml");

    String address = "https://localhost:" + port + "/services/";
    WebClient client = WebClient.create(address, OAuth2TestUtils.setupProviders(),
                                        "alice", "security", busFile.toString());
    // Save the Cookie for the second request...
    WebClient.getConfig(client).getRequestContext().put(
        org.apache.cxf.message.Message.MAINTAIN_SESSION, Boolean.TRUE);

    // Get Authorization Code
    String code = OAuth2TestUtils.getAuthorizationCode(client, "openid");
    assertNotNull(code);

    // Now get the access token
    client = WebClient.create(address, OAuth2TestUtils.setupProviders(),
                              "consumer-id", "this-is-a-secret", busFile.toString());
    // Save the Cookie for the second request...
    WebClient.getConfig(client).getRequestContext().put(
        org.apache.cxf.message.Message.MAINTAIN_SESSION, Boolean.TRUE);

    ClientAccessToken accessToken =
        OAuth2TestUtils.getAccessTokenWithAuthorizationCode(client, code);
    assertNotNull(accessToken.getTokenKey());
    String oldAccessToken = accessToken.getTokenKey();
    assertTrue(accessToken.getApprovedScope().contains("openid"));

    String idToken = accessToken.getParameters().get("id_token");
    assertNotNull(idToken);

    // Refresh the access token
    client.type("application/x-www-form-urlencoded").accept("application/json");

    Form form = new Form();
    form.param("grant_type", "refresh_token");
    form.param("refresh_token", accessToken.getRefreshToken());
    form.param("client_id", "consumer-id");
    form.param("scope", "openid");
    Response response = client.post(form);

    accessToken = response.readEntity(ClientAccessToken.class);
    assertNotNull(accessToken.getTokenKey());
    assertNotNull(accessToken.getRefreshToken());
    accessToken.getParameters().get("id_token");
    assertNotNull(idToken);
    String newAccessToken = accessToken.getTokenKey();

    // Now test the UserInfoService.

    // The old Access Token should fail
    String userInfoAddress = "https://localhost:" + port + "/ui/plain/userinfo";
    WebClient userInfoClient = WebClient.create(userInfoAddress, OAuth2TestUtils.setupProviders(),
                                                busFile.toString());
    userInfoClient.accept("application/json");
    userInfoClient.header("Authorization", "Bearer " + oldAccessToken);

    Response serviceResponse = userInfoClient.get();
    assertEquals(serviceResponse.getStatus(), 401);

    // The refreshed Access Token should work
    userInfoClient.replaceHeader("Authorization", "Bearer " + newAccessToken);
    serviceResponse = userInfoClient.get();
    assertEquals(serviceResponse.getStatus(), 200);

    UserInfo userInfo = serviceResponse.readEntity(UserInfo.class);
    assertNotNull(userInfo);

    assertEquals("alice", userInfo.getSubject());
    assertEquals("consumer-id", userInfo.getAudience());
}
 
Example #21
Source File: UserAccountService.java    From g-suite-identity-sync with Apache License 2.0 4 votes vote down vote up
@PUT
@Path("groups")
public void syncGroups() {
    UserInfo userInfo = oidcContext.getUserInfo();
    syncService.synchronizeUserGroups(userInfo);
}
 
Example #22
Source File: AccountUtil.java    From g-suite-identity-sync with Apache License 2.0 4 votes vote down vote up
public static final LdapAccount.Role getLdapRole(UserInfo userInfo, String gsuiteDomain) {
    return isInternalAccount(userInfo, gsuiteDomain) ? LdapAccount.Role.INTERNAL : LdapAccount.Role.EXTERNAL;
}
 
Example #23
Source File: AccountUtil.java    From g-suite-identity-sync with Apache License 2.0 4 votes vote down vote up
public static final Role getAccountRole(UserInfo userInfo, String gsuiteDomain) {
    return isInternalAccount(userInfo, gsuiteDomain) ? Role.INTERNAL : Role.EXTERNAL;
}
 
Example #24
Source File: AccountUtil.java    From g-suite-identity-sync with Apache License 2.0 4 votes vote down vote up
public static final boolean isInternalAccount(UserInfo info, String gsuiteDomain) {
    return gsuiteDomain.equals(info.getProperty("hd"));
}
 
Example #25
Source File: AccountUtil.java    From g-suite-identity-sync with Apache License 2.0 4 votes vote down vote up
public static final LdapAccount.Role getLdapRole(UserInfo userInfo, String gsuiteDomain) {
    return isInternalAccount(userInfo, gsuiteDomain) ? LdapAccount.Role.INTERNAL : LdapAccount.Role.EXTERNAL;
}
 
Example #26
Source File: AccountUtil.java    From g-suite-identity-sync with Apache License 2.0 4 votes vote down vote up
public static final boolean isInternalAccount(UserInfo info, String gsuiteDomain) {
    return gsuiteDomain.equals(info.getProperty("hd"));
}
 
Example #27
Source File: UserInfoContext.java    From cxf with Apache License 2.0 votes vote down vote up
UserInfo getUserInfo(); 
Example #28
Source File: AccountSyncService.java    From g-suite-identity-sync with Apache License 2.0 votes vote down vote up
void synchronizeUserGroups(UserInfo userInfo); 
Example #29
Source File: UserInfoProvider.java    From cxf with Apache License 2.0 votes vote down vote up
UserInfo getUserInfo(String clientId, UserSubject authenticatedUser, List<String> scopes);