List of usage examples for org.springframework.security.core Authentication getPrincipal
Object getPrincipal();
From source file:org.syncope.core.security.SyncopeAuthenticationProvider.java
@Override @Transactional(noRollbackFor = { BadCredentialsException.class }) public Authentication authenticate(final Authentication authentication) throws AuthenticationException { boolean authenticated; SyncopeUser passwordUser = new SyncopeUser(); SyncopeUser user = null;//from ww w .j a va 2 s. co m if (adminUser.equals(authentication.getPrincipal())) { passwordUser.setPassword(authentication.getCredentials().toString(), CipherAlgorithm.MD5, 0); authenticated = adminMD5Password.equalsIgnoreCase(passwordUser.getPassword()); } else { String username; try { username = authentication.getPrincipal().toString(); } catch (NumberFormatException e) { throw new UsernameNotFoundException("Invalid username: " + authentication.getName(), e); } user = userDAO.find(username); if (user == null) { throw new UsernameNotFoundException("Could not find user " + username); } passwordUser.setPassword(authentication.getCredentials().toString(), user.getCipherAlgoritm(), 0); authenticated = user.getPassword().equalsIgnoreCase(passwordUser.getPassword()); } Authentication result; if ((user == null || !user.getSuspended()) && authenticated) { UsernamePasswordAuthenticationToken token = new UsernamePasswordAuthenticationToken( authentication.getPrincipal(), null, userDetailsService .loadUserByUsername(authentication.getPrincipal().toString()).getAuthorities()); token.setDetails(authentication.getDetails()); result = token; LOG.debug("User {} authenticated with roles {}", authentication.getPrincipal(), token.getAuthorities()); if (user != null) { user.setLastLoginDate(new Date()); user.setFailedLogins(0); userDAO.save(user); } } else { result = authentication; if (user != null && !user.getSuspended()) { user.setFailedLogins(user.getFailedLogins() + 1); userDAO.save(user); } LOG.debug("User {} not authenticated", authentication.getPrincipal()); throw new BadCredentialsException("User " + authentication.getPrincipal() + " not authenticated"); } return result; }
From source file:org.geonode.security.DatabaseSecurityClientTest.java
@Test public void testAuthenticateUserPassword() throws Exception { String username = "aang"; String password = "katara"; final String[] requestHeaders = { "Authorization", "Basic " + new String(Base64.encodeBase64((username + ":" + password).getBytes())) }; final String response = "{\"superuser\": true, \"user\": \"aang\", \"geoserver\": \"false\"}"; EasyMock.expect(mockHttpClient.sendGET(EasyMock.eq("http://localhost:8000/layers/resolve_user"), EasyMock.aryEq(requestHeaders))).andReturn(response); EasyMock.replay(mockHttpClient);//from w w w. j a va2 s . com Authentication authentication = client.authenticateUserPwd(username, password); EasyMock.verify(mockHttpClient); assertNotNull(authentication); assertTrue(authentication instanceof UsernamePasswordAuthenticationToken); assertTrue(authentication.isAuthenticated()); assertEquals("aang", ((UserDetails) authentication.getPrincipal()).getUsername()); List<GrantedAuthority> authorities = new ArrayList<GrantedAuthority>(); authorities.addAll(authentication.getAuthorities()); assertTrue(authorities.contains(GeoServerRole.ADMIN_ROLE)); assertTrue(authorities.contains(GeoServerRole.AUTHENTICATED_ROLE)); }
From source file:org.artifactory.webapp.servlet.RequestFilter.java
@Override public void doFilter(final ServletRequest req, final ServletResponse resp, final FilterChain chain) throws IOException, ServletException { long start = System.currentTimeMillis(); //Wrap the response HttpServletRequest request = (HttpServletRequest) req; HttpServletResponse response = (HttpServletResponse) resp; CapturingHttpServletResponseWrapper responseWrapper = new CapturingHttpServletResponseWrapper(response); try {//from ww w . jav a 2s .c o m RequestWrapper requestWrapper = new RequestWrapper(request); RequestThreadLocal.set(requestWrapper); chain.doFilter(req, responseWrapper); String servletPath = RequestUtils.getServletPathFromRequest(request); String method = request.getMethod(); long contentLength = 0; if ("get".equalsIgnoreCase(method)) { contentLength = responseWrapper.getContentLength(); } if (("put".equalsIgnoreCase(method)) || ("post".equalsIgnoreCase(method))) { contentLength = HttpUtils.getContentLength(request); } String username = "non_authenticated_user"; // First try to get the authentication from the session. Authentication authentication = RequestUtils.getAuthentication((HttpServletRequest) req); if (authentication != null) { username = authentication.getPrincipal().toString(); } else if (RequestUtils.isAuthHeaderPresent(request) || RequestUtils.getApiKeyTokenKeyValue(request) != null) { // since we do not have an authentication here, and a session was not opened since this // is a non UI request, we are forced to extract it out of the authentication header. username = RequestUtils.extractUsernameFromRequest(request); // in case of token request fetch user name username = findPropAuthUserNameByToken(request, username); } String remoteAddress = new HttpAuthenticationDetails(request).getRemoteAddress(); RequestLogger.request(remoteAddress, username, method, servletPath, request.getProtocol(), responseWrapper.getStatus(), contentLength, System.currentTimeMillis() - start); } finally { RequestThreadLocal.destroy(); } }
From source file:info.raack.appliancelabeler.security.HttpSessionAndDatabaseOAuthRemeberMeServices.java
public void rememberTokens(Map<String, OAuthConsumerToken> tokens, HttpServletRequest request, HttpServletResponse response) {/* w ww. j ava 2 s.c o m*/ // put tokens into session String email = ""; HttpSession session = request.getSession(false); if (session != null) { session.setAttribute(REMEMBERED_TOKENS_KEY, tokens); email = (String) session.getAttribute(EMAIL_ATTRIBUTE); } // put tokens into database Authentication auth = SecurityContextHolder.getContext().getAuthentication(); if (auth != null && auth.isAuthenticated()) { String userId = null; if (auth instanceof RememberMeAuthenticationToken) { Object principal = auth.getPrincipal(); if (principal instanceof OAuthUserDetails) { userId = ((OAuthUserDetails) principal).getUsername(); } else if (principal instanceof String) { userId = (String) auth.getPrincipal(); } } else if (auth instanceof OAuthAutomaticAuthenticationToken) { // user is already logged in via spring security userId = (String) auth.getPrincipal(); } logger.debug("Saving oauth tokens to database"); if (userId != null) { dataService.saveOAuthTokensForUserId(userId, email, tokens); } } }
From source file:cz.swi2.mendeluis.app.web.security.CustomPermissionsEvaluator.java
/** * Checks the current logged in user's permission to the given object. * @param authentication/*from w w w .j ava2s . c o m*/ * @param targetDomainObject * @param permission * @return True if the user has right to access the object. */ @Override public boolean hasPermission(Authentication authentication, Object targetDomainObject, Object permission) { boolean hasPermission = false; if (targetDomainObject != null && targetDomainObject instanceof UserPortlet) { UserPortlet member = (UserPortlet) targetDomainObject; UserDetails userDetails = (UserDetails) authentication.getPrincipal(); User user = userService.getUserByUsername(userDetails.getUsername()); User user2 = member.getUser(); hasPermission = (user.getId() == user2.getId()); logger.info("Checking username {} has permission to access member {} - {}", userDetails.getUsername(), targetDomainObject, hasPermission); } return hasPermission; }
From source file:com.example.AuthenticationController.java
@PostMapping("/factor") public void accept(@RequestParam String factor, Principal principal, HttpServletRequest request, HttpServletResponse response) throws Exception { if (!"red".equals(factor)) { response.sendRedirect("/factor?error=true"); return;/*from w w w . jav a 2s.c o m*/ } Authentication authentication = (Authentication) principal; Collection<GrantedAuthority> authorities = new ArrayList<>(authentication.getAuthorities()); authorities.add(new SimpleGrantedAuthority("ROLE_FACTOR")); PreAuthenticatedAuthenticationToken successful = new PreAuthenticatedAuthenticationToken( authentication.getPrincipal(), authentication.getCredentials(), authorities); successful.setDetails(authentication.getDetails()); SecurityContextHolder.getContext().setAuthentication(successful); handler.onAuthenticationSuccess(request, response, successful); }
From source file:org.xaloon.wicket.security.spring.SpringSecurityFacade.java
private DefaultUserDetails getUserDetails() { Authentication authentication = SecurityContextHolder.getContext().getAuthentication(); if (authentication == null) { return null; }/*from w ww. java2 s. com*/ Object o = authentication.getPrincipal(); if (o != null && o instanceof DefaultUserDetails) { return (DefaultUserDetails) o; } return null; }
From source file:it.geosolutions.geostore.services.rest.SecurityTest.java
protected void springAuthenticationTest() { doAutoLogin("admin", "admin", null); assertNotNull(SecurityContextHolder.getContext()); assertNotNull(SecurityContextHolder.getContext().getAuthentication()); final Authentication authentication = SecurityContextHolder.getContext().getAuthentication(); authentication.getName();// ww w.j ava 2 s . c o m assertEquals("admin", authentication.getCredentials()); Object principal = authentication.getPrincipal(); assertNotNull(principal); if (principal instanceof User) { User user = (User) principal; assertEquals("admin", user.getName()); } else if (principal instanceof LdapUserDetailsImpl) { LdapUserDetailsImpl userDetails = (LdapUserDetailsImpl) principal; assertEquals("uid=admin,ou=people,dc=geosolutions,dc=it", userDetails.getDn()); } assertEquals(authentication.getAuthorities().size(), 1); for (GrantedAuthority authority : authentication.getAuthorities()) { assertEquals("ROLE_ADMIN", authority.getAuthority()); } }
From source file:com.atin84.starsign.web.security.SessionSuccessHandler.java
public void onAuthenticationSuccess(HttpServletRequest request, HttpServletResponse response, Authentication authentication) throws ServletException, IOException { SavedRequest savedRequest = requestCache.getRequest(request, response); HttpSession session = request.getSession(); UserDetails userDetails = (UserDetails) authentication.getPrincipal(); HashMap<String, Object> param = new HashMap<String, Object>(); param.put("USERID", userDetails.getUsername().toString()); UserModel currentUser = (UserModel) dao.selectToObj("select.userObjectInfo", param); HashMap<String, Object> paramMap = new HashMap<String, Object>(); Map<String, Object> resultMap = new HashMap<String, Object>(); resultMap = dao.selectToMap("select.licenseKey", paramMap); String licenseKey;// w w w . j a v a 2s . co m if (resultMap != null) { licenseKey = (String) resultMap.get("LICENSEKEY"); } else licenseKey = "NA"; session.setAttribute("licenseKey", licenseKey); session.setAttribute("currUser", currentUser); session.setAttribute("productVersion", propertyManager.getProductVersion()); session.setAttribute("serverVersion", propertyManager.getServerVersion()); session.setAttribute("v3meAgent", propertyManager.getV3meAgent()); session.setAttribute("v3meClient", propertyManager.getV3meClient()); session.setAttribute("refreshTime", propertyManager.getRefreshTime()); String currentLocale = "ko"; if (localeResolver != null) { logger.debug("current locale from locale resolver : " + localeResolver.resolveLocale(request)); String locale = localeResolver.resolveLocale(request).toString(); locale = locale.trim(); locale = locale.toUpperCase(); if (locale.equals("KO") || locale.equals("KR") || locale.equals("KO_KR")) currentLocale = "ko"; else if (locale.equals("EN") || locale.equals("US") || locale.equals("EN_US")) currentLocale = "en"; else if (locale.equals("JP") || locale.equals("JA") || locale.equals("JP_JP")) currentLocale = "jp"; else { //currentLocale = localeResolver.resolveLocale(request).toString(); currentLocale = "en"; } } session.setAttribute("currentLocale", currentLocale); if (savedRequest == null) { super.onAuthenticationSuccess(request, response, authentication); return; } if (isAlwaysUseDefaultTargetUrl() || StringUtils.hasText(request.getParameter(getTargetUrlParameter()))) { requestCache.removeRequest(request, response); super.onAuthenticationSuccess(request, response, authentication); return; } // Use the SavedRequest URL String targetUrl = savedRequest.getRedirectUrl(); logger.debug("Redirecting to SavedRequest Url: " + targetUrl); getRedirectStrategy().sendRedirect(request, response, targetUrl); }
From source file:it.scoppelletti.programmerpower.security.DefaultUserManager.java
@Transactional(readOnly = true) public User loadLoggedUser() { User principal;//from www .j a va 2 s .c o m Authentication auth; SecurityContext secCtx = SecurityContextHolder.getContext(); auth = secCtx.getAuthentication(); if (auth == null || !auth.isAuthenticated() || auth instanceof AnonymousAuthenticationToken) { return null; } principal = (User) auth.getPrincipal(); return loadUser(principal.getId()); }