Search in sources :

Example 6 with User

use of com.predic8.membrane.core.interceptor.registration.entity.User in project service-proxy by membrane.

the class OAuth2ResourceInterceptor method handleRequest.

public boolean handleRequest(Exchange exc, String state, String publicURL, Session session) throws Exception {
    String path = uriFactory.create(exc.getDestinations().get(0)).getPath();
    if (path == null)
        return false;
    if (path.endsWith("/oauth2callback")) {
        try {
            Map<String, String> params = URLParamUtil.getParams(uriFactory, exc);
            String state2 = params.get("state");
            if (state2 == null)
                throw new RuntimeException("No CSRF token.");
            Map<String, String> param = URLParamUtil.parseQueryString(state2);
            if (param == null || !param.containsKey("security_token"))
                throw new RuntimeException("No CSRF token.");
            boolean csrfMatch = false;
            for (String state3 : stateToOriginalUrl.keySet()) if (param.get("security_token").equals(state3))
                csrfMatch = true;
            if (!csrfMatch)
                throw new RuntimeException("CSRF token mismatch.");
            Request originalRequest = stateToOriginalUrl.get(param.get("security_token"));
            String url = originalRequest.getUri();
            if (url == null)
                url = "/";
            stateToOriginalUrl.remove(state2);
            if (log.isDebugEnabled())
                log.debug("CSRF token match.");
            String code = params.get("code");
            if (code == null)
                throw new RuntimeException("No code received.");
            Exchange e = new Request.Builder().post(auth.getTokenEndpoint()).header(Header.CONTENT_TYPE, "application/x-www-form-urlencoded").header(Header.ACCEPT, "application/json").header(Header.USER_AGENT, Constants.USERAGENT).body("code=" + code + "&client_id=" + auth.getClientId() + "&client_secret=" + auth.getClientSecret() + "&redirect_uri=" + publicURL + "oauth2callback" + "&grant_type=authorization_code").buildExchange();
            LogInterceptor logi = null;
            if (log.isDebugEnabled()) {
                logi = new LogInterceptor();
                logi.setHeaderOnly(false);
                logi.handleRequest(e);
            }
            Response response = auth.doRequest(e);
            if (response.getStatusCode() != 200) {
                response.getBody().read();
                throw new RuntimeException("Authentication server returned " + response.getStatusCode() + ".");
            }
            if (log.isDebugEnabled())
                logi.handleResponse(e);
            HashMap<String, String> json = Util.parseSimpleJSONResponse(response);
            if (!json.containsKey("access_token"))
                throw new RuntimeException("No access_token received.");
            // and also "scope": "", "token_type": "bearer"
            String token = (String) json.get("access_token");
            OAuth2AnswerParameters oauth2Answer = new OAuth2AnswerParameters();
            synchronized (session) {
                // saving for logout
                session.getUserAttributes().put("access_token", token);
            }
            oauth2Answer.setAccessToken(token);
            oauth2Answer.setTokenType(json.get("token_type"));
            oauth2Answer.setExpiration(json.get("expires_in"));
            oauth2Answer.setRefreshToken(json.get("refresh_token"));
            oauth2Answer.setReceivedAt(LocalDateTime.now());
            if (json.containsKey("id_token")) {
                if (idTokenIsValid(json.get("id_token")))
                    oauth2Answer.setIdToken(json.get("id_token"));
                else
                    oauth2Answer.setIdToken("INVALID");
            }
            validTokens.put(token, true);
            Exchange e2 = new Request.Builder().get(auth.getUserInfoEndpoint()).header("Authorization", json.get("token_type") + " " + token).header("User-Agent", Constants.USERAGENT).header(Header.ACCEPT, "application/json").buildExchange();
            if (log.isDebugEnabled()) {
                logi.setHeaderOnly(false);
                logi.handleRequest(e2);
            }
            Response response2 = auth.doRequest(e2);
            if (log.isDebugEnabled())
                logi.handleResponse(e2);
            if (response2.getStatusCode() != 200) {
                statistics.accessTokenInvalid();
                throw new RuntimeException("User data could not be retrieved.");
            }
            statistics.accessTokenValid();
            HashMap<String, String> json2 = Util.parseSimpleJSONResponse(response2);
            oauth2Answer.setUserinfo(json2);
            session.getUserAttributes().put(OAUTH2_ANSWER, oauth2Answer.serialize());
            processUserInfo(json2, session);
            exc.setRequest(originalRequest);
            return true;
        } catch (Exception e) {
            exc.setResponse(Response.badRequest().body(e.getMessage()).build());
            return true;
        }
    }
    return false;
}
Also used : CacheBuilder(com.google.common.cache.CacheBuilder) Request(com.predic8.membrane.core.http.Request) ParseException(com.floreysoft.jmte.message.ParseException) IOException(java.io.IOException) Exchange(com.predic8.membrane.core.exchange.Exchange) Response(com.predic8.membrane.core.http.Response) LogInterceptor(com.predic8.membrane.core.interceptor.LogInterceptor)

Example 7 with User

use of com.predic8.membrane.core.interceptor.registration.entity.User in project service-proxy by membrane.

the class OAuth2ResourceInterceptor method revalidateToken.

private HashMap<String, String> revalidateToken(OAuth2AnswerParameters params) throws Exception {
    Exchange e2 = new Request.Builder().get(auth.getUserInfoEndpoint()).header("Authorization", params.getTokenType() + " " + params.getAccessToken()).header("User-Agent", Constants.USERAGENT).header(Header.ACCEPT, "application/json").buildExchange();
    Response response2 = auth.doRequest(e2);
    if (response2.getStatusCode() != 200) {
        statistics.accessTokenInvalid();
        return null;
    } else {
        statistics.accessTokenValid();
        return Util.parseSimpleJSONResponse(response2);
    }
}
Also used : Exchange(com.predic8.membrane.core.exchange.Exchange) Response(com.predic8.membrane.core.http.Response) Request(com.predic8.membrane.core.http.Request)

Example 8 with User

use of com.predic8.membrane.core.interceptor.registration.entity.User in project service-proxy by membrane.

the class BasicAuthenticationInterceptor method getLongDescription.

@Override
public String getLongDescription() {
    StringBuilder sb = new StringBuilder();
    sb.append(getShortDescription());
    sb.append("<br/>");
    sb.append("Users: ");
    for (User user : userDataProvider.getUsers()) {
        sb.append(StringEscapeUtils.escapeHtml(user.getUsername()));
        sb.append(", ");
    }
    sb.delete(sb.length() - 2, sb.length());
    sb.append("<br/>Passwords are not shown.");
    return sb.toString();
}
Also used : User(com.predic8.membrane.core.interceptor.authentication.session.StaticUserDataProvider.User)

Example 9 with User

use of com.predic8.membrane.core.interceptor.registration.entity.User in project service-proxy by membrane.

the class BasicAuthenticationInterceptor method init.

@Override
public void init() throws Exception {
    // to not alter the interface of "BasicAuthenticationInterceptor" in the config file the "name" attribute is renamed to "username" in code
    for (User user : getUsers()) {
        if (user.getAttributes().containsKey("name")) {
            String username = user.getAttributes().get("name");
            user.getAttributes().remove("name");
            user.getAttributes().put("username", username);
        }
    }
    userDataProvider.getUsersByName().clear();
    for (User user : userDataProvider.getUsers()) userDataProvider.getUsersByName().put(user.getUsername(), user);
}
Also used : User(com.predic8.membrane.core.interceptor.authentication.session.StaticUserDataProvider.User)

Example 10 with User

use of com.predic8.membrane.core.interceptor.registration.entity.User in project service-proxy by membrane.

the class QuickstartRESTTest method doit.

@Test
public void doit() throws IOException, InterruptedException {
    File baseDir = getExampleDir("quickstart-rest");
    Process2 sl = new Process2.Builder().in(baseDir).script("service-proxy").waitForMembrane().start();
    try {
        String result = getAndAssert200("http://localhost:2000/restnames/name.groovy?name=Pia");
        assertContains("Italy", result);
        AssertUtils.closeConnections();
        new ProxiesXmlUtil(new File(baseDir, "proxies.xml")).updateWith("<spring:beans xmlns=\"http://membrane-soa.org/proxies/1/\"\r\n" + "	xmlns:spring=\"http://www.springframework.org/schema/beans\"\r\n" + "	xmlns:xsi=\"http://www.w3.org/2001/XMLSchema-instance\"\r\n" + "	xsi:schemaLocation=\"http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans-4.2.xsd\r\n" + "					    http://membrane-soa.org/proxies/1/ http://membrane-soa.org/schemas/proxies-1.xsd\">\r\n" + "\r\n" + "	<router>\r\n" + "\r\n" + "       <serviceProxy name=\"names\" port=\"2000\">\r\n" + "         <path isRegExp=\"true\">/(rest)?names.*</path>\r\n" + "         <rewriter>\r\n" + "           <map from=\"/names/(.*)\" to=\"/restnames/name\\.groovy\\?name=$1\" />\r\n" + "         </rewriter>\r\n" + "         <statisticsCSV file=\"log.csv\" />\r\n" + "         <response>\r\n" + "           <regExReplacer regex=\"\\s*,\\s*&lt;\" replace=\"&lt;\" />\r\n" + "           <transform xslt=\"restnames.xsl\" />\r\n" + "         </response>\r\n" + "         <target host=\"thomas-bayer.com\" port=\"80\" />\r\n" + "       </serviceProxy>\r\n" + "     \r\n" + "       <serviceProxy name=\"Console\" port=\"9000\">\r\n" + "         <basicAuthentication>\r\n" + "           <user name=\"alice\" password=\"membrane\" />\r\n" + "         </basicAuthentication>			\r\n" + "         <adminConsole />\r\n" + "       </serviceProxy>	\r\n" + "     </router>\r\n" + "</spring:beans>", sl);
        result = getAndAssert200("http://localhost:2000/names/Pia");
        assertContains("Italy, Spain", result);
        assertContainsNot(",<", result);
        String csvLog = FileUtils.readFileToString(new File(baseDir, "log.csv"));
        assertContains("Pia", csvLog);
        AssertUtils.setupHTTPAuthentication("localhost", 9000, "alice", "membrane");
        result = getAndAssert200("http://localhost:9000/admin/");
        assertContains("ServiceProxies", result);
    } finally {
        sl.killScript();
    }
}
Also used : Process2(com.predic8.membrane.examples.Process2) ProxiesXmlUtil(com.predic8.membrane.examples.ProxiesXmlUtil) File(java.io.File) Test(org.junit.Test)

Aggregations

User (com.predic8.membrane.core.interceptor.authentication.session.StaticUserDataProvider.User)4 Request (com.predic8.membrane.core.http.Request)3 IOException (java.io.IOException)3 Test (org.junit.Test)3 Exchange (com.predic8.membrane.core.exchange.Exchange)2 Response (com.predic8.membrane.core.http.Response)2 Rule (com.predic8.membrane.core.rules.Rule)2 Process2 (com.predic8.membrane.examples.Process2)2 ProxiesXmlUtil (com.predic8.membrane.examples.ProxiesXmlUtil)2 File (java.io.File)2 ArrayList (java.util.ArrayList)2 ObjectMapper (com.fasterxml.jackson.databind.ObjectMapper)1 ParseException (com.floreysoft.jmte.message.ParseException)1 CacheBuilder (com.google.common.cache.CacheBuilder)1 LogInterceptor (com.predic8.membrane.core.interceptor.LogInterceptor)1 StaticUserDataProvider (com.predic8.membrane.core.interceptor.authentication.session.StaticUserDataProvider)1 User (com.predic8.membrane.core.interceptor.registration.entity.User)1 ServiceProxy (com.predic8.membrane.core.rules.ServiceProxy)1 ServiceProxyKey (com.predic8.membrane.core.rules.ServiceProxyKey)1 Connection (java.sql.Connection)1