Implementação Jasig CAS

6 respostas
G

Estou passando por dias dificeis tentando implementar um SSO com Jasig CAS, documentação muito ruim e escassa, consegui rodar o Server do CAS e colocar duas aplicações de exemplo para funcionar compartilhando a mesma sessão através do ticket que ele gera, mas não estou conseguindo recuperar o usuario logado, algumas referencias no wiki do CAS diz que teoricamente através do request.getRemoteUser() eu deveria conseguir mas sempre vem nulo, estou meio limitado nisso. Alguém já implementou o CAS ou tem alguma ideia de como posso prosseguir?

Desculpe se algo ficar meio subentendido.

6 Respostas

S

Dá uma olhada nisso, man

http://sfohart.blogspot.com/2011/04/single-sign-on-configurando-sso-no.html

Espero que ajude

G

Vlw d+ irmão, isso ja vai ser uma grande ajuda.

J

conseguiu? to com o mesmo problema, mas aqui nao usamos spring, só jsf e jee…

como recuperou o usuario q logou no CAS?

G

Bom faz um tempinho que tive q para de mexer nisso.... se não me engano a minha solução foi implementar um filtro que creio ter visto no proprio site do JASIG o doFilter ficou assim:

public void doFilter(ServletRequest req, ServletResponse resp, FilterChain chain) throws IOException,
			ServletException {
//		if (filterConfig == null)
//			return;
//
//		HttpServletRequest request = (HttpServletRequest) req;
//		HttpServletResponse response = (HttpServletResponse) resp;
//
//		
//		String ticket = (String) request.getParameter("ticket");
//		
//		System.out.println("Remote User: " + request.getRemoteUser());
//		System.out.println("User: Principal: " + request.getUserPrincipal());
//		
//		chain.doFilter(req, resp);
		
		acceptSSL();
		registerMyHostnameVerifier();
		
		HttpServletRequest httpRequest = (HttpServletRequest) req;
        HttpServletResponse httpResponse = (HttpServletResponse) resp;

        // If the user principal is not null the user has been authenticated
        // by this application so just continue on to the next filter in the
        // request chain.
        if (httpRequest.getSession().getAttribute("_const_cas_assertion_") != null) {
            chain.doFilter(req, resp);
            return;
        }

        // User is NOT authenticated to this application, so we must query the
        // CAS server to authenticate.

        // If the user has already authenticated to CAS via another application,
        // CAS will simply redirect back to this application with a
        // service ticket set as a request parameter without displaying the
        // login screen.  If the user hasn't authenticated to CAS via another application,
        // CAS will display the login screen then redirect back to this application
        // with a service ticket after successfully authenticating.

        // Get the service ticket.
        String serviceTicket = req.getParameter("ticket");

        // If there is no service ticket parameter then redirect to the CAS
        // login URL to get one.
        if (serviceTicket == null || serviceTicket.length() < 1) {
            String redirectURL = CAS_LOGIN_URL + "?service=" + THIS_APPS_URL;
            httpResponse.sendRedirect(redirectURL);
            return;
        }

        // Since we have a service ticket from CAS, validate the ticket by opening
        // an SSL connection to the server and reading the response.
        String urlString = CAS_VALIDATE_URL + "?ticket=" + serviceTicket + "&service=" +
            THIS_APPS_URL;

        URL url = new URL(urlString);
        URLConnection connection = url.openConnection();

        BufferedReader in =
            new BufferedReader(new InputStreamReader(connection.getInputStream()));

        String xmlResponse = "";
        String line = "";
        while ((line = in.readLine()) != null) {
            System.out.println(line);
            xmlResponse += line;
        }
        in.close();

        String userData = null;

        // Parse the xml response
        try {
            Namespace namespace = Namespace.getNamespace("cas", "http://www.yale.edu/tp/cas");
            SAXBuilder builder = new SAXBuilder();
            Document xmlDoc =
                builder.build(new ByteArrayInputStream(xmlResponse.getBytes("UTF-8")));
            Element rootElement = xmlDoc.detachRootElement();

            Element successElement = rootElement.getChild("authenticationSuccess",
                    namespace);

            // if the user element is null there was an error validating
            // the service ticket, so redirect to an error page.
            if (successElement == null) {
                System.err.print("Error validating CAS ticket.");
                httpResponse.sendRedirect("error_page.jsp");
                return;
            }

            Element userElement = successElement.getChild("user", namespace);
            userData = userElement.getText();
        } catch (Exception e) {
            e.printStackTrace();
        }

        // If user data is null or empty redirect to an error page.
        if (userData == null || userData.length() < 0) {
            System.err.print("Error getting user data.");
            httpResponse.sendRedirect("error_page.jsp");
            return;
        }

        // Create a principal and assertion object and set in the session
        AttributePrincipal principal = new AttributePrincipalImpl(userData); //setando o usuario
        Assertion assertion = new AssertionImpl(principal);
        httpRequest.getSession().setAttribute("_const_cas_assertion_", assertion);
        chain.doFilter(req, resp);
	}

E para teste fiz uma jsp simples:

<%@page contentType="text/html"%>
<%@page pageEncoding="UTF-8"%>
<%@ page import="java.util.Map"%>
<%@ page import="java.util.Iterator"%>
<%@ page import="org.jasig.cas.client.authentication.AttributePrincipal"%>

<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN"
   "http://www.w3.org/TR/html4/loose.dtd">

<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<title>CAS Test</title>
</head>
<body>

<h1>CAS Test</h1>

<p><%=request.getRemoteUser()%></p>

</body>
</html>
J

nao consegui fazer o java CAS client, funcionar com rubyCAS, alguém sabe se são compatíveis?

A

olá, alguém conseguiu customizar a parte de autenticação?

Criado 18 de março de 2011
Ultima resposta 6 de dez. de 2011
Respostas 6
Participantes 4