org.jasig.cas.client.validation.Assertion Java Examples

The following examples show how to use org.jasig.cas.client.validation.Assertion. 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: CasAuthenticationUserDetailsService.java    From lemon with Apache License 2.0 6 votes vote down vote up
public void updateUserInfo(Assertion assertion) {
    String username = assertion.getPrincipal().getName();
    String nickName = (String) assertion.getPrincipal().getAttributes()
            .get("nickName");

    if (nickName == null) {
        nickName = username;
    }

    UserDTO userDto = new UserDTO();
    userDto.setRef(username);
    userDto.setUsername(username);
    userDto.setDisplayName(nickName);
    userDto.setNickName(nickName);
    userSyncConnector.updateUser(userDto);
}
 
Example #2
Source File: IndexController.java    From CAS with Apache License 2.0 6 votes vote down vote up
@RequestMapping(value = "/caslogin", method = RequestMethod.GET)
public void caslogin() throws IOException {
    HttpSession session = request.getSession();
    Assertion assertion = (Assertion) session.getAttribute(AbstractCasFilter.CONST_CAS_ASSERTION);
    if (assertion != null) {
        //获取登录用户名
        String username = assertion.getPrincipal().getName();
        System.out.println("user ---------> " + username);
        User temp = userService.findByUsername(username);
        System.out.println("TEMP user ---------> " + (temp.getUsername()));
        if (temp != null) {
            session.setAttribute(WebSecurityConfig.SESSION_LOGIN, temp);

            String jsessionid = session.getId();

            System.out.println("jsessionid ------> " + jsessionid);

            // 使用url传递参数,跳转到前端
            // response.sendRedirect("http://front.anumbrella.net:8000/home?jsessionid=" + jsessionid);

            // 使用nginx代理,跳转到前端
            response.sendRedirect("http://nginx.anumbrella.net:81/home");
        }
    }
}
 
Example #3
Source File: WebSecurityConfig.java    From CAS with Apache License 2.0 6 votes vote down vote up
@Override
public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws IOException {
    HttpSession session = request.getSession(false);

    if (session != null) {
        System.out.println("requst path " + request.getServletPath());

        Assertion assertion = (Assertion) session.getAttribute(AbstractCasFilter.CONST_CAS_ASSERTION);

        if (assertion != null) {
            System.out.println("cas user ---------> " + assertion.getPrincipal().getName());
        }

        User value = (User) session.getAttribute(SESSION_LOGIN);

        System.out.println("security session = null ---------> " + (value == null));

        if (value != null) {
            return true;
        }
    }

    response.setStatus(HttpServletResponse.SC_UNAUTHORIZED);
    return false;
}
 
Example #4
Source File: WebSecurityConfig.java    From CAS with Apache License 2.0 6 votes vote down vote up
@Override
public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws IOException {
    HttpSession session = request.getSession();


    //获取cas给我们传递回来的对象,这个东西放到了session中
    //session的 key是 _const_cas_assertion_
    Assertion assertion = (Assertion) request.getSession().getAttribute(AbstractCasFilter.CONST_CAS_ASSERTION);

    //获取登录用户名
    String loginName = assertion.getPrincipal().getName();
    System.out.printf("登录用户名:%s\r\n", loginName);


    // 判断是否已有该用户登录的session
    if (session.getAttribute(SESSION_KEY) != null) {
        return true;
    }


    // 跳转到登录页
    String url = "/login";
    response.sendRedirect(url);
    return false;
}
 
Example #5
Source File: WebSecurityConfig.java    From CAS with Apache License 2.0 6 votes vote down vote up
@Override
public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws IOException {
    HttpSession session = request.getSession();


    //获取cas给我们传递回来的对象,这个东西放到了session中
    //session的 key是 _const_cas_assertion_
    Assertion assertion = (Assertion) request.getSession().getAttribute(AbstractCasFilter.CONST_CAS_ASSERTION);

    //获取登录用户名
    String loginName = assertion.getPrincipal().getName();
    System.out.printf("登录用户名:%s\r\n", loginName);


    // 判断是否已有该用户登录的session
    if (session.getAttribute(SESSION_KEY) != null) {
        return true;
    }


    // 跳转到登录页
    String url = "/login";
    response.sendRedirect(url);
    return false;
}
 
Example #6
Source File: CasSsoService3.java    From Knowage-Server with GNU Affero General Public License v3.0 6 votes vote down vote up
/**
 * Get a new ticket.
 * 
 * @param session HttpSession
 * 
 * @return String
 * 
 * @throws IOException Signals that an I/O exception has occurred.
 */
public String readTicket(HttpSession session) throws IOException{
 logger.debug("IN");
 String ticket=null;
 String spagoBiServerURL = EnginConf.getInstance().getSpagoBiServerUrl();
 logger.debug("Read spagoBiServerURL=" + spagoBiServerURL);
 SourceBean engineConfig = EnginConf.getInstance().getConfig();
 SourceBean sourceBeanConf = (SourceBean) engineConfig.getAttribute("FILTER_RECEIPT");
 String filterReceipt = (String) sourceBeanConf.getCharacters();
 logger.debug("Read filterReceipt=" + filterReceipt);
 filterReceipt = spagoBiServerURL + filterReceipt;
 
 Assertion assertion = (Assertion) session.getAttribute(AbstractCasFilter.CONST_CAS_ASSERTION);
 ticket=assertion.getPrincipal().getProxyTicketFor(filterReceipt);

 logger.debug("OUT.ticket="+ticket);
 return ticket;
}
 
Example #7
Source File: CasSsoService5.java    From Knowage-Server with GNU Affero General Public License v3.0 6 votes vote down vote up
public String readUserIdentifier(HttpServletRequest request){
   HttpSession session=request.getSession();
   Assertion assertion = (Assertion) session.getAttribute(AbstractCasFilter.CONST_CAS_ASSERTION);
   if (assertion == null) {
   	return super.readUserIdentifier(request);
   }
   String userInSession=assertion.getPrincipal().getName();

//String user=(String)request.getRemoteUser();
//logger.debug("CAS user in HttpServletRequest:"+user);
logger.debug("CAS user in HttpSession:"+userInSession);
Calendar calendar = Calendar.getInstance();
calendar.add(Calendar.HOUR, 10);
Date expiresAt = calendar.getTime();
	
String jwtToken = JWTSsoService.userId2jwtToken(userInSession, expiresAt);
logger.debug("JWT-TOKEN " + jwtToken);
	
return jwtToken;
  }
 
Example #8
Source File: ShibcasAuthServlet.java    From shib-cas-authn3 with Apache License 2.0 6 votes vote down vote up
private void validatevalidateCasTicket(final HttpServletRequest request, final HttpServletResponse response, final String ticket,
                                       final String authenticationKey, final boolean force) throws ExternalAuthenticationException, IOException {
    try {
        ticketValidator.setRenew(force);
        final String serviceUrl = constructServiceUrl(request, response, true);
        logger.debug("validating ticket: {} with service url: {}", ticket, serviceUrl);
        final Assertion assertion = ticketValidator.validate(ticket, serviceUrl);
        if (assertion == null) {
            throw new TicketValidationException("Validation failed. Assertion could not be retrieved for ticket " + ticket);
        }
        for (final CasToShibTranslator casToShibTranslator : translators) {
            casToShibTranslator.doTranslation(request, response, assertion, authenticationKey);
        }
    } catch (final Exception e) {
        logger.error("Ticket validation failed, returning InvalidTicket", e);
        request.setAttribute(ExternalAuthentication.AUTHENTICATION_ERROR_KEY, "InvalidTicket");
    }
    ExternalAuthentication.finishExternalAuthentication(authenticationKey, request, response);
}
 
Example #9
Source File: ShibcasAuthServlet.java    From shib-cas-authn3 with Apache License 2.0 6 votes vote down vote up
private void validatevalidateCasTicket(final HttpServletRequest request, final HttpServletResponse response, final String ticket,
                                       final String authenticationKey, final boolean force) throws ExternalAuthenticationException, IOException {
    try {
        ticketValidator.setRenew(force);
        final String serviceUrl = constructServiceUrl(request, response, true);
        logger.debug("validating ticket: {} with service url: {}", ticket, serviceUrl);
        final Assertion assertion = ticketValidator.validate(ticket, serviceUrl);
        if (assertion == null) {
            throw new TicketValidationException("Validation failed. Assertion could not be retrieved for ticket " + ticket);
        }
        for (final CasToShibTranslator casToShibTranslator : translators) {
            casToShibTranslator.doTranslation(request, response, assertion, authenticationKey);
        }
    } catch (final Exception e) {
        logger.error("Ticket validation failed, returning InvalidTicket", e);
        request.setAttribute(ExternalAuthentication.AUTHENTICATION_ERROR_KEY, "InvalidTicket");
    }
    ExternalAuthentication.finishExternalAuthentication(authenticationKey, request, response);
}
 
Example #10
Source File: ShibcasAuthServletTest.java    From shib-cas-authn3 with Apache License 2.0 5 votes vote down vote up
@Test
public void testDoGetPassiveAndForced() throws Exception {
    //Mock some objects.
    final HttpServletRequest request = createDoGetHttpServletRequest(CONVERSATION_TICKET_GATEWAY_ATTEMPTED, TICKET, "true");
    final HttpServletResponse response = createMockHttpServletResponse();
    final Assertion assertion = createMockAssertion();

    final Cas20ServiceTicketValidator ticketValidator = PowerMockito.mock(Cas30ServiceTicketValidator.class);
    PowerMockito.when(ticketValidator.validate(TICKET, URL_WITH_CONVERSATION_GATEWAY_ATTEMPTED)).thenReturn(assertion);

    PowerMockito.mockStatic(ExternalAuthentication.class);
    BDDMockito.given(ExternalAuthentication.startExternalAuthentication(request)).willReturn(E1S1);

    //Prep our object
    final ShibcasAuthServlet shibcasAuthServlet = createShibcasAuthServlet();

    //Override the internal Cas30TicketValidator because we don't want it to call a real server
    MemberModifier.field(ShibcasAuthServlet.class, "ticketValidator").set(shibcasAuthServlet, ticketValidator);

    //Passive and forced request/response
    BDDMockito.given(request.getAttribute(ExternalAuthentication.FORCE_AUTHN_PARAM)).willReturn("true");
    BDDMockito.given(request.getAttribute(ExternalAuthentication.PASSIVE_AUTHN_PARAM)).willReturn("true");
    shibcasAuthServlet.doGet(request, response);

    //Verify
    verify(request).setAttribute(ExternalAuthentication.PRINCIPAL_NAME_KEY, JDOE);
}
 
Example #11
Source File: ShibcasAuthServletTest.java    From shib-cas-authn3 with Apache License 2.0 5 votes vote down vote up
@Test
public void testDoGetPassiveAuthenticated() throws Exception {
    //Mock some objects.
    final HttpServletRequest request = createDoGetHttpServletRequest(CONVERSATION_TICKET + "&gatewayAttempted=true", TICKET, "true");
    final HttpServletResponse response = createMockHttpServletResponse();
    final Assertion assertion = createMockAssertion();

    final Cas20ServiceTicketValidator ticketValidator = PowerMockito.mock(Cas20ServiceTicketValidator.class);
    PowerMockito.when(ticketValidator.validate(TICKET, URL_WITH_CONVERSATION_GATEWAY_ATTEMPTED)).thenReturn(assertion);

    PowerMockito.mockStatic(ExternalAuthentication.class);
    BDDMockito.given(ExternalAuthentication.startExternalAuthentication(request)).willReturn(E1S1);

    //Prep our object
    final ShibcasAuthServlet shibcasAuthServlet = createShibcasAuthServlet();

    //Override the internal Cas20TicketValidator because we don't want it to call a real server
    MemberModifier.field(ShibcasAuthServlet.class, "ticketValidator").set(shibcasAuthServlet, ticketValidator);

    //Passive request/response with authenticated user
    BDDMockito.given(request.getAttribute(ExternalAuthentication.FORCE_AUTHN_PARAM)).willReturn("false");
    BDDMockito.given(request.getAttribute(ExternalAuthentication.PASSIVE_AUTHN_PARAM)).willReturn("true");
    shibcasAuthServlet.doGet(request, response);

    //Verify
    verify(request).setAttribute(ExternalAuthentication.PRINCIPAL_NAME_KEY, JDOE);
}
 
Example #12
Source File: ShibcasAuthServletTest.java    From shib-cas-authn3 with Apache License 2.0 5 votes vote down vote up
private Assertion createMockAssertion() {
    final Assertion assertion = Mockito.mock(Assertion.class);
    final AttributePrincipal attributePrincipal = Mockito.mock(AttributePrincipal.class);

    BDDMockito.given(attributePrincipal.getName()).willReturn(JDOE);
    BDDMockito.given(assertion.getPrincipal()).willReturn(attributePrincipal);

    return assertion;
}
 
Example #13
Source File: CasUserDetailsService.java    From kylin with Apache License 2.0 5 votes vote down vote up
@Override
protected UserDetails loadUserDetails(Assertion assertion) {
    if (assertion == null) {
        throw new CredentialsExpiredException("bad assertion");
    }
    ManagedUser user = parseUserDetails(assertion);
    // create user if not exists
    KylinUserManager kylinUserManager = KylinUserManager.getInstance(KylinConfig.getInstanceFromEnv());
    ManagedUser existUser = kylinUserManager.get(user.getUsername());
    if (existUser == null) {
        kylinUserManager.update(user);
    }
    return kylinUserManager.get(user.getUsername());
}
 
Example #14
Source File: CasUserDetailsService.java    From kylin with Apache License 2.0 5 votes vote down vote up
protected ManagedUser parseUserDetails(Assertion assertion) {
    AttributePrincipal principal = assertion.getPrincipal();
    List<GrantedAuthority> grantedAuthorities = Stream.of(defaultAuthorities)
            .map(SimpleGrantedAuthority::new)
            .collect(Collectors.toList());
    return new ManagedUser(principal.getName(), NON_EXISTENT_PASSWORD_VALUE, true, grantedAuthorities);
}
 
Example #15
Source File: AuthenticatedNameTranslator.java    From shib-cas-authn3 with Apache License 2.0 5 votes vote down vote up
@Override
public void doTranslation(final HttpServletRequest request, final HttpServletResponse response,
                          final Assertion assertion, final String authenticationKey) {
    if (assertion == null || assertion.getPrincipal() == null) {
        logger.error("No valid assertion or principal could be found to translate");
        return;
    }
    final AttributePrincipal casPrincipal = assertion.getPrincipal();
    logger.debug("principalName found and being passed on: {}", casPrincipal.getName());

    // Pass authenticated principal back to IdP to finish its part of authentication request processing
    final Collection<IdPAttributePrincipal> assertionAttributes = produceIdpAttributePrincipal(assertion.getAttributes());
    final Collection<IdPAttributePrincipal> principalAttributes = produceIdpAttributePrincipal(casPrincipal.getAttributes());

    if (!assertionAttributes.isEmpty() || !principalAttributes.isEmpty()) {
        logger.debug("Found attributes from CAS. Processing...");
        final Set<Principal> principals = new HashSet<>();

        principals.addAll(assertionAttributes);
        principals.addAll(principalAttributes);
        principals.add(new UsernamePrincipal(casPrincipal.getName()));

        request.setAttribute(ExternalAuthentication.SUBJECT_KEY, new Subject(false, principals,
            Collections.emptySet(), Collections.emptySet()));
        logger.info("Created an IdP subject instance with principals containing attributes for {} ", casPrincipal.getName());

    } else {
        logger.debug("No attributes released from CAS. Creating an IdP principal for {}", casPrincipal.getName());
        request.setAttribute(ExternalAuthentication.PRINCIPAL_NAME_KEY, casPrincipal.getName());
    }
}
 
Example #16
Source File: ShibcasAuthServletTest.java    From shib-cas-authn3 with Apache License 2.0 5 votes vote down vote up
@Test
public void testDoGetStandard() throws Exception {
    //Mock some objects.
    final HttpServletRequest request = createDoGetHttpServletRequest(CONVERSATION_TICKET, TICKET, null);
    final HttpServletResponse response = createMockHttpServletResponse();
    final Assertion assertion = createMockAssertion();

    final Cas20ServiceTicketValidator ticketValidator = PowerMockito.mock(Cas20ServiceTicketValidator.class);
    PowerMockito.when(ticketValidator.validate(TICKET, URL_WITH_CONVERSATION)).thenReturn(assertion);

    PowerMockito.mockStatic(ExternalAuthentication.class);
    BDDMockito.given(ExternalAuthentication.startExternalAuthentication(request)).willReturn(E1S1);

    //Prep our object
    final ShibcasAuthServlet shibcasAuthServlet = createShibcasAuthServlet();

    //Override the internal Cas20TicketValidator because we don't want it to call a real server
    MemberModifier.field(ShibcasAuthServlet.class, "ticketValidator").set(shibcasAuthServlet, ticketValidator);

    //Standard request/response
    BDDMockito.given(request.getAttribute(ExternalAuthentication.FORCE_AUTHN_PARAM)).willReturn("false");
    BDDMockito.given(request.getAttribute(ExternalAuthentication.PASSIVE_AUTHN_PARAM)).willReturn("false");
    shibcasAuthServlet.doGet(request, response);

    //Verify
    verify(request).setAttribute(ExternalAuthentication.PRINCIPAL_NAME_KEY, JDOE);
}
 
Example #17
Source File: ShibcasAuthServletTest.java    From shib-cas-authn3 with Apache License 2.0 5 votes vote down vote up
@Test
public void testDoGetPassiveAuthenticated() throws Exception {
    //Mock some objects.
    final HttpServletRequest request = createDoGetHttpServletRequest(CONVERSATION_TICKET + "&gatewayAttempted=true", TICKET, "true");
    final HttpServletResponse response = createMockHttpServletResponse();
    final Assertion assertion = createMockAssertion();

    final Cas20ServiceTicketValidator ticketValidator = PowerMockito.mock(Cas20ServiceTicketValidator.class);
    PowerMockito.when(ticketValidator.validate(TICKET, URL_WITH_CONVERSATION_GATEWAY_ATTEMPTED)).thenReturn(assertion);

    PowerMockito.mockStatic(ExternalAuthentication.class);
    BDDMockito.given(ExternalAuthentication.startExternalAuthentication(request)).willReturn(E1S1);

    //Prep our object
    final ShibcasAuthServlet shibcasAuthServlet = createShibcasAuthServlet();

    //Override the internal Cas20TicketValidator because we don't want it to call a real server
    MemberModifier.field(ShibcasAuthServlet.class, "ticketValidator").set(shibcasAuthServlet, ticketValidator);

    //Passive request/response with authenticated user
    BDDMockito.given(request.getAttribute(ExternalAuthentication.FORCE_AUTHN_PARAM)).willReturn("false");
    BDDMockito.given(request.getAttribute(ExternalAuthentication.PASSIVE_AUTHN_PARAM)).willReturn("true");
    shibcasAuthServlet.doGet(request, response);

    //Verify
    verify(request).setAttribute(ExternalAuthentication.PRINCIPAL_NAME_KEY, JDOE);
}
 
Example #18
Source File: ShibcasAuthServletTest.java    From shib-cas-authn3 with Apache License 2.0 5 votes vote down vote up
@Test
public void testDoGetForced() throws Exception {
    //Mock some objects.
    final HttpServletRequest request = createDoGetHttpServletRequest(CONVERSATION_TICKET, TICKET, null);
    final HttpServletResponse response = createMockHttpServletResponse();
    final Assertion assertion = createMockAssertion();

    final Cas20ServiceTicketValidator ticketValidator = PowerMockito.mock(Cas20ServiceTicketValidator.class);
    PowerMockito.when(ticketValidator.validate(TICKET, URL_WITH_CONVERSATION)).thenReturn(assertion);

    PowerMockito.mockStatic(ExternalAuthentication.class);
    BDDMockito.given(ExternalAuthentication.startExternalAuthentication(request)).willReturn(E1S1);

    //Prep our object
    final ShibcasAuthServlet shibcasAuthServlet = createShibcasAuthServlet();

    //Override the internal Cas20TicketValidator because we don't want it to call a real server
    MemberModifier.field(ShibcasAuthServlet.class, "ticketValidator").set(shibcasAuthServlet, ticketValidator);

    //Forced request/response
    BDDMockito.given(request.getAttribute(ExternalAuthentication.FORCE_AUTHN_PARAM)).willReturn("true");
    BDDMockito.given(request.getAttribute(ExternalAuthentication.PASSIVE_AUTHN_PARAM)).willReturn("false");
    shibcasAuthServlet.doGet(request, response);

    //Verify
    verify(request).setAttribute(ExternalAuthentication.PRINCIPAL_NAME_KEY, JDOE);
}
 
Example #19
Source File: ShibcasAuthServletTest.java    From shib-cas-authn3 with Apache License 2.0 5 votes vote down vote up
@Test
public void testDoGetPassiveAndForced() throws Exception {
    //Mock some objects.
    final HttpServletRequest request = createDoGetHttpServletRequest(CONVERSATION_TICKET_GATEWAY_ATTEMPTED, TICKET, "true");
    final HttpServletResponse response = createMockHttpServletResponse();
    final Assertion assertion = createMockAssertion();

    final Cas20ServiceTicketValidator ticketValidator = PowerMockito.mock(Cas30ServiceTicketValidator.class);
    PowerMockito.when(ticketValidator.validate(TICKET, URL_WITH_CONVERSATION_GATEWAY_ATTEMPTED)).thenReturn(assertion);

    PowerMockito.mockStatic(ExternalAuthentication.class);
    BDDMockito.given(ExternalAuthentication.startExternalAuthentication(request)).willReturn(E1S1);

    //Prep our object
    final ShibcasAuthServlet shibcasAuthServlet = createShibcasAuthServlet();

    //Override the internal Cas30TicketValidator because we don't want it to call a real server
    MemberModifier.field(ShibcasAuthServlet.class, "ticketValidator").set(shibcasAuthServlet, ticketValidator);

    //Passive and forced request/response
    BDDMockito.given(request.getAttribute(ExternalAuthentication.FORCE_AUTHN_PARAM)).willReturn("true");
    BDDMockito.given(request.getAttribute(ExternalAuthentication.PASSIVE_AUTHN_PARAM)).willReturn("true");
    shibcasAuthServlet.doGet(request, response);

    //Verify
    verify(request).setAttribute(ExternalAuthentication.PRINCIPAL_NAME_KEY, JDOE);
}
 
Example #20
Source File: ShibcasAuthServletTest.java    From shib-cas-authn3 with Apache License 2.0 5 votes vote down vote up
private Assertion createMockAssertion() {
    final Assertion assertion = Mockito.mock(Assertion.class);
    final AttributePrincipal attributePrincipal = Mockito.mock(AttributePrincipal.class);

    BDDMockito.given(attributePrincipal.getName()).willReturn(JDOE);
    BDDMockito.given(assertion.getPrincipal()).willReturn(attributePrincipal);

    return assertion;
}
 
Example #21
Source File: CasUserDetailsService.java    From kylin-on-parquet-v2 with Apache License 2.0 5 votes vote down vote up
@Override
protected UserDetails loadUserDetails(Assertion assertion) {
    if (assertion == null) {
        throw new CredentialsExpiredException("bad assertion");
    }
    ManagedUser user = parseUserDetails(assertion);
    // create user if not exists
    KylinUserManager kylinUserManager = KylinUserManager.getInstance(KylinConfig.getInstanceFromEnv());
    ManagedUser existUser = kylinUserManager.get(user.getUsername());
    if (existUser == null) {
        kylinUserManager.update(user);
    }
    return kylinUserManager.get(user.getUsername());
}
 
Example #22
Source File: CasUserDetailsService.java    From kylin-on-parquet-v2 with Apache License 2.0 5 votes vote down vote up
protected ManagedUser parseUserDetails(Assertion assertion) {
    AttributePrincipal principal = assertion.getPrincipal();
    List<GrantedAuthority> grantedAuthorities = Stream.of(defaultAuthorities)
            .map(SimpleGrantedAuthority::new)
            .collect(Collectors.toList());
    return new ManagedUser(principal.getName(), NON_EXISTENT_PASSWORD_VALUE, true, grantedAuthorities);
}
 
Example #23
Source File: CasSsoService3.java    From Knowage-Server with GNU Affero General Public License v3.0 5 votes vote down vote up
/**
    * Read user id.
    * 
    * @param session HttpSession
    * 
    * @return String
    */
   public String readUserIdentifier(HttpServletRequest request){
   HttpSession session=request.getSession();
   Assertion assertion = (Assertion) session.getAttribute(AbstractCasFilter.CONST_CAS_ASSERTION);
   String userInSession=assertion.getPrincipal().getName();
//String user=(String)request.getRemoteUser();
//logger.debug("CAS user in HttpServletRequest:"+user);
logger.debug("CAS user in HttpSession:"+userInSession);
return userInSession;
   }
 
Example #24
Source File: CasSsoService3NoProxy.java    From Knowage-Server with GNU Affero General Public License v3.0 5 votes vote down vote up
/**
    * Read user id.
    * 
    * @param session HttpSession
    * 
    * @return String
    */
   public String readUserIdentifier(HttpServletRequest request){
   HttpSession session=request.getSession();
   Assertion assertion = (Assertion) session.getAttribute(AbstractCasFilter.CONST_CAS_ASSERTION);
   String userInSession=assertion.getPrincipal().getName();
String user=(String)request.getRemoteUser();
logger.debug("CAS user in HttpServletRequest:"+user);
logger.debug("CAS user in HttpSession:"+userInSession);
return user!=null? user:userInSession;
   }
 
Example #25
Source File: MCRCASServlet.java    From mycore with GNU General Public License v3.0 5 votes vote down vote up
public void doGetPost(MCRServletJob job) throws Exception {
    HttpServletRequest req = job.getRequest();
    HttpServletResponse res = job.getResponse();

    String ticket = req.getParameter("ticket");
    if ((ticket == null) || (ticket.trim().length() == 0)) {
        res.sendError(HttpServletResponse.SC_BAD_REQUEST);
        return;
    }

    // Validate ticket at CAS server
    Cas20ProxyTicketValidator sv = new Cas20ProxyTicketValidator(serverURL);
    sv.setAcceptAnyProxy(true);
    Assertion a = sv.validate(ticket, clientURL);
    AttributePrincipal principal = a.getPrincipal();

    // Get user name logged in
    String userName = principal.getName();
    LOGGER.info("Login {}", userName);

    MCRUser user;
    boolean userExists = MCRUserManager.exists(userName, realmID);
    if (userExists) {
        user = MCRUserManager.getUser(userName, realmID);
    } else {
        user = new MCRUser(userName, realmID);
    }

    // Get user properties from LDAP server
    boolean userChanged = MCRLDAPClient.instance().updateUserProperties(user);
    if (userChanged && userExists) {
        MCRUserManager.updateUser(user);
    }

    // Store login user in session and redirect browser to target url
    MCRSessionMgr.getCurrentSession().setUserInformation(user);
    // MCR-1154
    req.changeSessionId();
    MCRLoginServlet.redirect(res);
}
 
Example #26
Source File: AuthenticatedNameTranslator.java    From shib-cas-authn3 with Apache License 2.0 5 votes vote down vote up
@Override
public void doTranslation(final HttpServletRequest request, final HttpServletResponse response,
                          final Assertion assertion, final String authenticationKey) {
    if (assertion == null || assertion.getPrincipal() == null) {
        logger.error("No valid assertion or principal could be found to translate");
        return;
    }
    final AttributePrincipal casPrincipal = assertion.getPrincipal();
    logger.debug("principalName found and being passed on: {}", casPrincipal.getName());

    // Pass authenticated principal back to IdP to finish its part of authentication request processing
    final Collection<IdPAttributePrincipal> assertionAttributes = produceIdpAttributePrincipal(assertion.getAttributes());
    final Collection<IdPAttributePrincipal> principalAttributes = produceIdpAttributePrincipal(casPrincipal.getAttributes());

    if (!assertionAttributes.isEmpty() || !principalAttributes.isEmpty()) {
        logger.debug("Found attributes from CAS. Processing...");
        final Set<Principal> principals = new HashSet<>();

        principals.addAll(assertionAttributes);
        principals.addAll(principalAttributes);
        principals.add(new UsernamePrincipal(casPrincipal.getName()));

        request.setAttribute(ExternalAuthentication.SUBJECT_KEY, new Subject(false, principals,
            Collections.emptySet(), Collections.emptySet()));
        logger.info("Created an IdP subject instance with principals containing attributes for {} ", casPrincipal.getName());

    } else {
        logger.debug("No attributes released from CAS. Creating an IdP principal for {}", casPrincipal.getName());
        request.setAttribute(ExternalAuthentication.PRINCIPAL_NAME_KEY, casPrincipal.getName());
    }
}
 
Example #27
Source File: ShibcasAuthServletTest.java    From shib-cas-authn3 with Apache License 2.0 5 votes vote down vote up
@Test
public void testDoGetStandard() throws Exception {
    //Mock some objects.
    final HttpServletRequest request = createDoGetHttpServletRequest(CONVERSATION_TICKET, TICKET, null);
    final HttpServletResponse response = createMockHttpServletResponse();
    final Assertion assertion = createMockAssertion();

    final Cas20ServiceTicketValidator ticketValidator = PowerMockito.mock(Cas20ServiceTicketValidator.class);
    PowerMockito.when(ticketValidator.validate(TICKET, URL_WITH_CONVERSATION)).thenReturn(assertion);

    PowerMockito.mockStatic(ExternalAuthentication.class);
    BDDMockito.given(ExternalAuthentication.startExternalAuthentication(request)).willReturn(E1S1);

    //Prep our object
    final ShibcasAuthServlet shibcasAuthServlet = createShibcasAuthServlet();

    //Override the internal Cas20TicketValidator because we don't want it to call a real server
    MemberModifier.field(ShibcasAuthServlet.class, "ticketValidator").set(shibcasAuthServlet, ticketValidator);

    //Standard request/response
    BDDMockito.given(request.getAttribute(ExternalAuthentication.FORCE_AUTHN_PARAM)).willReturn("false");
    BDDMockito.given(request.getAttribute(ExternalAuthentication.PASSIVE_AUTHN_PARAM)).willReturn("false");
    shibcasAuthServlet.doGet(request, response);

    //Verify
    verify(request).setAttribute(ExternalAuthentication.PRINCIPAL_NAME_KEY, JDOE);
}
 
Example #28
Source File: ShibcasAuthServletTest.java    From shib-cas-authn3 with Apache License 2.0 5 votes vote down vote up
@Test
public void testDoGetForced() throws Exception {
    //Mock some objects.
    final HttpServletRequest request = createDoGetHttpServletRequest(CONVERSATION_TICKET, TICKET, null);
    final HttpServletResponse response = createMockHttpServletResponse();
    final Assertion assertion = createMockAssertion();

    final Cas20ServiceTicketValidator ticketValidator = PowerMockito.mock(Cas20ServiceTicketValidator.class);
    PowerMockito.when(ticketValidator.validate(TICKET, URL_WITH_CONVERSATION)).thenReturn(assertion);

    PowerMockito.mockStatic(ExternalAuthentication.class);
    BDDMockito.given(ExternalAuthentication.startExternalAuthentication(request)).willReturn(E1S1);

    //Prep our object
    final ShibcasAuthServlet shibcasAuthServlet = createShibcasAuthServlet();

    //Override the internal Cas20TicketValidator because we don't want it to call a real server
    MemberModifier.field(ShibcasAuthServlet.class, "ticketValidator").set(shibcasAuthServlet, ticketValidator);

    //Forced request/response
    BDDMockito.given(request.getAttribute(ExternalAuthentication.FORCE_AUTHN_PARAM)).willReturn("true");
    BDDMockito.given(request.getAttribute(ExternalAuthentication.PASSIVE_AUTHN_PARAM)).willReturn("false");
    shibcasAuthServlet.doGet(request, response);

    //Verify
    verify(request).setAttribute(ExternalAuthentication.PRINCIPAL_NAME_KEY, JDOE);
}
 
Example #29
Source File: CasDuoSecurityRefedsAuthnMethodTranslator.java    From shib-cas-authn3 with Apache License 2.0 4 votes vote down vote up
@Override
public void doTranslation(final HttpServletRequest request, final HttpServletResponse response, final Assertion assertion, final String authenticationKey) throws Exception {

    final ProfileRequestContext prc = ExternalAuthentication.getProfileRequestContext(authenticationKey, request);
    final AuthenticationContext authnContext = prc.getSubcontext(AuthenticationContext.class, true);
    if (authnContext == null) {
        logger.debug("No authentication context is available");
        return;
    }
    final RequestedPrincipalContext principalCtx = authnContext.getSubcontext(RequestedPrincipalContext.class, true);
    if (principalCtx == null || principalCtx.getRequestedPrincipals().isEmpty()) {
        logger.debug("No requested principal context is available in the authentication context; Overriding class to {}", AuthnContext.PPT_AUTHN_CTX);
        overrideAuthnContextClass(AuthnContext.PPT_AUTHN_CTX, request, authenticationKey);
        return;
    }

    final Principal principal = new AuthnContextClassRefPrincipal(REFEDS);
    final Principal attribute = principalCtx.getRequestedPrincipals().stream().filter(p -> p.equals(principal)).findFirst().orElse(null);
    if (attribute == null) {
        logger.debug("No authn context class ref principal is found in the requested principals; overriding to {}", AuthnContext.PPT_AUTHN_CTX);
        overrideAuthnContextClass(AuthnContext.PPT_AUTHN_CTX, request, authenticationKey);
        return;
    }
    final String authnMethod = attribute.getName();
    logger.debug("Requested authn method provided by IdP is {}", authnMethod);
    if (!assertion.getPrincipal().getAttributes().containsKey("authnContextClass")) {
        logger.debug("No authentication context class is provided by CAS; Overriding context class to {}", AuthnContext.PPT_AUTHN_CTX);
        overrideAuthnContextClass(AuthnContext.PPT_AUTHN_CTX, request, authenticationKey);
        return;
    }

    final Object clazz = assertion.getPrincipal().getAttributes().get("authnContextClass");
    logger.debug("Located asserted authentication context class [{}]", clazz);

    if (clazz.equals("mfa-duo")) {
        overrideAuthnContextClass(REFEDS, request, authenticationKey);
        logger.info("Validation payload successfully asserts the authentication context class for mfa-duo; Context class is set to {}", REFEDS);
        return;
    }
    logger.debug("Authentication context class [{}] provided by CAS is not one by Duo Security. "
        + "The requested authentication method to be used shall be {} and is left unmodified", clazz, authnMethod);
    overrideAuthnContextClass(clazz.toString(), request, authenticationKey);
}
 
Example #30
Source File: CasDuoSecurityRefedsAuthnMethodTranslator.java    From shib-cas-authn3 with Apache License 2.0 4 votes vote down vote up
@Override
public void doTranslation(final HttpServletRequest request, final HttpServletResponse response, final Assertion assertion, final String authenticationKey) throws Exception {

    final ProfileRequestContext prc = ExternalAuthentication.getProfileRequestContext(authenticationKey, request);
    final AuthenticationContext authnContext = prc.getSubcontext(AuthenticationContext.class, true);
    if (authnContext == null) {
        logger.debug("No authentication context is available");
        return;
    }
    final RequestedPrincipalContext principalCtx = authnContext.getSubcontext(RequestedPrincipalContext.class, true);
    if (principalCtx == null || principalCtx.getRequestedPrincipals().isEmpty()) {
        logger.debug("No requested principal context is available in the authentication context; Overriding class to {}", AuthnContext.PPT_AUTHN_CTX);
        overrideAuthnContextClass(AuthnContext.PPT_AUTHN_CTX, request, authenticationKey);
        return;
    }

    final Principal principal = new AuthnContextClassRefPrincipal(REFEDS);
    final Principal attribute = principalCtx.getRequestedPrincipals().stream().filter(p -> p.equals(principal)).findFirst().orElse(null);
    if (attribute == null) {
        logger.debug("No authn context class ref principal is found in the requested principals; overriding to {}", AuthnContext.PPT_AUTHN_CTX);
        overrideAuthnContextClass(AuthnContext.PPT_AUTHN_CTX, request, authenticationKey);
        return;
    }
    final String authnMethod = attribute.getName();
    logger.debug("Requested authn method provided by IdP is {}", authnMethod);
    if (!assertion.getPrincipal().getAttributes().containsKey("authnContextClass")) {
        logger.debug("No authentication context class is provided by CAS; Overriding context class to {}", AuthnContext.PPT_AUTHN_CTX);
        overrideAuthnContextClass(AuthnContext.PPT_AUTHN_CTX, request, authenticationKey);
        return;
    }

    final Object clazz = assertion.getPrincipal().getAttributes().get("authnContextClass");
    logger.debug("Located asserted authentication context class [{}]", clazz);

    if (clazz.equals("mfa-duo")) {
        overrideAuthnContextClass(REFEDS, request, authenticationKey);
        logger.info("Validation payload successfully asserts the authentication context class for mfa-duo; Context class is set to {}", REFEDS);
        return;
    }
    logger.debug("Authentication context class [{}] provided by CAS is not one by Duo Security. "
        + "The requested authentication method to be used shall be {} and is left unmodified", clazz, authnMethod);
    overrideAuthnContextClass(clazz.toString(), request, authenticationKey);
}