List of usage examples for org.springframework.security.core Authentication getName
public String getName();
From source file:software.coolstuff.springframework.owncloud.service.impl.rest.OwncloudRestResourceServiceImpl.java
protected Sardine getSardine() throws OwncloudSardineCacheException { Authentication authentication = SecurityContextHolder.getContext().getAuthentication(); String username = authentication.getName(); try {/*from ww w . ja v a 2 s.c o m*/ log.debug("Get the Sardine Implementation of User {}", username); return sardineCache.get(username); } catch (Exception e) { val logMessage = String.format( "Cannot get the Sardine Implementation based by User %s from the Sardine Cache", username); log.error(logMessage, e); throw new OwncloudSardineCacheException(logMessage, e); } }
From source file:de.iteratec.iteraplan.presentation.UserContextInitializationServiceImpl.java
/** * Stores the user's login name and the user's roles to the session. The stored information is * used in {@link de.iteratec.iteraplan.presentation.dialogs.Start.InitCommand} to create the * {@link UserContext} object./*from w ww . j av a 2 s. c om*/ * * Retrieves all information about the logged-in user from the iteraplan database, creates the * {@link UserContext} filled with the respective values of the logged-in user and stores the * context in the global memory. Also checks, if the user's password has expired. If the user * context already exists, nothing is done. * * @return An error message key or null if everything was successful. */ private String createAndStoreUserContext(HttpServletRequest req, Authentication authentication) { HttpSession session = req.getSession(); String userLogin = StringUtils.trim(authentication.getName()); session.setAttribute(LOGGED_IN_USER_LOGIN, userLogin); // Make sure that the MASTER data source is used upon login. The user's context stored in the // thread local of the UserContext is not null, if the user has already logged into iteraplan // previously and the server has not been restarted since. Note that though the session has // been invalidated on logout (see Spring Security configuration), but the UserContext is still // there. // Thus the reference to the data source that the user connects to must be explicitly set to // the MASTER data source. Otherwise the data source stored in the context is used, but the // according database does usually not contain all the data necessary for a successful login // (e.g. the role for the demo access to iteraplan). if (UserContext.getCurrentUserContext() != null) { LOGGER.info("Point the user to the MASTER data source."); UserContext.getCurrentUserContext().setDataSource(Constants.MASTER_DATA_SOURCE); } final Set<String> userRoles = getUserRoles(authentication); session.setAttribute(LOGGED_IN_USER_ROLES, userRoles); User user = userService.getUserByLoginIfExists(userLogin); final Set<Role> roles = loadRoles(userRoles); Locale locale = RequestContextUtils.getLocale(req); // Create and store user context. UserContext userContext = new UserContext(userLogin, roles, locale, user); UserContext.setCurrentUserContext(userContext); session.setAttribute(SessionConstants.USER_CONTEXT, userContext); LOGGER.debug("User context created and stored in user's session."); LOGIN_LOGGER.info(userContext.toCSVString()); if (user == null) { user = userService.createUser(userLogin); // Create and store user context. // the new user can only be created after the user context is set (above) // as the update of an entity triggers the LastModificationInterceptor, which // expects an already set user context userContext = new UserContext(userLogin, roles, locale, user); UserContext.detachCurrentUserContext(); UserContext.setCurrentUserContext(userContext); session.setAttribute(SessionConstants.USER_CONTEXT, userContext); } readLdapData(authentication.getPrincipal(), user); if (roles != null && !roles.isEmpty() && !(roles.containsAll(user.getRoles()) && user.getRoles().containsAll(roles))) { user.clearRoles(); for (Role role : roles) { user.addRoleTwoWay(role); } userService.saveOrUpdate(user); } final String errorMessageKey = createDataSource(userContext); if (errorMessageKey != null) { return errorMessageKey; } LOGGER.info("User has logged in."); // notify ElasticeamService (bean), that the metamodel and model for the 'new' datasource needs to be loaded elasticService.initOrReload(); //Create elasticMiContext ElasticMiContext elasticMiContext = elasticMiContextAndStakeholderManagerInitializationService .initializeMiContextAndStakeholderManager(userLogin, userContext.getDataSource()); session.setAttribute(SessionConstants.ELASTIC_MI_CONTEXT, elasticMiContext); return null; }
From source file:software.coolstuff.springframework.owncloud.service.impl.rest.OwncloudRestResourceServiceImpl.java
@Override public OwncloudQuota getQuota() { Authentication authentication = SecurityContextHolder.getContext().getAuthentication(); return userService.getQuota(authentication.getName()); }
From source file:org.snippr.web.controllers.SnippetCRUDController.java
/** * Returns the list of all Labels from the database for the logged user * @return Set<Snippet>/*from ww w . j a v a 2 s . c om*/ * @throws InstanceNotFoundException */ public Set<org.snippr.business.entities.Label> getLabels() { Authentication auth = SecurityUtil.getAuthentication(); String username = auth.getName(); try { userModel.prepareForEdit(username); } catch (InstanceNotFoundException e) { e.printStackTrace(); } return userModel.getLabels(); }
From source file:cherry.sqlman.tool.search.SqlSearchControllerImpl.java
@Override public ModelAndView execute(SqlSearchForm form, BindingResult binding, Authentication auth, Locale locale, SitePreference sitePref, NativeWebRequest request) { if (hasErrors(form, binding)) { return withViewname(viewnameOfStart).build(); }/*from ww w .ja v a 2 s .c o m*/ if (form.getPno() <= 0L) { form.setPno(0L); } if (form.getPsz() <= 0L) { form.setPsz(config.getPaginatorDefaultPageSize()); } PagedList<Map<String, ?>> result = searchService.search(form, auth.getName()); return withViewname(viewnameOfStart).addObject(result).build(); }
From source file:de.uni_koeln.spinfo.maalr.login.PostLoginHandler.java
@Override public void onAuthenticationSuccess(HttpServletRequest request, HttpServletResponse response, Authentication authentication) throws IOException, ServletException { String dictContext = Configuration.getInstance().getDictContext(); // Set Session Timeout to one hour request.getSession().setMaxInactiveInterval(60 * 60); if (authentication != null && authentication instanceof JaasAuthenticationToken) { // TODO: Implement something similar for ldap... request.getSession().setAttribute("uname", authentication.getName()); }//w w w . j av a 2 s . com if (authentication != null && authentication instanceof OpenIDAuthenticationToken) { // TODO: Optimize this - inefficient to query for each request... MaalrUserInfo userInfo = backend.getByLogin(authentication.getName()); if (userInfo == null) { OpenIDAuthenticationToken token = (OpenIDAuthenticationToken) SecurityContextHolder.getContext() .getAuthentication(); List<OpenIDAttribute> attributes = token.getAttributes(); userInfo = new MaalrUserInfo(authentication.getName(), Role.OPENID_2); for (OpenIDAttribute openIDAttribute : attributes) { if (openIDAttribute.getValues() != null && openIDAttribute.getValues().size() > 0) { if ("axContactEmail".equals(openIDAttribute.getName()) && userInfo.getEmail() == null) { userInfo.setEmail(openIDAttribute.getValues().get(0)); } if ("oiContactEmail".equals(openIDAttribute.getName()) && userInfo.getEmail() == null) { userInfo.setEmail(openIDAttribute.getValues().get(0)); } if ("axNamePersonFirstName".equals(openIDAttribute.getName()) && userInfo.getFirstname() == null) { userInfo.setFirstname(openIDAttribute.getValues().get(0)); } if ("axNamePersonLastName".equals(openIDAttribute.getName()) && userInfo.getLastname() == null) { userInfo.setLastname(openIDAttribute.getValues().get(0)); } } } try { backend.insert(userInfo); } catch (InvalidUserException e) { e.printStackTrace(); } } request.getSession().setAttribute("uname", userInfo.getFirstname()); } if (authentication != null) { Set<String> roles = AuthorityUtils.authorityListToSet(authentication.getAuthorities()); if (roles.contains(Constants.Roles.ADMIN_5)) { response.sendRedirect(dictContext + "/admin/admin.html"); return; } else if (roles.contains(Constants.Roles.TRUSTED_IN_4)) { response.sendRedirect(dictContext + "/editor/editor.html"); return; } } response.sendRedirect(dictContext + "/index.html"); }
From source file:co.com.carpco.altablero.spring.web.controller.ClassRoomController.java
@RequestMapping(value = "/admin/cursos", method = { RequestMethod.GET, RequestMethod.POST }) public ModelAndView classRoomPage(@RequestParam(value = "year", required = false) String year, @RequestParam(value = "grade", required = false) String grade) { Authentication auth = SecurityContextHolder.getContext().getAuthentication(); if (!(auth instanceof AnonymousAuthenticationToken)) { if (year == null || year.isEmpty()) { Calendar date = Calendar.getInstance(); year = String.valueOf(date.get(Calendar.YEAR)); }/*from www . j a v a 2 s .co m*/ if (grade == null) { grade = "0"; } ModelAndView model = roleUtils.createModelWithUserDetails(auth.getName()); UserBO user = userBll.getUserByDocumentNumber(auth.getName()); Set<ClassRoomBO> classRoomBOSet = classRoomBll.getClassRoomSet(user.getSchool().getId(), year, grade); List<GradeBO> gradeList = new ArrayList<>(gradeBll.getGradeSet()); List<YearBO> yearList = new ArrayList<>(yearBll.getYearSet()); Collections.sort(gradeList); Collections.sort(yearList); model.addObject("classrooms", classRoomBOSet); model.addObject("years", yearList); model.addObject("grades", gradeList); model.setViewName("admin/classroom/list"); return model; } else { return new ModelAndView("redirect:/login"); } }
From source file:fr.gael.dhus.spring.security.authentication.DefaultAuthenticationProvider.java
@Override @Transactional(propagation = Propagation.REQUIRED) public Authentication authenticate(Authentication authentication) throws AuthenticationException { String username = (String) authentication.getPrincipal(); String password = (String) authentication.getCredentials(); String ip = "unknown"; if (authentication.getDetails() instanceof WebAuthenticationDetails) { ip = ((WebAuthenticationDetails) authentication.getDetails()).getRemoteAddress(); }/*from w w w . j a v a2s.c om*/ LOGGER.info("Connection attempted by '" + authentication.getName() + "' from " + ip); arwDao.loginStart(username); User user = userService.getUserNoCheck(username); if (user == null || user.isDeleted()) { throw new BadCredentialsException(errorMessage); } PasswordEncryption encryption = user.getPasswordEncryption(); if (!encryption.equals(PasswordEncryption.NONE)) { MessageDigest md; try { md = MessageDigest.getInstance(encryption.getAlgorithmKey()); password = new String(Hex.encode(md.digest(password.getBytes("UTF-8")))); } catch (NoSuchAlgorithmException | UnsupportedEncodingException e) { arwDao.loginEnd(user, false); throw new BadCredentialsException("Authentication process failed", e); } } if (!user.getPassword().equals(password)) { LOGGER.warn(new Message(MessageType.USER, "Connection refused for '" + username + "' from " + ip + " : error in login/password combination")); arwDao.loginEnd(user, false); throw new BadCredentialsException(errorMessage); } for (AccessRestriction restriction : user.getRestrictions()) { LOGGER.warn("Connection refused for '" + username + "' from " + ip + " : account is locked (" + restriction.getBlockingReason() + ")"); arwDao.loginEnd(user, false); throw new LockedException(restriction.getBlockingReason()); } LOGGER.info("Connection success for '" + username + "' from " + ip); arwDao.loginEnd(user, true); return new ValidityAuthentication(user, user.getAuthorities()); }
From source file:ru.efo.security.ADUserDetailsService.java
@Override public Authentication authenticate(Authentication authentication) throws AuthenticationException { final String username = authentication.getName(); final String password = authentication.getCredentials().toString(); logger.log(Level.FINE, "Performing logon into '" + ldapUrl + "' with credentials '" + username + "'/'" + password.replaceAll(".", "*") + "'"); DirContext context = null;/*from ww w . java2 s .c o m*/ try { context = getDirContext(username + userSuffix, password); logger.log(Level.FINE, "User '" + username + "' has been successfully logged on"); final ADUserDetails details = loadUserByUsername(context, username, password); return new UsernamePasswordAuthenticationToken(details, password, details.getAuthorities()); } catch (NamingException ex) { logger.log(Level.SEVERE, "Could not login into '" + ldapUrl + "'", ex); throw new BadCredentialsException(ex.getMessage()); } finally { if (context != null) { try { context.close(); } catch (NamingException ex) { logger.log(Level.WARNING, "Could not close DirContext", ex); } } } }
From source file:com.googlecode.fascinator.portal.security.filter.FascinatorAuthenticationInterceptorFilter.java
@Override protected void doFilterInternal(HttpServletRequest request, HttpServletResponse response, FilterChain filterChain) throws ServletException, IOException { Authentication authentication = SecurityContextHolder.getContext().getAuthentication(); JsonSessionState jsonSessionState = (JsonSessionState) request.getSession() .getAttribute("sso:com.googlecode.fascinator.portal.JsonSessionState"); if (jsonSessionState != null) { PreAuthenticatedAuthenticationToken token = null; if (authentication == null || authentication instanceof AnonymousAuthenticationToken) { if (jsonSessionState.get("username") != null) { token = new PreAuthenticatedAuthenticationToken(jsonSessionState.get("username"), "password"); SpringUser user = new SpringUser(); user.setUsername((String) jsonSessionState.get("username")); user.setSource((String) jsonSessionState.get("source")); token.setDetails(user);//from w w w.j a v a2s .c o m } else { if (request.getParameter("apiKey") != null && apiClients.get(request.getParameter("apiKey")) != null) { String username = apiClients.get(request.getParameter("apiKey")); token = new PreAuthenticatedAuthenticationToken(username, "password"); jsonSessionState.set("username", username); jsonSessionState.set("source", "internal"); SpringUser user = new SpringUser(); user.setUsername(username); user.setSource("internal"); token.setDetails(user); } } } else if (jsonSessionState.get("username") != null && !authentication.getName().equals(jsonSessionState.get("username"))) { token = new PreAuthenticatedAuthenticationToken(jsonSessionState.get("username"), "password"); SpringUser user = new SpringUser(); user.setUsername((String) jsonSessionState.get("username")); user.setSource((String) jsonSessionState.get("source")); token.setDetails(user); } else if (jsonSessionState.get("username") == null) { // must have logged out SecurityContextHolder.getContext().setAuthentication(null); } if (token != null) { // User has been logged in so let's create their credentials and // authenticate them authentication = authManager.authenticate(token); SecurityContextHolder.getContext().setAuthentication(authentication); } } if (authentication != null && !(authentication instanceof AnonymousAuthenticationToken)) { // SSO doesn't use a normal Roles plugin so we need to get the // roles again here and create a new token SpringUser user = (SpringUser) authentication.getCredentials(); if (!user.isSsoRolesSet()) { List<GrantedAuthority> userRoles = buildRoleList(user, jsonSessionState); user.setSsoRolesSet(true); authentication = new PreAuthenticatedAuthenticationToken(user.getUsername(), user, userRoles); SecurityContextHolder.getContext().setAuthentication(authentication); } } filterChain.doFilter(request, response); }