Search in sources :

Example 1 with Authentication

use of org.olat.basesecurity.Authentication in project OpenOLAT by OpenOLAT.

the class LTIManagerImpl method createPersonSourceId.

/**
 * A comma-separated list of URN values for roles. If this list is non-empty,
 * it should contain at least one role from the LIS System Role, LIS
 * Institution Role, or LIS Context Role vocabularies (See Appendix A of
 * LTI_BasicLTI_Implementation_Guide_rev1.pdf).
 *
 * @param roles
 * @return
 */
/*private String setRoles(Identity identity, Roles roles, LTIContext context) {
		StringBuilder rolesStr;
		if (roles.isGuestOnly()) {
			rolesStr = new StringBuilder("Guest");
		} else {
			rolesStr = new StringBuilder("Learner");
			boolean coach = context.isCoach(identity);
			if (coach) {
				rolesStr.append(",").append("Instructor");
			}
			boolean admin = context.isAdmin(identity);
			if (roles.isOLATAdmin() || admin) {
				rolesStr.append(",").append("Administrator");
			}
		}

		return rolesStr.toString();
	}*/
private String createPersonSourceId(Identity identity) {
    // The person source ID is used as user identifier. The rule is as follows:
    // 1) if a shibboleth authentication token is availble, use the ShibbolethModule.getDefaultUIDAttribute()
    // 2) if a LDAP authentication token is available, use the LDAPConstants.LDAP_USER_IDENTIFYER
    // 3) as fallback use the system URL together with the identity username
    String personSourceId = null;
    // Use the shibboleth ID as person source identificator
    List<Authentication> authMethods = BaseSecurityManager.getInstance().getAuthentications(identity);
    for (Authentication method : authMethods) {
        String provider = method.getProvider();
        if (ShibbolethDispatcher.PROVIDER_SHIB.equals(provider)) {
            personSourceId = method.getAuthusername();
            // done, case 1)
            break;
        } else if (LDAPAuthenticationController.PROVIDER_LDAP.equals(provider)) {
            personSourceId = method.getAuthusername();
        // normally done, case 2). however, lets continue because we might still find a case 1)
        }
    // ignore all other authentication providers
    }
    if (!StringHelper.containsNonWhitespace(personSourceId)) {
        // fallback to the serverDomainName:identityId as case 3)
        personSourceId = Settings.getServerDomainName() + ":" + identity.getKey();
    }
    return personSourceId;
}
Also used : Authentication(org.olat.basesecurity.Authentication)

Example 2 with Authentication

use of org.olat.basesecurity.Authentication in project OpenOLAT by OpenOLAT.

the class ShibbolethRegistrationController method event.

@Override
public void event(UserRequest ureq, Controller source, Event event) {
    if (source == migrationForm) {
        if (event == Event.CANCELLED_EVENT) {
            mainContainer.setPage(VELOCITY_ROOT + "/register.html");
        } else if (event == Event.DONE_EVENT) {
            state = STATE_MIGRATED_SHIB_USER;
            mainContainer.setPage(VELOCITY_ROOT + "/disclaimer.html");
        }
    } else if (source == regWithUserPropForm) {
        if (event == Event.CANCELLED_EVENT) {
            mainContainer.setPage(VELOCITY_ROOT + "/register.html");
        } else if (event == Event.DONE_EVENT) {
            state = STATE_NEW_SHIB_USER;
            mainContainer.setPage(VELOCITY_ROOT + "/disclaimer.html");
        }
    } else if (source == regForm) {
        if (event == Event.DONE_EVENT) {
            String choosenLogin = regForm.getLogin();
            BaseSecurity secMgr = BaseSecurityManager.getInstance();
            Identity identity = secMgr.findIdentityByName(choosenLogin);
            if (identity == null) {
                // ok, create new user
                if (isMandatoryUserPropertyMissing()) {
                    regWithUserPropForm = new ShibbolethRegistrationUserPropertiesFrom(ureq, getWindowControl(), shibbolethAttributes);
                    regWithUserPropForm.addControllerListener(this);
                    mainContainer.put("getUserPropsForm", regWithUserPropForm.getInitialComponent());
                    mainContainer.setPage(VELOCITY_ROOT + "/register_user_props.html");
                } else {
                    state = STATE_NEW_SHIB_USER;
                    mainContainer.setPage(VELOCITY_ROOT + "/disclaimer.html");
                }
            } else {
                // offer identity migration, if OLAT provider exists
                Authentication auth = secMgr.findAuthentication(identity, BaseSecurityModule.getDefaultAuthProviderIdentifier());
                if (auth == null) {
                    // no OLAT provider, migration not possible...
                    getWindowControl().setError(translator.translate("sr.error.loginexists", new String[] { WebappHelper.getMailConfig("mailSupport") }));
                } else {
                    // OLAT provider exists, offer migration...
                    migrationForm = new ShibbolethMigrationForm(ureq, getWindowControl(), auth);
                    migrationForm.addControllerListener(this);
                    mainContainer.put("migrationForm", migrationForm.getInitialComponent());
                    mainContainer.setPage(VELOCITY_ROOT + "/migration.html");
                }
            }
        }
    } else if (source == languageChooserController) {
        if (event == Event.DONE_EVENT) {
            // language choosed
            mainContainer.setPage(VELOCITY_ROOT + "/register.html");
            ureq.getUserSession().removeEntry(LocaleNegotiator.NEGOTIATED_LOCALE);
        } else if (event instanceof LanguageChangedEvent) {
            LanguageChangedEvent lcev = (LanguageChangedEvent) event;
            translator.setLocale(lcev.getNewLocale());
            dclController.changeLocale(lcev.getNewLocale());
        }
    } else if (source == dclController) {
        if (event == Event.DONE_EVENT) {
            // disclaimer accepted...
            if (state == STATE_NEW_SHIB_USER) {
                // ...proceed and create user
                String choosenLogin;
                if (regForm == null) {
                    choosenLogin = proposedUsername;
                } else {
                    choosenLogin = regForm.getLogin();
                }
                // check if login has been taken by another user in the meantime...
                BaseSecurity secMgr = BaseSecurityManager.getInstance();
                // check if login has been taken by another user in the meantime...
                Identity identity = secMgr.findIdentityByName(choosenLogin);
                if (identity != null) {
                    getWindowControl().setError(translator.translate("sr.login.meantimetaken"));
                    mainContainer.setPage(VELOCITY_ROOT + "/register.html");
                    state = STATE_UNDEFINED;
                    return;
                }
                String email = shibbolethAttributes.getValueForUserPropertyName(UserConstants.EMAIL);
                if (!UserManager.getInstance().isEmailAllowed(email)) {
                    // error, email already exists. should actually not happen if OLAT Authenticator has
                    // been set after removing shibboleth authenticator
                    getWindowControl().setError(translator.translate("sr.error.emailexists", new String[] { WebappHelper.getMailConfig("mailSupport") }));
                    mainContainer.setPage(VELOCITY_ROOT + "/register.html");
                    state = STATE_UNDEFINED;
                    return;
                }
                identity = shibbolethManager.createUser(choosenLogin, shibbolethUniqueID, locale.getLanguage(), shibbolethAttributes);
                // tell system that this user did accept the disclaimer
                CoreSpringFactory.getImpl(RegistrationManager.class).setHasConfirmedDislaimer(identity);
                doLogin(identity, ureq);
                return;
            } else if (state == STATE_MIGRATED_SHIB_USER) {
                // ...proceed and migrate user
                // create additional authentication
                Authentication auth = migrationForm.getAuthentication();
                Identity authenticationedIdentity = auth.getIdentity();
                BaseSecurity secMgr = BaseSecurityManager.getInstance();
                secMgr.createAndPersistAuthentication(authenticationedIdentity, ShibbolethDispatcher.PROVIDER_SHIB, shibbolethUniqueID, null, null);
                // update user profile
                shibbolethManager.syncUser(authenticationedIdentity, shibbolethAttributes);
                doLogin(authenticationedIdentity, ureq);
                return;
            }
        } else if (event == Event.CANCELLED_EVENT) {
            mainContainer.setPage(VELOCITY_ROOT + "/register.html");
            getWindowControl().setError(translator.translate("sr.error.disclaimer"));
        }
    }
}
Also used : RegistrationManager(org.olat.registration.RegistrationManager) Authentication(org.olat.basesecurity.Authentication) LanguageChangedEvent(org.olat.core.commons.chiefcontrollers.LanguageChangedEvent) Identity(org.olat.core.id.Identity) BaseSecurity(org.olat.basesecurity.BaseSecurity)

Example 3 with Authentication

use of org.olat.basesecurity.Authentication in project OpenOLAT by OpenOLAT.

the class UserAuthenticationMgmtTest method createAuthentications.

@Test
public void createAuthentications() throws IOException, URISyntaxException {
    RestConnection conn = new RestConnection();
    Identity adminIdent = securityManager.findIdentityByName("administrator");
    try {
        Authentication refAuth = securityManager.findAuthentication(adminIdent, "REST-API");
        if (refAuth != null) {
            securityManager.deleteAuthentication(refAuth);
        }
    } catch (Exception e) {
    // 
    }
    DBFactory.getInstance().commitAndCloseSession();
    assertTrue(conn.login("administrator", "openolat"));
    AuthenticationVO vo = new AuthenticationVO();
    vo.setAuthUsername("administrator");
    vo.setIdentityKey(adminIdent.getKey());
    vo.setProvider("REST-API");
    vo.setCredential("credentials");
    URI request = UriBuilder.fromUri(getContextURI()).path("/users/administrator/auth").build();
    HttpPut method = conn.createPut(request, MediaType.APPLICATION_JSON, true);
    conn.addJsonEntity(method, vo);
    HttpResponse response = conn.execute(method);
    assertTrue(response.getStatusLine().getStatusCode() == 200 || response.getStatusLine().getStatusCode() == 201);
    AuthenticationVO savedAuth = conn.parse(response, AuthenticationVO.class);
    Authentication refAuth = securityManager.findAuthentication(adminIdent, "REST-API");
    assertNotNull(refAuth);
    assertNotNull(refAuth.getKey());
    assertTrue(refAuth.getKey().longValue() > 0);
    assertNotNull(savedAuth);
    assertNotNull(savedAuth.getKey());
    assertTrue(savedAuth.getKey().longValue() > 0);
    assertEquals(refAuth.getKey(), savedAuth.getKey());
    assertEquals(refAuth.getAuthusername(), savedAuth.getAuthUsername());
    assertEquals(refAuth.getIdentity().getKey(), savedAuth.getIdentityKey());
    assertEquals(refAuth.getProvider(), savedAuth.getProvider());
    assertEquals(refAuth.getCredential(), savedAuth.getCredential());
    conn.shutdown();
}
Also used : 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) URISyntaxException(java.net.URISyntaxException) IOException(java.io.IOException) HttpPut(org.apache.http.client.methods.HttpPut) Test(org.junit.Test)

Example 4 with Authentication

use of org.olat.basesecurity.Authentication in project OpenOLAT by OpenOLAT.

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 5 with Authentication

use of org.olat.basesecurity.Authentication in project OpenOLAT by OpenOLAT.

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)

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