Example usage for org.springframework.security.cas.authentication CasAuthenticationToken getAssertion

List of usage examples for org.springframework.security.cas.authentication CasAuthenticationToken getAssertion

Introduction

In this page you can find the example usage for org.springframework.security.cas.authentication CasAuthenticationToken getAssertion.

Prototype

public Assertion getAssertion() 

Source Link

Usage

From source file:eu.trentorise.smartcampus.permissionprovider.authority.CASAuthorityHandler.java

@SuppressWarnings("unchecked")
@Override//  ww w.j a  va  2s  . c o m
public Map<String, String> extractAttributes(HttpServletRequest request, Map<String, String> map,
        AuthorityMapping mapping) {
    Map<String, String> attrs = new HashMap<String, String>();

    CasAuthenticationToken token = (CasAuthenticationToken) SecurityContextHolder.getContext()
            .getAuthentication();
    String username = token.getName();
    Map<String, Object> tokenAttrs = token.getAssertion().getAttributes();
    if (tokenAttrs == null) {
        tokenAttrs = new HashMap<String, Object>();
    }
    tokenAttrs.put(USERNAME, username);

    for (String key : mapping.getIdentifyingAttributes()) {
        Object value = readAttribute(key, tokenAttrs);
        if (value != null) {
            attrs.put(key, value.toString());
        }
    }
    for (Attributes attribute : mapping.getAttributes()) {
        // used alias if present to set attribute in map
        String key = (attribute.getAlias() != null && !attribute.getAlias().isEmpty()) ? attribute.getAlias()
                : attribute.getValue();
        Object value = readAttribute(attribute.getValue(), tokenAttrs);
        if (value != null) {
            attrs.put(key, value.toString());
        }
    }
    return attrs;
}

From source file:pl.fraanek.caspresentation.client.springsecurity.ProxyTicketSampleServlet.java

@Override
protected void doGet(HttpServletRequest request, HttpServletResponse response)
        throws ServletException, IOException {
    // NOTE: The CasAuthenticationToken can also be obtained using SecurityContextHolder.getContext().getAuthentication()
    final CasAuthenticationToken token = (CasAuthenticationToken) request.getUserPrincipal();
    // proxyTicket could be reused to make calls to to the CAS service even if the target url differs
    final String proxyTicket = token.getAssertion().getPrincipal().getProxyTicketFor(targetUrl);

    // Make a remote call to ourself. This is a bit silly, but it works well to demonstrate how to use proxy tickets.
    final String serviceUrl = targetUrl + "?ticket=" + URLEncoder.encode(proxyTicket, "UTF-8");
    String proxyResponse = CommonUtils.getResponseFromServer(serviceUrl, "UTF-8");

    // modify the response and write it out to inform the user that it was obtained using a proxy ticket.
    proxyResponse = proxyResponse.replaceFirst("Secure Page", "Secure Page using a Proxy Ticket");
    proxyResponse = proxyResponse.replaceFirst("<p>",
            "<p>This page is rendered by " + getClass().getSimpleName()
                    + " by making a remote call to the Secure Page using a proxy ticket (" + proxyTicket
                    + ") and inserts this message. ");
    final PrintWriter writer = response.getWriter();
    writer.write(proxyResponse);//w  ww. j a  v a  2  s . c  o  m
}

From source file:com.xinlei.core.app.cas.web.ProxyTicketSampleServlet.java

@Override
public void doGet(HttpServletRequest request, HttpServletResponse response)
        throws ServletException, IOException {
    // NOTE: The CasAuthenticationToken can also be obtained using
    // SecurityContextHolder.getContext().getAuthentication()
    final CasAuthenticationToken token = (CasAuthenticationToken) request.getUserPrincipal();
    // proxyTicket could be reused to make calls to to the CAS service even if the
    // target url differs
    final String proxyTicket = token.getAssertion().getPrincipal().getProxyTicketFor(targetUrl);

    // Make a remote call to ourselves. This is a bit silly, but it works well to
    // demonstrate how to use proxy tickets.
    final String serviceUrl = targetUrl + "?ticket=" + URLEncoder.encode(proxyTicket, "UTF-8");
    String proxyResponse = CommonUtils.getResponseFromServer(new URL(serviceUrl),
            new HttpsURLConnectionFactory(), "UTF-8");

    // modify the response and write it out to inform the user that it was obtained
    // using a proxy ticket.
    proxyResponse = proxyResponse.replaceFirst("Secure Page", "Secure Page using a Proxy Ticket");
    proxyResponse = proxyResponse.replaceFirst("<p>",
            "<p>This page is rendered by " + getClass().getSimpleName()
                    + " by making a remote call to the Secure Page using a proxy ticket (" + proxyTicket
                    + ") and inserts this message. ");
    response.setContentType("text/html;charset=UTF-8");
    final PrintWriter writer = response.getWriter();
    writer.write(proxyResponse);/*from  w  w w.j a v a2s .  c  o  m*/
}

From source file:com.gdn.iam.spring.security.FortressDecisionVoter.java

@Override
@SuppressWarnings("static-access")
public int vote(Authentication authentication, FilterInvocation fi, Collection<ConfigAttribute> attributes) {
    Authentication securityContextAuthentication = SecurityContextHolder.getContext().getAuthentication();
    int result = super.vote(securityContextAuthentication, fi, attributes);
    if (System.getenv(IAM_SECURITY_PARAMETER) != null) {
        LOG.warn("iam security is disable, enable all access mode is enable");
        return result;
    } else {//  w w  w  . j a v  a 2  s.  co m
        LOG.debug("authentication = {}", ToStringBuilder.reflectionToString(securityContextAuthentication));
        LOG.debug("super vote for : {}", result);
        if (super.ACCESS_GRANTED == result) {
            String requestMethod = fi.getRequest().getMethod().toLowerCase();
            String filterUrl = getFilterUrl(fi.getHttpRequest());
            if (filterUrl == null) {
                return result;
            }
            try {
                CasAuthenticationToken casAuthenticationToken = ((CasAuthenticationToken) securityContextAuthentication);
                LOG.debug("assertion : {}",
                        ToStringBuilder.reflectionToString(casAuthenticationToken.getAssertion()));
                String iamSessionXml = (String) casAuthenticationToken.getAssertion().getAttributes()
                        .get(IAM_SESSION_ATTRIBUTE_KEY);
                LOG.debug("iam session xml == {}", iamSessionXml);
                Session iamSession = sessionCache.getIfPresent(casAuthenticationToken.getKeyHash());
                if (iamSession == null) {
                    Unmarshaller unmarshaller = null;
                    try {
                        unmarshaller = context.createUnmarshaller();
                    } catch (JAXBException ex) {
                        LOG.warn("cannot create unmarshaller : ", ex);
                    }
                    iamSession = (Session) unmarshaller.unmarshal(new StringReader(iamSessionXml));
                    sessionCache.put(casAuthenticationToken.getKeyHash(), iamSession);
                }
                StringBuilder sessionPermissionKeyBuilder = new StringBuilder(iamSession.getSessionId())
                        .append(filterUrl).append(requestMethod);
                Boolean isAllowed = accessCache.getIfPresent(sessionPermissionKeyBuilder.toString());
                if (isAllowed == null) {
                    isAllowed = accessManager.checkAccess(iamSession, new Permission(filterUrl, requestMethod));
                    accessCache.put(sessionPermissionKeyBuilder.toString(), isAllowed);
                }
                LOG.debug("{} is {} to access {} with method {}",
                        new Object[] { securityContextAuthentication.getName(),
                                isAllowed ? "granted" : "denied", filterUrl, requestMethod });
                if (isAllowed) {
                    return super.ACCESS_GRANTED;
                }
            } catch (Exception e) {
                LOG.error("catch exception when communicate with iam server", e);
            }
        }
        return super.ACCESS_DENIED;
    }
}

From source file:de.thm.arsnova.services.UserService.java

@Override
public User getCurrentUser() {
    final Authentication authentication = SecurityContextHolder.getContext().getAuthentication();
    if (authentication == null || authentication.getPrincipal() == null) {
        return null;
    }/*from   ww  w. ja  v  a2 s .co m*/

    User user = null;

    if (authentication instanceof OAuthAuthenticationToken) {
        user = getOAuthUser(authentication);
    } else if (authentication instanceof CasAuthenticationToken) {
        final CasAuthenticationToken token = (CasAuthenticationToken) authentication;
        user = new User(token.getAssertion().getPrincipal());
    } else if (authentication instanceof AnonymousAuthenticationToken) {
        final AnonymousAuthenticationToken token = (AnonymousAuthenticationToken) authentication;
        user = new User(token);
    } else if (authentication instanceof UsernamePasswordAuthenticationToken) {
        final UsernamePasswordAuthenticationToken token = (UsernamePasswordAuthenticationToken) authentication;
        user = new User(token);
        if (authentication.getAuthorities().contains(new SimpleGrantedAuthority("ROLE_GUEST"))) {
            user.setType(User.GUEST);
        } else if (authentication.getAuthorities().contains(new SimpleGrantedAuthority("ROLE_DB_USER"))) {
            user.setType(User.ARSNOVA);
        }
    }

    if (user == null || user.getUsername().equals("anonymous")) {
        throw new UnauthorizedException();
    }

    return user;
}