Example usage for org.springframework.security.core Authentication getPrincipal

List of usage examples for org.springframework.security.core Authentication getPrincipal

Introduction

In this page you can find the example usage for org.springframework.security.core Authentication getPrincipal.

Prototype

Object getPrincipal();

Source Link

Document

The identity of the principal being authenticated.

Usage

From source file:org.pac4j.saml.client.Saml2ClientWrapper.java

protected Saml2WrapperCredentials retrieveCredentials(final WebContext wc) throws RequiresHttpAction {

    J2EContext jc = (J2EContext) wc;/*from w  w w.  j  a  v  a2 s .c o  m*/
    HttpServletRequest request = jc.getRequest();
    HttpServletResponse response = jc.getResponse();

    org.springframework.security.core.Authentication samlAuthentication = sAMLProcessingFilter
            .attemptAuthentication(request, response);

    NameID nameID = (NameID) samlAuthentication.getPrincipal();

    SAMLCredential sAMLCredential = (SAMLCredential) samlAuthentication.getCredentials();

    List<Attribute> attributes = sAMLCredential.getAttributes();

    Saml2WrapperCredentials saml2Credentials = new Saml2WrapperCredentials(nameID, attributes,
            this.getClass().getSimpleName(), samlAuthentication);

    return saml2Credentials;

}

From source file:eu.freme.broker.tools.ratelimiter.RateLimitingFilter.java

@Override
public void doFilter(ServletRequest req, ServletResponse res, FilterChain chain)
        throws IOException, ServletException {

    if (rateLimiterEnabled) {

        HttpServletRequest request = (HttpServletRequest) req;
        Authentication auth = SecurityContextHolder.getContext().getAuthentication();

        username = auth.getName();//  w  ww  . j a v a2s .  c o  m
        if (username.equals("anonymousUser")) {
            username = req.getRemoteAddr();
        } else {
            User user = ((User) auth.getPrincipal());
            username = user.getName();
        }

        userRole = ((SimpleGrantedAuthority) auth.getAuthorities().toArray()[0]).getAuthority();

        long size = req.getContentLength();
        if (size == 0) {
            try {
                size = request.getHeader("input").length();
            } catch (NullPointerException e) {
                //Then the size is truly 0
            }
        }
        try {
            rateLimiterInMemory.addToStoredRequests(username, new Date().getTime(), size,
                    request.getRequestURI(), userRole);
        } catch (TooManyRequestsException e) {
            HttpServletResponse response = (HttpServletResponse) res;
            exceptionHandlerService.writeExceptionToResponse(request, response, e);
            return;
        }
    }

    chain.doFilter(req, res);

}

From source file:org.xaloon.wicket.security.spring.SpringSecurityFacade.java

@Override
public boolean isLoggedIn() {
    Authentication authentication = SecurityContextHolder.getContext().getAuthentication();
    return (authentication != null && authentication.isAuthenticated()
            && !ANONYMOUS_USER.equalsIgnoreCase(authentication.getPrincipal().toString()));
}

From source file:com.springsource.hq.plugin.tcserver.serverconfig.web.support.HqAuthenticationFilter.java

/**
 * This takes an existing Authentication object, and converts it into an tc Server plugin-based object.
 * //from   w  w  w  .  j a v a2  s .c om
 * @param auth
 * @param sessionId
 * @return
 */
private UsernamePasswordAuthenticationToken createHqAuthenticationToken(Authentication auth, String sessionId) {
    List<GrantedAuthority> auths = new ArrayList<GrantedAuthority>();
    auths.addAll(auth.getAuthorities());
    auths.add(new GrantedAuthorityImpl(defaultRole));
    UsernamePasswordAuthenticationToken newToken = new HqAuthenticationToken(auth.getPrincipal(),
            auth.getCredentials(), auths, sessionId);
    return newToken;
}

From source file:shiver.me.timbers.spring.security.jwt.JwtPrincipalAuthenticationConverterTest.java

@Test
@SuppressWarnings("unchecked")
public void Can_convert_an_authentication_with_a_user_details_to_a_jwt_principle() {

    final Authentication authentication = mock(Authentication.class);

    final UserDetails userDetails = mock(UserDetails.class);
    final String username = someString();
    final Collection<GrantedAuthority> authorities = mock(Collection.class);
    final List<String> roles = mock(List.class);

    // Given//  w w  w. ja v  a 2 s . c om
    given(authentication.getPrincipal()).willReturn(userDetails);
    given(userDetails.getUsername()).willReturn(username);
    given(authentication.getAuthorities()).willReturn((Collection) authorities);
    given(grantedAuthorityConverter.convert(authorities)).willReturn(roles);

    // When
    final JwtPrincipal actual = converter.convert(authentication);

    // Then
    assertThat(actual.getUsername(), is(username));
    assertThat(actual.getRoles(), is(roles));
}

From source file:nz.net.orcon.kanban.tools.ListTools.java

public String getCurrentUser() {
    SecurityContext context = SecurityContextHolder.getContext();
    Authentication authentication = context.getAuthentication();
    Object principal = "system";
    if (authentication != null) {
        principal = authentication.getPrincipal();
    }//from  w w w  .  ja v a  2s .  c o m
    return (String) principal;
}

From source file:uk.org.rbc1b.roms.security.RomsPermissionEvaluator.java

/**
 * @param authentication authentication (username, authorities) derived form the data source
 * @param targetDomainObject object type to be viewed/modified, e.g. Circuit
 * @param permission permission level required, matching the AccessLevel enumeration
 * @return true if the user can perform the task
 *//*ww  w . j  a  va2s . c o  m*/
@Override
public boolean hasPermission(Authentication authentication, Object targetDomainObject, Object permission) {

    AccessLevel level;
    try {
        level = AccessLevel.valueOf(permission.toString());
    } catch (IllegalArgumentException e) {
        throw new IllegalArgumentException("Invalid access level [" + permission + "]");
    }

    ROMSUserDetails user = (ROMSUserDetails) authentication.getPrincipal();

    return hasPermission(user, Application.valueOf((String) targetDomainObject), level);

}

From source file:com.bisone.saiku.security.replace.SessionService.java

private void createSession(Authentication auth, String username, String password) {

    if (auth == null || !auth.isAuthenticated()) {
        return;//  w  w w.j  av  a  2  s. co m
    }

    boolean isAnonymousUser = (auth instanceof AnonymousAuthenticationToken);
    Object p = auth.getPrincipal();
    String authUser = getUsername(p);
    boolean isAnonymous = (isAnonymousUser || StringUtils.equals("anonymousUser", authUser));
    boolean isAnonOk = (!isAnonymous || (isAnonymous && anonymous));

    if (isAnonOk && auth.isAuthenticated() && p != null && !sessionHolder.containsKey(p)) {
        Map<String, Object> session = new HashMap<String, Object>();

        if (isAnonymous) {
            log.debug("Creating Session for Anonymous User");
        }

        if (StringUtils.isNotBlank(username)) {
            session.put("username", username);
        } else {
            session.put("username", authUser);
        }
        if (StringUtils.isNotBlank(password)) {
            session.put("password", password);
        }
        session.put("sessionid", UUID.randomUUID().toString());
        session.put("authid", RequestContextHolder.currentRequestAttributes().getSessionId());
        List<String> roles = new ArrayList<String>();
        for (GrantedAuthority ga : SecurityContextHolder.getContext().getAuthentication().getAuthorities()) {
            roles.add(ga.getAuthority());
        }
        session.put("roles", roles);

        sessionHolder.put(p, session);
    }

}

From source file:org.duracloud.account.app.controller.AmaTestBase.java

protected void intializeAuthManager() {
    Authentication auth = createMock(Authentication.class);

    EasyMock.expect(auth.getName()).andReturn(TEST_USERNAME).anyTimes();
    authenticationManager = createMock(AuthenticationManager.class);

    SecurityContext ctx = new SecurityContextImpl();
    ctx.setAuthentication(auth);/* www .ja  v a 2s . c  o m*/
    EasyMock.expect(auth.getPrincipal()).andReturn(createUser()).anyTimes();
    SecurityContextHolder.setContext(ctx);
}

From source file:cz.swi2.mendeluis.app.web.security.CustomPermissionsEvaluator.java

/**
 * Checks the current logged in user's permission to the object with the given id. 
 * @param authentication/*from w ww.j  av a  2 s .c  om*/
 * @param targetId
 * @param targetType
 * @param permission
 * @return True if the user has right to access the object. 
 */
@Override
public boolean hasPermission(Authentication authentication, Serializable targetId, String targetType,
        Object permission) {
    boolean hasPermission = false;
    if (targetId != null && "UserPortlet".equals(targetType)) {
        UserPortletDTO up = userPortletFacade.getUserPortletWithId((int) targetId);
        if (up != null) {
            UserDetails userDetails = (UserDetails) authentication.getPrincipal();
            UserDTO user = userFacade.getUserByUsername(userDetails.getUsername());
            UserDTO user2 = up.getUser();
            hasPermission = (user.getId() == user2.getId());
            logger.info("Checking username {} has permission to access member {} - {}",
                    userDetails.getUsername(), up, hasPermission);
        }
    }
    return hasPermission;
}