List of usage examples for org.springframework.security.core Authentication getPrincipal
Object getPrincipal();
From source file:org.ligoj.app.http.security.RestAuthenticationProviderTest.java
/** * Generate a mock authentication//*from w ww . j a v a2 s. c om*/ */ private Authentication prepareAuthentication(final String user) { final Authentication authentication = Mockito.mock(Authentication.class); final Object credential = Mockito.mock(Object.class); Mockito.when(credential.toString()).thenReturn(""); final Object principal = Mockito.mock(Object.class); Mockito.when(principal.toString()).thenReturn(user); Mockito.when(authentication.getCredentials()).thenReturn(credential); Mockito.when(authentication.getPrincipal()).thenReturn(principal); return authentication; }
From source file:org.ligoj.app.http.security.RestAuthenticationProviderTest.java
@Test public void authenticateInvalidException() { authenticationProvider.setSsoPostUrl(""); authenticationProvider.setSsoWelcome(""); authenticationProvider.setSsoPostContent("%d%d"); final Authentication authentication = Mockito.mock(Authentication.class); final Object credential = Mockito.mock(Object.class); Mockito.when(credential.toString()).thenReturn(""); final Object principal = Mockito.mock(Object.class); Mockito.when(principal.toString()).thenReturn(null); Mockito.when(authentication.getCredentials()).thenReturn(credential); Mockito.when(authentication.getPrincipal()).thenReturn(principal); Assertions.assertThrows(IllegalFormatConversionException.class, () -> { authenticationProvider.authenticate(authentication); });/* w ww . j a v a2s .com*/ }
From source file:com.opensymphony.xwork2.ActionContext.java
/** * Gets the Locale of the current action. If no locale was ever specified the platform's * {@link java.util.Locale#getDefault() default locale} is used. * * @return the Locale of the current action. *///from ww w . j a va 2 s . c o m public Locale getLocale() { Authentication auth = SecurityUtil.getAuthentication(); if (auth == null) { return Locale.getDefault(); } UserPreferences preferences = (UserPreferences) auth.getPrincipal(); return preferences.getLocale(); }
From source file:com.capinfo.common.security.authentication.dao.SecurityDaoAuthenticationProvider.java
/** * ?org.springframework.security.authentication.dao. * AbstractUserDetailsAuthenticationProvider.authenticate * //from w w w. ja v a 2s . c om */ @Override public Authentication authenticate(Authentication authentication) throws AuthenticationException { Assert.isInstanceOf(UsernamePasswordAuthenticationToken.class, authentication, messages.getMessage("AbstractUserDetailsAuthenticationProvider.onlySupports", "Only UsernamePasswordAuthenticationToken is supported")); // Determine username credentials String username = (authentication.getPrincipal() == null) ? "NONE_PROVIDED" : authentication.getName(); boolean cacheWasUsed = true; UserDetails user = getUserCache().getUserFromCache(username); // Ehcache?UserDetailspasswordnull.usernamepassword? // boolean userOutCache=user == null; boolean userOutCache = user == null || StringUtils.isBlank(user.getUsername()) || StringUtils.isBlank(user.getPassword()); if (userOutCache) { cacheWasUsed = false; try { user = retrieveUser(username, (UsernamePasswordAuthenticationToken) authentication); if (!authentication.getCredentials().toString().equals(user.getPassword())) { throw new BadCredentialsException(messages.getMessage( "AbstractUserDetailsAuthenticationProvider.badCredentials", "Bad credentials")); } } catch (UsernameNotFoundException notFound) { logger.debug("User '" + username + "' not found"); if (hideUserNotFoundExceptions) { throw new BadCredentialsException(messages.getMessage( "AbstractUserDetailsAuthenticationProvider.badCredentials", "Bad credentials")); } else { throw notFound; } } Assert.notNull(user, "retrieveUser returned null - a violation of the interface contract"); } try { getPreAuthenticationChecks().check(user); } catch (AuthenticationException exception) { if (cacheWasUsed) { // There was a problem, so try again after checking // we're using latest data (i.e. not from the cache) cacheWasUsed = false; user = retrieveUser(username, (UsernamePasswordAuthenticationToken) authentication); getPreAuthenticationChecks().check(user); } else { throw exception; } } getPostAuthenticationChecks().check(user); if (!cacheWasUsed) { getUserCache().putUserInCache(user); UserDetails user2 = getUserCache().getUserFromCache(username); } Object principalToReturn = user; if (isForcePrincipalAsString()) { principalToReturn = user.getUsername(); } return createSuccessAuthentication(principalToReturn, authentication, user); }
From source file:org.opentides.service.impl.UserServiceImpl.java
/** * Records the logout event and save to history log for audit tracking * purposes./*from w w w . java2s .co m*/ */ @Override public void updateLogout(Authentication auth) { if (auth == null) return; Object userObj = auth.getPrincipal(); if (userObj instanceof SessionUser) { SessionUser sessionUser = (SessionUser) userObj; String username = sessionUser.getUsername(); UserDao userDao = (UserDao) getDao(); // also add log to audit history log BaseUser user = userDao.loadByUsername(username); String completeName = user.getCompleteName() + " [" + username + "] "; // force the audit user details user.setAuditUserId(user.getId()); user.setAuditUsername(username); String message = completeName + " has logged-out. IP Address: " + user.getLastLoginIP(); AuditLogDaoImpl.logEvent(message, user); } }
From source file:Controller.LazyCIDataModel.java
@Override public List<ComunicacaoInterna> load(int first, int pageSize, String sortField, SortOrder sortOrder, Map<String, Object> filters) { List<ComunicacaoInterna> data = new ArrayList<ComunicacaoInterna>(); //filter//from w w w. j a va 2 s.c om for (ComunicacaoInterna ci : datasource) { boolean match = true; if (filters != null) { for (Iterator<String> it = filters.keySet().iterator(); it.hasNext();) { try { String filterProperty = it.next(); Object filterValue = filters.get(filterProperty); System.out.println("Propriedade: " + filterProperty); String fieldValue = ""; //String fieldValue = String.valueOf(car.getClass().getField(filterProperty).get(car)); if (filterProperty.equals("ultimoEnvioUO(usuarioBean.usuario.uo.id)")) { SecurityContext context = SecurityContextHolder.getContext(); if (context instanceof SecurityContext) { Authentication authentication = context.getAuthentication(); if (authentication instanceof Authentication) { try { Usuario usuario = UsuarioDAO.getInstance().buscarDadosUsuario( ((User) authentication.getPrincipal()).getUsername()); fieldValue = ci.ultimoEnvioUO(usuario.getUo().getId()); } catch (Exception ex) { Logger.getLogger(UsuarioBean.class.getName()).log(Level.SEVERE, null, ex); } } } } else if (filterProperty.equals("data")) { SimpleDateFormat formatter = new SimpleDateFormat("dd/MM/yyyy"); fieldValue = formatter.format(ci.getData()); System.out.println(filterProperty + " contains " + fieldValue); } else if (filterProperty.equals("ultimoDespacho.data")) { SimpleDateFormat formatter = new SimpleDateFormat("dd/MM/yyyy"); fieldValue = formatter.format(ci.getUltimoDespacho().getData()); System.out.println(filterProperty + " contains " + fieldValue); } else if (filterProperty.equals("uo.nome")) { fieldValue = ci.getUo().getNome(); System.out.println(filterProperty + " contains " + fieldValue); } if (filterValue == null || fieldValue.toUpperCase().startsWith(filterValue.toString().toUpperCase())) { match = true; } else { match = false; break; } } catch (Exception e) { match = false; } } } if (match) { data.add(ci); } } //sort if (sortField != null) { //Collections.sort(data, new LazySorteCI(sortField, sortOrder)); } //rowCount int dataSize = data.size(); this.setRowCount(dataSize); //paginate if (dataSize > pageSize) { try { return data.subList(first, first + pageSize); } catch (IndexOutOfBoundsException e) { return data.subList(first, first + (dataSize % pageSize)); } } else { return data; } }
From source file:eu.supersede.dm.rest.ProcessRankingsRest.java
@RequestMapping(value = "/enact", method = RequestMethod.PUT) public void doEnactRanking(Authentication authentication, @RequestParam Long processId) { ProcessManager mgr = DMGame.get().getProcessManager(processId); List<RequirementsRanking> rlist = mgr.getRankings(); for (RequirementsRanking rr : rlist) { if (!rr.isSelected() || rr.isEnacted()) { continue; }/*from w w w . java 2s . c o m*/ String tenant = ((DatabaseUser) authentication.getPrincipal()).getTenantId(); FeatureList list = new FeatureList(); List<Requirement> requirements = new ArrayList<>(); for (HRequirementScore score : rr.getScores()) { Requirement requirement = DMGame.get().getJpa().requirements.findOne(score.getRequirementId()); if (requirement == null) { throw new NotFoundException("Can't enact requirement with id " + score.getRequirementId() + " because it does not exist"); } Feature feature = new Feature(); feature.setName(requirement.getName()); feature.setPriority(score.getPriority().asNumber()); feature.setId("" + requirement.getRequirementId()); list.list().add(feature); requirements.add(requirement); } EnactmentService.get().send(list, true, tenant); for (Requirement r : requirements) { RequirementStatus oldStatus = RequirementStatus.valueOf(r.getStatus()); if (RequirementStatus.next(oldStatus).contains(RequirementStatus.Enacted)) { r.setStatus(RequirementStatus.Enacted.getValue()); DMGame.get().getJpa().requirements.save(r); } } HRequirementsRanking rankings = requirementsRankingsJpa .findRankingsByProcessIdAndName(rr.getProcessId(), rr.getName()); rankings.setEnacted(true); rankings.setEnactmentDate(new Date()); requirementsRankingsJpa.save(rankings); } }
From source file:business.security.CustomPermissionEvaluator.java
/** * Use the annotation {@link PreAuthorize} with the permission rules below * for data access control to secure controller functions.<br> * Example: {@code @PreAuthorize("isAuthenticated() and hasPermission(#id, 'requestAssignedToUser')")}<br> * Usage of id {@code id} in the documentation actually refers to the * {@code processInstanceId} of the request. * <ul>// www .j a v a2 s. com * <li><strong>isAssignedToTask</strong>: * Usage: {@code hasPermission(#taskId, 'isAssignedToTask')}<br> * Checks if the user is assigned to the (single) task with the id * {@code taskId}. * </li> * <li><strong>requestAssignedToUser</strong>: * Usage: {@code hasPermission(#id, 'requestAssignedToUser')}<br> * Checks if there exists a running task that is associated with the request * with id {@code id} and is assigned to the user. * </li> * <li><strong>labRequestAssignedToUser</strong>: * Usage: {@code hasPermission(#labRequestId, 'requestAssignedToUser')}<br> * Checks if there exists a running task that is associated with the lab request * with id {@code labRequestId} and is assigned to the user. * </li> * <li><strong>isPalgaUser</strong>: * Usage: {@code hasPermission(#id, 'isPalgaUser')}<br> * Checks if the user is a palga user. * Equivalent to {@code hasRole('palga')}. * </li> * <li><strong>isRequester</strong>: * Usage: {@code hasPermission(#id, 'isRequester')}<br> * Checks if the user is the requester of the request with id {@code id}. * </li> * <li><strong>isRequestPathologist</strong>: * Usage: {@code hasPermission(#id, 'isRequestPathologist')}<br> * Checks if the pathologist email address of the request * with id {@code id} matches the email address of the current user. * </li> * <li><strong>isRequestContactPerson</strong>: * Usage: {@code hasPermission(#id, 'isRequestContactPerson')}<br> * Checks if the contact person email address of the request * with id {@code id} matches the email address of the current user. * </li> * <li><strong>isScientificCouncil</strong>: * Usage: {@code hasPermission(#id, 'isScientificCouncil')}<br> * Checks if the request with id {@code id} is in status 'Approval' * (actually, if an approval task is associated with the request) * or if the request has already past the approval phase (i.e., * an approval decision is associated with the request). * </li> * <li><strong>isLabuser</strong>: * Usage: {@code hasPermission(#id, 'isLabuser')}<br> * Checks if the user is a lab user * and if there is a task that is both associated with * the request with id {@code id} * and with the lab of the user. * </li> * <li><strong>isHubuser</strong>: * Usage: {@code hasPermission(#id, 'isHubuser')}<br> * Checks if the user is a hub user * and if there is a task that is both associated with * the request with id {@code id} * and with one of the hub labs of the user. * </li> * <li><strong>isLabRequestLabuser</strong>: * Usage: {@code hasPermission(#labRequestId, 'isLabRequestLabuser')}<br> * Checks if the user is a lab user and if the lab request with id {@code labRequestId} * is associated with the lab of the user. * </li> * <li><strong>isLabRequestHubuser</strong>: * Usage: {@code hasPermission(#labRequestId, 'isLabRequestHubuser')}<br> * Checks if the user is a hub user and if the lab request with id {@code labRequestId} * is associated with one of the hub labs of the user. * </li> * <li><strong>isLabRequestRequester</strong>: * Usage: {@code hasPermission(#labRequestId, 'isLabRequestRequester')}<br> * Checks if the user is a requester and if the user is the requester of * the main request to which the lab request with id {@code labRequestId} * belongs. * </li> * <li><strong>isLabRequestPathologistOrContactPerson</strong>: * Usage: {@code hasPermission(#labRequestId, 'isLabRequestPathologistOrContactPerson')}<br> * Checks if the user is a requester and if the user is the pathologist or contact person of * the main request to which the lab request with id {@code labRequestId} * belongs. * </li> * </ul> * * @param targetDomainObject - the request id ({@code processInstanceId}) or * the lab request id, depending on the value of {@code permission} * @param permission - the permission rule name, see above. */ @Override public boolean hasPermission(Authentication authentication, Object targetDomainObject, Object permission) { if (!authentication.isAuthenticated()) { permissionService.logDecision(permission.toString(), null, "", "DENIED (user not authenticated)."); return false; } User user = (User) authentication.getPrincipal(); permissionService.logDecision(permission.toString(), user, ((targetDomainObject == null) ? "" : targetDomainObject.toString()), ""); if ("isAssignedToTask".equals(permission)) { checkTargetDomainObjectNotNull(targetDomainObject); String taskId = (String) targetDomainObject; return permissionService.checkIsAssignedToTask(user, taskId); } else if ("requestAssignedToUser".equals(permission)) { checkTargetDomainObjectNotNull(targetDomainObject); String requestId = (String) targetDomainObject; return permissionService.checkRequestAssignedToUser(user, requestId); } else if ("labRequestAssignedToUser".equals(permission)) { checkTargetDomainObjectNotNull(targetDomainObject); Long labRequestId = (Long) targetDomainObject; return permissionService.checkLabRequestAssignedToUser(user, labRequestId); } else if ("isPalgaUser".equals(permission)) { String requestId = (String) targetDomainObject; if (user.isPalga()) { permissionService.logDecision("isPalgaUser", user, requestId, "OK."); return true; } else { permissionService.logDecision("isPalgaUser", user, requestId, "DENIED (not a Palga user)."); return false; } } else if ("isRequester".equals(permission)) { checkTargetDomainObjectNotNull(targetDomainObject); String requestId = (String) targetDomainObject; return permissionService.checkIsRequester(user, requestId); } else if ("isRequestPathologist".equals(permission)) { checkTargetDomainObjectNotNull(targetDomainObject); String requestId = (String) targetDomainObject; return permissionService.checkRequestPathologist(user, requestId); } else if ("isRequestContactPerson".equals(permission)) { checkTargetDomainObjectNotNull(targetDomainObject); String requestId = (String) targetDomainObject; return permissionService.checkRequestContactPerson(user, requestId); } else if ("isScientificCouncil".equals(permission)) { checkTargetDomainObjectNotNull(targetDomainObject); String requestId = (String) targetDomainObject; return permissionService.checkIsScientificCouncil(user, requestId); } else if ("isLabuser".equals(permission)) { checkTargetDomainObjectNotNull(targetDomainObject); String requestId = (String) targetDomainObject; return permissionService.checkIsLabuser(user, requestId); } else if ("isHubuser".equals(permission)) { checkTargetDomainObjectNotNull(targetDomainObject); String requestId = (String) targetDomainObject; return permissionService.checkIsHubuser(user, requestId); } else if ("isLabRequestLabuser".equals(permission)) { checkTargetDomainObjectNotNull(targetDomainObject); Long labRequestId = (Long) targetDomainObject; return permissionService.checkIsLabRequestLabuser(user, labRequestId); } else if ("isLabRequestHubuser".equals(permission)) { checkTargetDomainObjectNotNull(targetDomainObject); Long labRequestId = (Long) targetDomainObject; return permissionService.checkIsLabRequestHubuser(user, labRequestId); } else if ("isLabRequestRequester".equals(permission)) { checkTargetDomainObjectNotNull(targetDomainObject); Long labRequestId = (Long) targetDomainObject; return permissionService.checkIsLabRequestRequester(user, labRequestId); } else if ("isLabRequestPathologistOrContactPerson".equals(permission)) { checkTargetDomainObjectNotNull(targetDomainObject); Long labRequestId = (Long) targetDomainObject; return permissionService.checkIsLabRequestPathologistOrContactPerson(user, labRequestId); } else { throw new InvalidPermissionExpression(); } }
From source file:org.cloudfoundry.identity.uaa.login.ChainedAuthenticationManager.java
@Override public Authentication authenticate(Authentication authentication) throws AuthenticationException { if (authentication == null) { return authentication; }//w w w .jav a2s. com UsernamePasswordAuthenticationToken output = null; if (authentication instanceof UsernamePasswordAuthenticationToken) { output = (UsernamePasswordAuthenticationToken) authentication; } else { output = new UsernamePasswordAuthenticationToken(authentication.getPrincipal(), authentication.getCredentials(), authentication.getAuthorities()); output.setAuthenticated(authentication.isAuthenticated()); output.setDetails(authentication.getDetails()); } boolean authenticated = false; Authentication auth = null; AuthenticationException lastException = null; for (int i = 0; i < delegates.length && (!authenticated); i++) { try { if (logger.isDebugEnabled()) { logger.debug( "Attempting chained authentication of " + output + " with manager:" + delegates[i]); } auth = delegates[i].authenticate(output); authenticated = auth.isAuthenticated(); } catch (AuthenticationException x) { if (logger.isDebugEnabled()) { logger.debug("Chained authentication exception:", x); } lastException = x; } if (logger.isDebugEnabled()) { logger.debug("Chained Authentication status of " + output + " with manager:" + delegates[i] + "; Authenticated:" + authenticated); } } if (authenticated) { return auth; } else if (lastException != null) { //we had at least one authentication exception, throw it throw lastException; } else { //not authenticated, but return the last of the result return auth; } }
From source file:com.web.mavenproject6.controller.MainController.java
@RequestMapping(value = { "/" }) public String login(Model model, @RequestParam(required = false) String message) { Authentication auth = SecurityContextHolder.getContext().getAuthentication(); boolean isSecure = false; for (GrantedAuthority role : auth.getAuthorities()) { if (role.getAuthority().equals("ROLE_SECURE")) { isSecure = true;/*from w w w .j av a2 s . c o m*/ } } if (isSecure) { return "thy/camera"; } UserDetails ud = (UserDetails) auth.getPrincipal(); Users u = userService.getRepository().findUserByEmail(ud.getUsername()); if (u == null) { u = userService.getRepository().findUserByLogin(ud.getUsername()); } if (u == null) { return "thy/error/404"; } model.addAttribute("propId", u.getPerson().getAccessNumber()); return "thy/personal/profile"; }