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:net.firejack.platform.web.security.spring.AuthenticationManager.java

protected Authentication doAuthentication(Authentication authentication) throws AuthenticationException {
    if (authentication.getPrincipal() == null || authentication.getCredentials() == null
            || authentication.getDetails() == null) {
        String errorMessage = MessageResolver.messageFormatting("login.wrong.credentials", null);
        throw new BadCredentialsException(errorMessage);
    }/*from ww  w  .  j  av a2 s . c  om*/

    String userName = authentication.getPrincipal().toString();
    String password = authentication.getCredentials().toString();
    HttpSession session = ((AuthenticationToken) authentication).getSession();

    if (StringUtils.isNotBlank(userName) && StringUtils.isNotBlank(password)) {
        if (!getAuthenticators().isEmpty()) {
            AuthenticatorFactory authenticatorFactory = AuthenticatorFactory.getInstance();
            IAuthenticationSource authenticationSource = authenticatorFactory
                    .provideDefaultAuthenticationSource(userName, password);
            for (IAuthenticator authenticator : getAuthenticators()) {
                IAuthenticationDetails authenticationDetails = authenticator.authenticate(authenticationSource);
                if (authenticationDetails != null) {
                    return generateDefaultToken(authenticationDetails, session);
                }
            }
        }
    }

    String errorMessage = MessageResolver.messageFormatting("login.authentication.failure", null);
    throw new BadCredentialsException(errorMessage);
}

From source file:com.klm.workshop.controller.host.manage.AccountController.java

/**
 * Retrieve the currently logged in user
 * // ww w  . ja v a  2s . c  o  m
 * @return Current user
 */
private User getCurrentUser() {
    Authentication auth = SecurityContextHolder.getContext().getAuthentication();
    CustomUserDetails details = (CustomUserDetails) auth.getPrincipal();
    return details.getUser();
}

From source file:org.kmnet.com.fw.web.security.logging.UserIdMDCPutFilter.java

/**
 * fetches the username which has been authenticated
 * @param request {@link HttpServletRequest}
 * @param response {@link HttpServletResponse}
 * @return username//  w w  w .  jav a  2s .  c om
 * @see org.kmnet.com.fw.web.logging.mdc.AbstractMDCPutFilter#getMDCValue(HttpServletRequest, HttpServletResponse)
 */
@Override
protected String getMDCValue(HttpServletRequest request, HttpServletResponse response) {

    Authentication authentication = SecurityContextHolder.getContext().getAuthentication();

    if (authentication != null) {
        Object principal = authentication.getPrincipal();
        if (principal instanceof UserDetails) {
            return ((UserDetails) principal).getUsername();
        }
        return principal.toString();
    }

    return null;
}

From source file:org.duracloud.duradmin.util.SpaceUtil.java

public static AclType resolveCallerAcl(String spaceId, ContentStore store, Map<String, AclType> acls,
        Authentication authentication, Boolean snapshotInProgress) throws ContentStoreException {
    //if a snapshot is in progress, read only
    // check authorities
    if (isRoot(authentication)) {
        return AclType.WRITE;
    }//from   w ww  . j a  v  a  2  s .com

    if (snapshotInProgress == null) {
        snapshotInProgress = false;
        if (isSnapshotProvider(store)) {
            snapshotInProgress = isSnapshotInProgress(store, spaceId);
        }
    }

    if (spaceId.equals(Constants.SNAPSHOT_METADATA_SPACE)) {
        return AclType.READ;
    }

    if (snapshotInProgress) {
        return AclType.READ;
    }
    // check authorities
    if (isAdmin(authentication)) {
        return AclType.WRITE;
    }

    AclType callerAcl = null;

    DuracloudUserDetails details = (DuracloudUserDetails) authentication.getPrincipal();
    List<String> userGroups = details.getGroups();

    for (Map.Entry<String, AclType> e : acls.entrySet()) {
        AclType value = e.getValue();

        if (e.getKey().equals(details.getUsername()) || userGroups.contains(e.getKey())) {
            callerAcl = value;
            if (AclType.WRITE.equals(callerAcl)) {
                break;
            }
        }
    }

    return callerAcl;
}

From source file:eu.supersede.fe.rest.NotificationRest.java

@RequestMapping(method = RequestMethod.DELETE, value = "/{notificationId}")
public void delete(Authentication authentication, @PathVariable Long notificationId) {
    DatabaseUser currentUser = (DatabaseUser) authentication.getPrincipal();
    User u = users.getOne(currentUser.getUserId());
    Notification n = notifications.findOne(notificationId);

    if (n.getUser().equals(u)) {
        notifications.delete(notificationId);
    } else {//from  w  ww .j  a  v a 2 s.  c o  m
        throw new UnauthorizedException();
    }
}

From source file:com.sitewhere.security.SitewhereAuthenticationProvider.java

public Authentication authenticate(Authentication input) throws AuthenticationException {
    try {//from w  w w .ja va2 s  .com
        if (input instanceof UsernamePasswordAuthenticationToken) {
            String username = (String) input.getPrincipal();
            String password = (String) input.getCredentials();
            IUser user = SiteWhereServer.getInstance().getUserManagement().authenticate(username, password);
            List<IGrantedAuthority> auths = SiteWhereServer.getInstance().getUserManagement()
                    .getGrantedAuthorities(user.getUsername());
            SitewhereUserDetails details = new SitewhereUserDetails(user, auths);
            return new SitewhereAuthentication(details, password);
        } else if (input instanceof SitewhereAuthentication) {
            return input;
        } else {
            throw new AuthenticationServiceException("Unknown authentication: " + input.getClass().getName());
        }
    } catch (SiteWhereException e) {
        throw new BadCredentialsException("Unable to authenticate.", e);
    }
}

From source file:com.trenako.web.security.SpringSignupServiceTests.java

@Test
public void shouldAuthenticateAccounts() {
    SecurityContext mockContext = mock(SecurityContext.class);

    Account account = buildAccount();//w w w . j  av  a  2  s.  c om
    AccountDetails accountDetails = new AccountDetails(account);

    // inject the mock security context
    service.setSecurityContext(mockContext);
    service.authenticate(account);

    ArgumentCaptor<Authentication> arg = ArgumentCaptor.forClass(Authentication.class);
    verify(mockContext, times(1)).setAuthentication(arg.capture());
    Authentication auth = arg.getValue();
    assertEquals("pa$$word", auth.getCredentials());
    assertEquals(accountDetails, auth.getPrincipal());
    assertEquals(account.getRoles().toString(), auth.getAuthorities().toString());
}

From source file:eu.supersede.fe.rest.NotificationRest.java

@RequestMapping(method = RequestMethod.PUT, value = "/{notificationId}/read")
public void setRead(Authentication authentication, @PathVariable Long notificationId) {
    DatabaseUser currentUser = (DatabaseUser) authentication.getPrincipal();
    User u = users.getOne(currentUser.getUserId());
    Notification n = notifications.findOne(notificationId);

    if (n.getUser().equals(u)) {
        n.setRead(true);/*  www .  ja  v a 2  s .c  o m*/
        notifications.save(n);
    } else {
        throw new UnauthorizedException();
    }
}

From source file:org.musicrecital.service.UserSecurityAdvice.java

private User getCurrentUser(Authentication auth, UserManager userManager) {
    User currentUser;//from ww w .  j a va 2  s.  c om
    if (auth.getPrincipal() instanceof LdapUserDetails) {
        LdapUserDetails ldapDetails = (LdapUserDetails) auth.getPrincipal();
        String username = ldapDetails.getUsername();
        currentUser = userManager.getUserByUsername(username);
    } else if (auth.getPrincipal() instanceof UserDetails) {
        currentUser = (User) auth.getPrincipal();
    } else if (auth.getDetails() instanceof UserDetails) {
        currentUser = (User) auth.getDetails();
    } else {
        throw new AccessDeniedException("User not properly authenticated.");
    }
    return currentUser;
}

From source file:org.socialsignin.exfmproxy.mvc.workaround.auth.WorkaroundExFmUserPasswordService.java

public String getAuthenticatedUserPassword() {

    Authentication authentication = SecurityContextHolder.getContext().getAuthentication();
    return authentication == null || authentication.getName().equals("anonymousUser") ? null
            : ((String) ((User) authentication.getPrincipal()).getPassword());
}