Search in sources :

Example 71 with SimplePrincipalCollection

use of org.apache.shiro.subject.SimplePrincipalCollection in project ddf by codice.

the class AssertionConsumerService method login.

private boolean login(org.opensaml.saml.saml2.core.Response samlResponse) {
    if (!request.isSecure()) {
        return false;
    }
    Map<String, Cookie> cookieMap = HttpUtils.getCookieMap(request);
    if (cookieMap.containsKey("JSESSIONID") && sessionFactory != null) {
        sessionFactory.getOrCreateSession(request).invalidate();
    }
    HandlerResult handlerResult = new HandlerResultImpl();
    SimplePrincipalCollection simplePrincipalCollection = new SimplePrincipalCollection();
    simplePrincipalCollection.add(new SecurityAssertionSaml(samlResponse.getAssertions().get(0).getDOM()), "default");
    SAMLAuthenticationToken samlToken = new SAMLAuthenticationToken(null, simplePrincipalCollection, request.getRemoteAddr());
    handlerResult.setToken(samlToken);
    handlerResult.setStatus(HandlerResult.Status.COMPLETED);
    if (handlerResult.getStatus() != HandlerResult.Status.COMPLETED) {
        LOGGER.debug("Failed to handle SAML assertion.");
        return false;
    }
    if (handlerResult.getToken() instanceof BaseAuthenticationToken) {
        ((BaseAuthenticationToken) handlerResult.getToken()).setAllowGuest(contextPolicyManager.getGuestAccess());
    }
    request.setAttribute(AUTHENTICATION_TOKEN_KEY, handlerResult);
    request.removeAttribute(ContextPolicy.NO_AUTH_POLICY);
    try {
        LOGGER.trace("Trying to login with provided SAML assertion.");
        loginFilter.doFilter(request, null, (servletRequest, servletResponse) -> {
        });
    } catch (IOException | AuthenticationException e) {
        LOGGER.debug("Failed to apply login filter to SAML assertion", e);
        return false;
    }
    return true;
}
Also used : Cookie(javax.servlet.http.Cookie) AuthenticationException(org.codice.ddf.platform.filter.AuthenticationException) HandlerResultImpl(org.codice.ddf.security.handler.HandlerResultImpl) BaseAuthenticationToken(org.codice.ddf.security.handler.BaseAuthenticationToken) SimplePrincipalCollection(org.apache.shiro.subject.SimplePrincipalCollection) HandlerResult(org.codice.ddf.security.handler.api.HandlerResult) IOException(java.io.IOException) SAMLAuthenticationToken(org.codice.ddf.security.handler.SAMLAuthenticationToken) SecurityAssertionSaml(ddf.security.assertion.saml.impl.SecurityAssertionSaml)

Example 72 with SimplePrincipalCollection

use of org.apache.shiro.subject.SimplePrincipalCollection in project ddf by codice.

the class IdpHandler method checkForAssertionInHttpHeader.

private HandlerResult checkForAssertionInHttpHeader(ServletRequest request) {
    HttpServletRequest httpRequest = (HttpServletRequest) request;
    String authHeader = ((HttpServletRequest) request).getHeader(SecurityConstants.SAML_HEADER_NAME);
    HandlerResult handlerResult = new HandlerResultImpl();
    // check for full SAML assertions coming in (federated requests, etc.)
    if (authHeader != null) {
        String[] tokenizedAuthHeader = authHeader.split(" ");
        if (tokenizedAuthHeader.length == 2 && tokenizedAuthHeader[0].equals("SAML") && samlSecurity != null) {
            String encodedSamlAssertion = tokenizedAuthHeader[1];
            LOGGER.trace("Header retrieved");
            try {
                String tokenString = samlSecurity.inflateBase64(encodedSamlAssertion);
                LOGGER.trace("Header value: {}", LogSanitizer.sanitize(tokenString));
                SimplePrincipalCollection simplePrincipalCollection = new SimplePrincipalCollection();
                simplePrincipalCollection.add(new SecurityAssertionSaml(SAMLUtils.getInstance().getSecurityTokenFromSAMLAssertion(tokenString)), "default");
                SAMLAuthenticationToken samlToken = new SAMLAuthenticationToken(simplePrincipalCollection, simplePrincipalCollection, request.getRemoteAddr());
                handlerResult.setToken(samlToken);
                handlerResult.setStatus(HandlerResult.Status.COMPLETED);
            } catch (IOException e) {
                LOGGER.info("Unexpected error converting header value to string", e);
            }
            return handlerResult;
        }
    }
    // Check for legacy SAML cookie
    Map<String, Cookie> cookies = HttpUtils.getCookieMap(httpRequest);
    Cookie samlCookie = cookies.get(SecurityConstants.SAML_COOKIE_NAME);
    if (samlCookie != null && samlSecurity != null) {
        String cookieValue = samlCookie.getValue();
        LOGGER.trace("Cookie retrieved");
        try {
            String tokenString = samlSecurity.inflateBase64(cookieValue);
            LOGGER.trace("Cookie value: {}", LogSanitizer.sanitize(tokenString));
            Element thisToken = StaxUtils.read(new StringReader(tokenString)).getDocumentElement();
            SimplePrincipalCollection simplePrincipalCollection = new SimplePrincipalCollection();
            simplePrincipalCollection.add(new SecurityAssertionSaml(thisToken), "default");
            SAMLAuthenticationToken samlToken = new SAMLAuthenticationToken(null, simplePrincipalCollection, request.getRemoteAddr());
            handlerResult.setToken(samlToken);
            handlerResult.setStatus(HandlerResult.Status.COMPLETED);
        } catch (IOException e) {
            LOGGER.info("Unexpected error converting cookie value to string - proceeding without SAML token.", e);
        } catch (XMLStreamException e) {
            LOGGER.info("Unexpected error converting XML string to element - proceeding without SAML token.", e);
        }
        return handlerResult;
    }
    return null;
}
Also used : Cookie(javax.servlet.http.Cookie) HandlerResultImpl(org.codice.ddf.security.handler.HandlerResultImpl) Element(org.w3c.dom.Element) SimplePrincipalCollection(org.apache.shiro.subject.SimplePrincipalCollection) HandlerResult(org.codice.ddf.security.handler.api.HandlerResult) IOException(java.io.IOException) SAMLAuthenticationToken(org.codice.ddf.security.handler.SAMLAuthenticationToken) HttpServletRequest(javax.servlet.http.HttpServletRequest) XMLStreamException(javax.xml.stream.XMLStreamException) StringReader(java.io.StringReader) SecurityAssertionSaml(ddf.security.assertion.saml.impl.SecurityAssertionSaml)

Example 73 with SimplePrincipalCollection

use of org.apache.shiro.subject.SimplePrincipalCollection in project ddf by codice.

the class LogoutRequestServiceTest method setup.

@Before
public void setup() throws ParserConfigurationException, SAXException, IOException {
    simpleSign = mock(SimpleSign.class);
    idpMetadata = mock(IdpMetadata.class);
    relayStates = mock(RelayStates.class);
    sessionFactory = mock(SessionFactory.class);
    request = mock(HttpServletRequest.class);
    logoutMessage = mock(LogoutMessageImpl.class);
    UuidGenerator uuidGenerator = mock(UuidGenerator.class);
    doReturn(UUID.randomUUID().toString()).when(uuidGenerator).generateUuid();
    doReturn(uuidGenerator).when(logoutMessage).getUuidGenerator();
    encryptionService = mock(EncryptionService.class);
    Element issuedAssertion = readSamlAssertion().getDocumentElement();
    SimplePrincipalCollection principalCollection = new SimplePrincipalCollection();
    SecurityAssertion securityAssertion = mock(SecurityAssertion.class);
    principalCollection.add(securityAssertion, "default");
    when(securityAssertion.getToken()).thenReturn(issuedAssertion);
    PrincipalHolder principalHolder = mock(PrincipalHolder.class);
    when(principalHolder.getPrincipals()).thenReturn(principalCollection);
    initializeLogoutRequestService();
    HttpSession session = mock(HttpSession.class);
    when(sessionFactory.getOrCreateSession(request)).thenReturn(session);
    when(session.getAttribute(eq(SecurityConstants.SECURITY_TOKEN_KEY))).thenReturn(principalHolder);
    when(request.getRequestURL()).thenReturn(new StringBuffer("https://www.url.com/url"));
    when(idpMetadata.getSigningCertificate()).thenReturn("signingCertificate");
    when(idpMetadata.getSingleLogoutBinding()).thenReturn(SamlProtocol.REDIRECT_BINDING);
    when(idpMetadata.getSingleLogoutLocation()).thenReturn(redirectLogoutUrl);
}
Also used : SessionFactory(ddf.security.http.SessionFactory) RelayStates(ddf.security.samlp.impl.RelayStates) UuidGenerator(org.codice.ddf.platform.util.uuidgenerator.UuidGenerator) HttpSession(javax.servlet.http.HttpSession) LogoutMessageImpl(ddf.security.samlp.impl.LogoutMessageImpl) Element(org.w3c.dom.Element) SimplePrincipalCollection(org.apache.shiro.subject.SimplePrincipalCollection) SecurityAssertion(ddf.security.assertion.SecurityAssertion) HttpServletRequest(javax.servlet.http.HttpServletRequest) SimpleSign(ddf.security.samlp.impl.SimpleSign) EncryptionService(ddf.security.encryption.EncryptionService) PrincipalHolder(ddf.security.common.PrincipalHolder) Before(org.junit.Before)

Example 74 with SimplePrincipalCollection

use of org.apache.shiro.subject.SimplePrincipalCollection in project killbill by killbill.

the class TestKillBillOktaRealm method testCheckOktaConnection.

@Test(groups = "external", enabled = false)
public void testCheckOktaConnection() throws Exception {
    // Convenience method to verify your Okta connectivity
    final Properties props = new Properties();
    props.setProperty("org.killbill.security.okta.url", "https://dev-XXXXXX.oktapreview.com");
    props.setProperty("org.killbill.security.okta.apiToken", "YYYYYY");
    props.setProperty("org.killbill.security.okta.permissionsByGroup", "support-group: entitlement:*\n" + "finance-group: invoice:*, payment:*\n" + "ops-group: *:*");
    final ConfigSource customConfigSource = new SimplePropertyConfigSource(props);
    final SecurityConfig securityConfig = new ConfigurationObjectFactory(customConfigSource).build(SecurityConfig.class);
    final KillBillOktaRealm oktaRealm = new KillBillOktaRealm(securityConfig);
    final String username = "pierre";
    final String password = "password";
    // Check authentication
    final UsernamePasswordToken token = new UsernamePasswordToken(username, password);
    final AuthenticationInfo authenticationInfo = oktaRealm.getAuthenticationInfo(token);
    System.out.println(authenticationInfo);
    // Check permissions
    final SimplePrincipalCollection principals = new SimplePrincipalCollection(username, username);
    final AuthorizationInfo authorizationInfo = oktaRealm.doGetAuthorizationInfo(principals);
    System.out.println("Roles: " + authorizationInfo.getRoles());
    System.out.println("Permissions: " + authorizationInfo.getStringPermissions());
}
Also used : SimplePropertyConfigSource(org.skife.config.SimplePropertyConfigSource) ConfigSource(org.skife.config.ConfigSource) SimplePropertyConfigSource(org.skife.config.SimplePropertyConfigSource) SecurityConfig(org.killbill.billing.util.config.definition.SecurityConfig) ConfigurationObjectFactory(org.skife.config.ConfigurationObjectFactory) SimplePrincipalCollection(org.apache.shiro.subject.SimplePrincipalCollection) Properties(java.util.Properties) AuthorizationInfo(org.apache.shiro.authz.AuthorizationInfo) AuthenticationInfo(org.apache.shiro.authc.AuthenticationInfo) UsernamePasswordToken(org.apache.shiro.authc.UsernamePasswordToken) Test(org.testng.annotations.Test)

Example 75 with SimplePrincipalCollection

use of org.apache.shiro.subject.SimplePrincipalCollection in project wechat by dllwh.

the class CustomSessionManager method getSessionEntity.

/**
 * ----------------------------------------------- [私有方法]
 */
private OnlineUser getSessionEntity(Session session) {
    /**
     * 获取登录信息
     */
    Object obj = session.getAttribute(DefaultSubjectContext.PRINCIPALS_SESSION_KEY);
    if (null == obj) {
        return null;
    }
    if (obj instanceof SimplePrincipalCollection) {
        SimplePrincipalCollection spc = (SimplePrincipalCollection) obj;
        obj = spc.getPrimaryPrincipal();
        if (null != obj && obj instanceof SysUser) {
            OnlineUser onlineUser = new OnlineUser((SysUser) obj);
            // 最后一次和系统交互的时间
            onlineUser.setLastAccess(session.getLastAccessTime());
            // 主机的ip地址
            onlineUser.setHost(session.getHost());
            // session ID
            onlineUser.setSessionId(session.getId().toString());
            // 会话到期
            onlineUser.setTimeout(session.getTimeout());
            // 会话创建
            onlineUser.setStartTime(session.getStartTimestamp());
            SessionStatus sessionStatus = (SessionStatus) session.getAttribute(CacheConstans.SESSION_STATUS);
            boolean status = Boolean.TRUE;
            if (null != sessionStatus) {
                status = sessionStatus.getOnlineStatus();
            }
            onlineUser.setSessionStatus(status);
            return onlineUser;
        }
    }
    return null;
}
Also used : SysUser(com.cdeledu.model.rbac.SysUser) OnlineUser(com.cdeledu.model.system.OnlineUser) SimplePrincipalCollection(org.apache.shiro.subject.SimplePrincipalCollection)

Aggregations

SimplePrincipalCollection (org.apache.shiro.subject.SimplePrincipalCollection)87 Test (org.junit.Test)38 PrincipalCollection (org.apache.shiro.subject.PrincipalCollection)34 SimpleAuthenticationInfo (org.apache.shiro.authc.SimpleAuthenticationInfo)12 Element (org.w3c.dom.Element)12 SecurityAssertion (ddf.security.assertion.SecurityAssertion)11 AuthorizationInfo (org.apache.shiro.authz.AuthorizationInfo)11 DefaultSecurityManager (org.apache.shiro.mgt.DefaultSecurityManager)11 SecurityAssertionSaml (ddf.security.assertion.saml.impl.SecurityAssertionSaml)10 Principal (java.security.Principal)10 SAMLAuthenticationToken (org.codice.ddf.security.handler.SAMLAuthenticationToken)10 ArrayList (java.util.ArrayList)9 Subject (org.apache.shiro.subject.Subject)9 AuthenticationInfo (org.apache.shiro.authc.AuthenticationInfo)8 Subject (ddf.security.Subject)7 AuthenticationException (org.apache.shiro.authc.AuthenticationException)7 Realm (org.apache.shiro.realm.Realm)7 SimpleSession (org.apache.shiro.session.mgt.SimpleSession)7 UsernamePasswordToken (org.apache.shiro.authc.UsernamePasswordToken)6 Assertion (org.opensaml.saml.saml2.core.Assertion)6