Search in sources :

Example 71 with Authentication

use of org.olat.basesecurity.Authentication in project openolat by klemens.

the class UserAuthenticationMgmtTest method deleteAuthentications.

@Test
public void deleteAuthentications() throws IOException, URISyntaxException {
    RestConnection conn = new RestConnection();
    assertTrue(conn.login("administrator", "openolat"));
    // create an authentication token
    Identity adminIdent = securityManager.findIdentityByName("administrator");
    Authentication authentication = securityManager.createAndPersistAuthentication(adminIdent, "REST-A-2", "administrator", "credentials", Encoder.Algorithm.sha512);
    assertTrue(authentication != null && authentication.getKey() != null && authentication.getKey().longValue() > 0);
    DBFactory.getInstance().intermediateCommit();
    // delete an authentication token
    URI request = UriBuilder.fromUri(getContextURI()).path("/users/administrator/auth/" + authentication.getKey()).build();
    HttpDelete method = conn.createDelete(request, MediaType.APPLICATION_XML);
    HttpResponse response = conn.execute(method);
    assertEquals(200, response.getStatusLine().getStatusCode());
    EntityUtils.consume(response.getEntity());
    Authentication refAuth = securityManager.findAuthentication(adminIdent, "REST-A-2");
    assertNull(refAuth);
    conn.shutdown();
}
Also used : HttpDelete(org.apache.http.client.methods.HttpDelete) Authentication(org.olat.basesecurity.Authentication) HttpResponse(org.apache.http.HttpResponse) Identity(org.olat.core.id.Identity) URI(java.net.URI) Test(org.junit.Test)

Example 72 with Authentication

use of org.olat.basesecurity.Authentication in project openolat by klemens.

the class UserAuthenticationMgmtTest method createAuthentications_checkDuplicate.

/**
 * Check if the REST call return a specific error if the pair authentication user name and provider
 * is already used.
 */
@Test
public void createAuthentications_checkDuplicate() throws IOException, URISyntaxException {
    Identity id1 = JunitTestHelper.createAndPersistIdentityAsRndUser("check-auth-1");
    Identity id2 = JunitTestHelper.createAndPersistIdentityAsRndUser("check-auth-2");
    String authUsername = UUID.randomUUID().toString();
    dbInstance.commitAndCloseSession();
    RestConnection conn = new RestConnection();
    Assert.assertTrue(conn.login("administrator", "openolat"));
    // set the first authentication
    AuthenticationVO vo1 = new AuthenticationVO();
    vo1.setAuthUsername(authUsername);
    vo1.setIdentityKey(id1.getKey());
    vo1.setProvider("REST-API");
    vo1.setCredential("credentials");
    URI request1 = UriBuilder.fromUri(getContextURI()).path("/users/" + id1.getName() + "/auth").build();
    HttpPut method1 = conn.createPut(request1, MediaType.APPLICATION_JSON, true);
    conn.addJsonEntity(method1, vo1);
    HttpResponse response1 = conn.execute(method1);
    Assert.assertEquals(200, response1.getStatusLine().getStatusCode());
    conn.parse(response1, AuthenticationVO.class);
    Authentication refAuth1 = securityManager.findAuthentication(id1, "REST-API");
    Assert.assertNotNull(refAuth1);
    Assert.assertEquals(id1, refAuth1.getIdentity());
    // set the second which duplicates the first
    AuthenticationVO vo2 = new AuthenticationVO();
    vo2.setAuthUsername(authUsername);
    vo2.setIdentityKey(id2.getKey());
    vo2.setProvider("REST-API");
    vo2.setCredential("credentials");
    URI request2 = UriBuilder.fromUri(getContextURI()).path("/users/" + id2.getName() + "/auth").build();
    HttpPut method2 = conn.createPut(request2, MediaType.APPLICATION_JSON, true);
    conn.addJsonEntity(method2, vo2);
    HttpResponse response2 = conn.execute(method2);
    Assert.assertEquals(409, response2.getStatusLine().getStatusCode());
    ErrorVO error = conn.parse(response2, ErrorVO.class);
    Assert.assertNotNull(error);
    conn.shutdown();
}
Also used : ErrorVO(org.olat.restapi.support.vo.ErrorVO) Authentication(org.olat.basesecurity.Authentication) HttpResponse(org.apache.http.HttpResponse) Identity(org.olat.core.id.Identity) AuthenticationVO(org.olat.restapi.support.vo.AuthenticationVO) URI(java.net.URI) HttpPut(org.apache.http.client.methods.HttpPut) Test(org.junit.Test)

Example 73 with Authentication

use of org.olat.basesecurity.Authentication in project openolat by klemens.

the class ViteroManager method checkUsers.

public CheckUserInfo checkUsers() throws VmsNotAvailableException {
    final String[] authProviders = new String[] { VMS_PROVIDER };
    final String prefix = getVmsUsernamePrefix();
    int authenticationCreated = 0;
    int authenticationDeleted = 0;
    // check if vms user with an openolat login exists on vms server
    // without the need authentication object in openolat.
    List<Usertype> users = getCustomersUsers();
    if (users != null && users.size() > 0) {
        for (Usertype user : users) {
            String vmsUsername = user.getUsername();
            if (vmsUsername.startsWith(prefix)) {
                String olatUsername = vmsUsername.substring(prefix.length(), vmsUsername.length());
                List<Identity> identities = securityManager.getIdentitiesByPowerSearch(olatUsername, null, false, null, null, authProviders, null, null, null, null, null);
                if (identities.isEmpty()) {
                    Identity identity = securityManager.findIdentityByName(olatUsername);
                    if (identity != null) {
                        authenticationCreated++;
                        securityManager.createAndPersistAuthentication(identity, VMS_PROVIDER, Integer.toString(user.getId()), null, null);
                        log.info("Recreate VMS authentication for: " + identity.getName());
                    }
                }
            }
        }
    }
    // check if all openolat users with a vms authentication have an user
    // on the vms server
    List<Identity> identities = securityManager.getIdentitiesByPowerSearch(null, null, false, null, null, authProviders, null, null, null, null, null);
    for (Identity identity : identities) {
        Authentication authentication = securityManager.findAuthentication(identity, VMS_PROVIDER);
        String vmsUserId = authentication.getAuthusername();
        boolean foundIt = false;
        for (Usertype user : users) {
            if (vmsUserId.equals(Integer.toString(user.getId()))) {
                foundIt = true;
            }
        }
        if (!foundIt) {
            securityManager.deleteAuthentication(authentication);
            authenticationDeleted++;
        }
    }
    CheckUserInfo infos = new CheckUserInfo();
    infos.setAuthenticationCreated(authenticationCreated);
    infos.setAuthenticationDeleted(authenticationDeleted);
    return infos;
}
Also used : Usertype(de.vitero.schema.user.Usertype) CheckUserInfo(org.olat.modules.vitero.model.CheckUserInfo) Authentication(org.olat.basesecurity.Authentication) Identity(org.olat.core.id.Identity)

Example 74 with Authentication

use of org.olat.basesecurity.Authentication in project openolat by klemens.

the class FeedMediaDispatcher method validAuthentication.

/**
 * Authenticates the identity by token
 *
 * @param identity
 * @param token
 * @return True if authentication is valid
 */
private boolean validAuthentication(Identity identity, String token) {
    boolean valid = false;
    BaseSecurity secMgr = BaseSecurityManager.getInstance();
    Authentication authentication = secMgr.findAuthenticationByAuthusername(identity.getKey().toString(), TOKEN_PROVIDER);
    if (authentication != null && authentication.getCredential().equals(token)) {
        valid = true;
    }
    return valid;
}
Also used : Authentication(org.olat.basesecurity.Authentication) BaseSecurity(org.olat.basesecurity.BaseSecurity)

Example 75 with Authentication

use of org.olat.basesecurity.Authentication in project openolat by klemens.

the class ShibbolethDispatcher method execute.

/**
 * Main method called by OpenOLATServlet.
 * This processess all shibboleth requests.
 *
 * @param req
 * @param resp
 * @param uriPrefix
 */
@Override
public void execute(HttpServletRequest req, HttpServletResponse resp) {
    if (translator == null) {
        translator = Util.createPackageTranslator(ShibbolethDispatcher.class, I18nModule.getDefaultLocale());
    }
    if (!shibbolethModule.isEnableShibbolethLogins()) {
        throw new OLATSecurityException("Got shibboleth request but shibboleth is not enabled");
    }
    String uriPrefix = DispatcherModule.getLegacyUriPrefix(req);
    Map<String, String> attributesMap = getShibbolethAttributesFromRequest(req);
    ShibbolethAttributes shibbolethAttriutes = CoreSpringFactory.getImpl(ShibbolethAttributes.class);
    shibbolethAttriutes.init(attributesMap);
    String uid = shibbolethAttriutes.getUID();
    if (uid == null) {
        handleException(new ShibbolethException(ShibbolethException.UNIQUE_ID_NOT_FOUND, "Unable to get unique identifier for subject. Make sure you are listed in the metadata.xml file and your resources your are trying to access are available and your are allowed to see them. (Resourceregistry). "), req, resp, translator);
        return;
    }
    if (!authorization(req, resp, shibbolethAttriutes)) {
        return;
    }
    UserRequest ureq = null;
    try {
        // upon creation URL is checked for
        ureq = new UserRequestImpl(uriPrefix, req, resp);
    } catch (NumberFormatException nfe) {
        // a 404 message must be shown -> e.g. robots correct their links.
        if (log.isDebug()) {
            log.debug("Bad Request " + req.getPathInfo());
        }
        DispatcherModule.sendBadRequest(req.getPathInfo(), resp);
        return;
    }
    Authentication auth = securityManager.findAuthenticationByAuthusername(uid, PROVIDER_SHIB);
    if (auth == null) {
        // no matching authentication...
        ShibbolethRegistrationController.putShibAttributes(req, shibbolethAttriutes);
        ShibbolethRegistrationController.putShibUniqueID(req, uid);
        redirectToShibbolethRegistration(resp);
        return;
    }
    if (ureq.getUserSession() != null) {
        // re-init the activity logger
        ThreadLocalUserActivityLoggerInstaller.initUserActivityLogger(req);
    }
    int loginStatus = AuthHelper.doLogin(auth.getIdentity(), ShibbolethDispatcher.PROVIDER_SHIB, ureq);
    if (loginStatus != AuthHelper.LOGIN_OK) {
        if (loginStatus == AuthHelper.LOGIN_NOTAVAILABLE) {
            DispatcherModule.redirectToServiceNotAvailable(resp);
        } else {
            // error, redirect to login screen
            DispatcherModule.redirectToDefaultDispatcher(resp);
        }
        return;
    }
    // Successful login
    Identity authenticationedIdentity = ureq.getIdentity();
    userDeletionManager.setIdentityAsActiv(authenticationedIdentity);
    shibbolethManager.syncUser(authenticationedIdentity, shibbolethAttriutes);
    ureq.getUserSession().getIdentityEnvironment().addAttributes(shibbolethModule.getAttributeTranslator().translateAttributesMap(shibbolethAttriutes.toMap()));
    MediaResource mr = ureq.getDispatchResult().getResultingMediaResource();
    if (mr instanceof RedirectMediaResource) {
        RedirectMediaResource rmr = (RedirectMediaResource) mr;
        rmr.prepare(resp);
    } else {
        // error, redirect to login screen
        DispatcherModule.redirectToDefaultDispatcher(resp);
    }
}
Also used : ShibbolethAttributes(org.olat.shibboleth.manager.ShibbolethAttributes) Authentication(org.olat.basesecurity.Authentication) OLATSecurityException(org.olat.core.logging.OLATSecurityException) RedirectMediaResource(org.olat.core.gui.media.RedirectMediaResource) MediaResource(org.olat.core.gui.media.MediaResource) RedirectMediaResource(org.olat.core.gui.media.RedirectMediaResource) Identity(org.olat.core.id.Identity) UserRequest(org.olat.core.gui.UserRequest) UserRequestImpl(org.olat.core.gui.UserRequestImpl)

Aggregations

Authentication (org.olat.basesecurity.Authentication)82 Identity (org.olat.core.id.Identity)46 BaseSecurity (org.olat.basesecurity.BaseSecurity)16 Test (org.junit.Test)10 RestSecurityHelper.getIdentity (org.olat.restapi.security.RestSecurityHelper.getIdentity)8 AuthenticationVO (org.olat.restapi.support.vo.AuthenticationVO)8 URI (java.net.URI)6 ArrayList (java.util.ArrayList)6 Produces (javax.ws.rs.Produces)6 HttpResponse (org.apache.http.HttpResponse)6 SecurityGroup (org.olat.basesecurity.SecurityGroup)6 Locale (java.util.Locale)4 GET (javax.ws.rs.GET)4 HttpPut (org.apache.http.client.methods.HttpPut)4 AssertException (org.olat.core.logging.AssertException)4 DBRuntimeException (org.olat.core.logging.DBRuntimeException)4 Algorithm (org.olat.core.util.Encoder.Algorithm)4 TemporaryKey (org.olat.registration.TemporaryKey)4 ErrorVO (org.olat.restapi.support.vo.ErrorVO)4 UserPropertyHandler (org.olat.user.propertyhandlers.UserPropertyHandler)4