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:nl.surfnet.coin.api.AbstractApiController.java

/**
 * Get the username of the (via oauth) authenticated user that performs this
 * request.//  ww w.j a va  2 s. co m
 * 
 * @return the username in case of an end user authorized request (3 legged
 *         oauth1, authorization code grant oauth2) or the consumer key in
 *         case of unauthorized requests.
 */
protected String getOnBehalfOf() {
    Authentication auth = SecurityContextHolder.getContext().getAuthentication();
    if (auth == null) {
        return null;
    } else {
        Object principal = auth.getPrincipal();
        if (auth instanceof OAuth2Authentication && ((OAuth2Authentication) auth).isClientOnly()) {
            //oauth2 client credentials
            return null;
        } else if (principal instanceof ConsumerDetails) {
            // Two legged, it does not have end user details
            return null;
        } else if (principal instanceof String) {
            return (String) principal;
        } else if (principal instanceof OAuthAuthenticationDetails) {
            return ((OAuthAuthenticationDetails) principal).getConsumerDetails().getConsumerName();
        } else if (principal instanceof ClientMetaDataPrincipal) {
            return ((ClientMetaDataPrincipal) principal).getRemoteUser();
        } else if (principal instanceof UserDetails) {
            return ((UserDetails) principal).getUsername();
        } else {
            throw new RuntimeException("Unexpected principal class: " + principal.getClass().getName());
        }
    }
}

From source file:org.jasig.schedassist.web.register.RegistrationFlowHelper.java

/**
 * Invoke methods on the {@link OwnerDao} and {@link AvailableScheduleDao} to complete
 * the registration process.// w  w w .ja v  a  2 s.  com
 * 
 * @param registration
 * @throws IneligibleException
 * @throws ParseException 
 * @throws InputFormatException 
 */
public void executeRegistration(final Registration registration)
        throws IneligibleException, InputFormatException, ParseException {
    SecurityContext context = SecurityContextHolder.getContext();
    Authentication authentication = context.getAuthentication();
    CalendarAccountUserDetailsImpl currentUser = (CalendarAccountUserDetailsImpl) authentication.getPrincipal();
    IScheduleOwner owner = ownerDao.register(currentUser.getCalendarAccount());
    owner = ownerDao.updatePreference(owner, Preferences.DURATIONS, registration.durationPreferenceValue());
    owner = ownerDao.updatePreference(owner, Preferences.LOCATION, registration.getLocation());
    owner = ownerDao.updatePreference(owner, Preferences.MEETING_PREFIX, registration.getTitlePrefix());
    owner = ownerDao.updatePreference(owner, Preferences.NOTEBOARD, registration.getNoteboard());
    owner = ownerDao.updatePreference(owner, Preferences.VISIBLE_WINDOW,
            registration.visibleWindowPreferenceKey());
    owner = ownerDao.updatePreference(owner, Preferences.DEFAULT_VISITOR_LIMIT,
            Integer.toString(registration.getDefaultVisitorsPerAppointment()));
    owner = ownerDao.updatePreference(owner, Preferences.MEETING_LIMIT,
            Integer.toString(registration.getMeetingLimitValue()));
    owner = ownerDao.updatePreference(owner, Preferences.REFLECT_SCHEDULE,
            Boolean.toString(registration.isReflectSchedule()));
    owner = ownerDao.updatePreference(owner, Preferences.REMINDERS, registration.emailReminderPreferenceKey());

    if (affiliationSource.doesAccountHaveAffiliation(owner.getCalendarAccount(), AffiliationImpl.ADVISOR)) {
        // set ADVISOR_SHARE_WITH_STUDENTS by default for all academic advisors
        owner = ownerDao.updatePreference(owner, Preferences.ADVISOR_SHARE_WITH_STUDENTS, "true");
    }
    if (affiliationSource.doesAccountHaveAffiliation(owner.getCalendarAccount(), AffiliationImpl.INSTRUCTOR)) {
        // set INSTRUCTOR_SHARE_WITH_STUDENTS by default for all instructors
        owner = ownerDao.updatePreference(owner, Preferences.INSTRUCTOR_SHARE_WITH_STUDENTS, "true");
    }
    if (registration.isScheduleSet()) {
        SimpleDateFormat dateFormat = new SimpleDateFormat("MM/dd/yyyy");
        Set<AvailableBlock> blocks = AvailableBlockBuilder.createBlocks(registration.getStartTimePhrase(),
                registration.getEndTimePhrase(), registration.getDaysOfWeekPhrase(),
                dateFormat.parse(registration.getStartDatePhrase()),
                dateFormat.parse(registration.getEndDatePhrase()),
                registration.getDefaultVisitorsPerAppointment());
        availableScheduleDao.addToSchedule(owner, blocks);
    }

    if (registration.isReflectSchedule()) {
        reflectionService.reflectAvailableSchedule(owner);
    }

    // since Spring Security won't let you update someone's Authorities, have to force re-auth
    SecurityContextHolder.clearContext();
}

From source file:com.evolveum.midpoint.web.security.MidPointAuthenticationProvider.java

@Override
public Authentication authenticate(Authentication authentication) throws AuthenticationException {
    if (StringUtils.isBlank((String) authentication.getPrincipal())) {
        throw new BadCredentialsException("web.security.provider.invalid");
    }//w w w  .  j a  v a2s. c  o  m

    MidPointPrincipal principal = null;
    try {
        principal = userProfileService.getPrincipal((String) authentication.getPrincipal());
    } catch (ObjectNotFoundException ex) {
        LOGGER.debug("Authentication of user with username '{}' failed: not found: {}", ex.getMessage(), ex);
        throw new BadCredentialsException("web.security.provider.access.denied");
    } catch (Exception ex) {
        LOGGER.error("Can't get user with username '{}'. Unknown error occured, reason {}.",
                new Object[] { authentication.getPrincipal(), ex.getMessage(), ex });
        throw new AuthenticationServiceException("web.security.provider.unavailable");
    }

    Authentication token = null;
    try {
        token = authenticateUser(principal, authentication);
    } catch (BadCredentialsException ex) {
        LOGGER.debug("Authentication of user with username '{}' failed: bad credentials: {}", ex.getMessage(),
                ex);
        throw ex;
    } catch (Exception ex) {
        LOGGER.error("Can't authenticate user '{}': {}",
                new Object[] { authentication.getPrincipal(), ex.getMessage(), ex });
        throw new AuthenticationServiceException("web.security.provider.unavailable");
    }

    LOGGER.debug("User '{}' authenticated ({}), authorities: {}", new Object[] { authentication.getPrincipal(),
            authentication.getClass().getSimpleName(), principal.getAuthorities() });
    return token;
}

From source file:eu.supersede.fe.security.SecurityConfiguration.java

@Bean
AuthenticationProvider customAuthenticationProvider() {
    return new AuthenticationProvider() {
        private final Logger log = LoggerFactory.getLogger(this.getClass());

        @Override/*from w w w  .ja va  2s.  co m*/
        @Transactional
        public Authentication authenticate(Authentication auth) throws AuthenticationException {
            String username = (String) auth.getPrincipal();
            String password = (String) auth.getCredentials();

            ServletRequestAttributes attr = (ServletRequestAttributes) RequestContextHolder
                    .currentRequestAttributes();
            HttpServletRequest req = attr.getRequest();
            String tenantId = req.getHeader("TenantId");

            if (tenantId == null) {
                log.error("Tenant provided");
                throw new BadCredentialsException("Invalid login request: missing tenant");
            }

            AuthorizationToken token = getAuthToken(username, password, tenantId);
            User user = users.findByUsername(username);

            if (user == null) {
                log.error("Username not found in Database");
                throw new BadCredentialsException("Invalid login request: user " + username + " not found");
            }

            // get authorities from profiles
            List<Profile> profiles = user.getProfiles();
            String[] authorities = new String[profiles.size()];

            for (int i = 0; i < profiles.size(); i++) {
                authorities[i] = "ROLE_" + profiles.get(i).getName();
            }

            log.debug("User has " + authorities.length + " authorities");

            List<GrantedAuthority> permissions = AuthorityUtils.createAuthorityList(authorities);
            DatabaseUser dbUser = new DatabaseUser(user.getUserId(),
                    user.getFirstName() + " " + user.getLastName(), user.getEmail(), password, token, true,
                    true, true, true, permissions, user.getLocale());

            return new UsernamePasswordAuthenticationToken(dbUser, password, permissions);// AUTHORITIES
        }

        private AuthorizationToken getAuthToken(String username, String password, String tenantId) {
            AuthorizationToken token = null;

            if (AUTH_MANAGER_ENABLED) {
                try {
                    token = proxy.getIFAuthenticationManager(tenantId).getAuthorizationToken(username, password,
                            tenantId);
                } catch (HttpClientErrorException e) {
                    log.error("Invalid username and password.");
                } catch (NullPointerException e1) {
                    log.error("Authorization token is null, check your if.properties file in the conf/ folder");
                } catch (Exception e2) {
                    e2.printStackTrace();
                }

                if (token == null || token.getAccessToken() == null) {
                    log.error("Supersede integration token is null");
                    throw new BadCredentialsException(
                            "Invalid login request: authentication manager token is null");
                }
            } else {
                log.warn("IF Authentication Manager disable, user token is NULL");
            }

            return token;
        }

        @Override
        @SuppressWarnings("rawtypes")
        public boolean supports(Class authentication) {
            return (UsernamePasswordAuthenticationToken.class.isAssignableFrom(authentication));
        }
    };
}

From source file:org.artifactory.ui.rest.service.admin.security.auth.login.LoginService.java

/**
 * @return True is anonymous user is logged in to this session.
 *//*  ww  w  . j  ava  2  s .  co  m*/
boolean isAnonymous(Authentication authentication) {
    return authentication != null && UserInfo.ANONYMOUS.equals(authentication.getPrincipal().toString());
}

From source file:com.erudika.para.security.OpenIDAuthFilter.java

/**
 * Handles an authentication request.//ww w.ja  va2s .  c  o  m
 * @param request HTTP request
 * @param response HTTP response
 * @return an authentication object that contains the principal object if successful.
 * @throws IOException ex
 */
@Override
public Authentication attemptAuthentication(HttpServletRequest request, HttpServletResponse response)
        throws IOException {
    final String requestURI = request.getRequestURI();
    Authentication userAuth = null;
    User user = null;

    if (requestURI.endsWith(OPENID_ACTION)) {
        Authentication oidAuth = super.attemptAuthentication(request, response);

        if (oidAuth == null) {
            // hang on... redirecting to openid provider
            return null;
        } else {
            //success!
            user = (User) oidAuth.getPrincipal();
            userAuth = new UserAuthentication(user);
        }
    }

    if (userAuth == null || user == null || user.getIdentifier() == null) {
        throw new BadCredentialsException("Bad credentials.");
    } else if (!user.isEnabled()) {
        throw new LockedException("Account is locked.");
    }
    return userAuth;
}

From source file:com.safasoft.treeweb.auth.CustomAuthenticationSuccessHandler.java

@Override
public void onAuthenticationSuccess(HttpServletRequest request, HttpServletResponse response,
        Authentication auth) throws IOException, ServletException {
    //login info//ww  w .  j  av a  2s  .  co  m
    HttpSession session = request.getSession();
    String cnname = (String) session.getAttribute("cnname");
    if (cnname == null || cnname.equals("")) {
        try {
            String principal = auth.getPrincipal().toString();
            int start = principal.indexOf("cn=");
            String tmp = principal.substring(start + 3);
            int end = tmp.indexOf(",");
            cnname = tmp.substring(0, end);
            session.setAttribute("cnname", cnname);
            session.setAttribute("uid", auth.getName());
            session.setAttribute("sessionid", session.getId());
        } catch (Exception ex) {
            authLogger.error(ex);
        }
    }
    //logging login
    FfLogFocus logFocus = new FfLogFocus();
    logFocus.setUserName(auth.getName());
    DataConverter dc = new DataConverter();
    dc.setConverter(new Date(), "dd-MMM-yyyy kk:mm:ss");
    logFocus.setLoginTime(dc.getConverter());
    FfLogFocus logFocusSave = new SessionUtil<FfLogFocusService>().getAppContext("ffLogFocusService")
            .save(logFocus);
    session.setAttribute("logParentId", logFocusSave.getId());
    //redirect
    setDefaultTargetUrl("/apps/main/home");
    super.onAuthenticationSuccess(request, response, auth);
}

From source file:Controller.UsuarioBean.java

public void pegarUsuarioSpringer() {
    usuario = new Usuario();
    SecurityContext context = SecurityContextHolder.getContext();
    if (context instanceof SecurityContext) {
        Authentication authentication = context.getAuthentication();
        if (authentication instanceof Authentication) {

            try {
                System.out//from  www . jav  a  2  s .com
                        .println("Teste de usurio: " + ((User) authentication.getPrincipal()).getUsername());
                usuario = UsuarioDAO.getInstance()
                        .buscarDadosUsuario(((User) authentication.getPrincipal()).getUsername());

            } catch (Exception ex) {
                Logger.getLogger(UsuarioBean.class.getName()).log(Level.SEVERE, null, ex);
            }
        }
    }
}

From source file:at.ac.univie.isc.asio.security.HttpMethodRestrictionFilter.java

/**
 * Copy the original authentication, but use the restricted set of authorities. Keep special token
 * classes, like Anonymous, RememberMe, etc. .
 *///from  w  w  w  .java  2s  . co m
private AbstractAuthenticationToken copy(final Authentication authentication,
        final Set<GrantedAuthority> restricted) {
    final AbstractAuthenticationToken replacement;
    if (authentication instanceof AnonymousAuthenticationToken) {
        replacement = new AnonymousAuthenticationToken("dummy-key", authentication.getPrincipal(), restricted);
    } else if (authentication instanceof RememberMeAuthenticationToken) {
        replacement = new RememberMeAuthenticationToken("dummy-key", authentication.getPrincipal(), restricted);
    } else if (authentication instanceof PreAuthenticatedAuthenticationToken) {
        replacement = new PreAuthenticatedAuthenticationToken(authentication.getPrincipal(),
                authentication.getCredentials(), restricted);
    } else {
        replacement = new UsernamePasswordAuthenticationToken(authentication.getPrincipal(),
                authentication.getCredentials(), restricted);
    }
    return replacement;
}