List of usage examples for org.springframework.security.core Authentication getAuthorities
Collection<? extends GrantedAuthority> getAuthorities();
AuthenticationManager
to indicate the authorities that the principal has been granted. From source file:com.bac.accountserviceapp.data.mysql.MysqlAccountServiceAppSpringAuthenticationTest.java
@Test public void testAuthentication_InactiveAccount() throws NoSuchAlgorithmException { logger.info("testAuthentication_InactiveAccount"); try {/*from ww w .jav a 2 s . com*/ createUserAccount(); // // Set the Account to Inactive // // account.setActive(INACTIVE); account.setEnabled(false); resultAccount = accessor.updateAccount(account); assertThat(resultAccount, is(notNullValue())); assertEquals(accountId, resultAccount.getId()); // assertEquals(INACTIVE, resultAccount.getActive()); assertEquals(false, resultAccount.isEnabled()); // // Authenticate // UsernamePasswordAuthenticationToken authentication = new UsernamePasswordAuthenticationToken(userEmail, userPassword); Authentication resultAuthentication = instance.login(authentication); assertNotNull(resultAuthentication); // // Check the outcome // authenticateOutcome(resultAuthentication, AUTHENTICATED); // // Get the Authentication Principal: It should represent the UserDetails // authenticatePrincipal(resultAuthentication, AccountServiceUserDetails.class); authenticateUserDetails((UserDetails) resultAuthentication.getPrincipal(), userEmail); // // Ensure that no Authority has been granted // Collection<? extends GrantedAuthority> authorities = resultAuthentication.getAuthorities(); assertNotNull(authorities); int expAuthoritySize = 0; int resultAuthoritySize = authorities.size(); assertEquals(expAuthoritySize, resultAuthoritySize); } catch (InvalidKeySpecException ex) { logger.error("Password encryption error"); } finally { // Clean up logger.info("testAuthentication: Delete"); deleteUserAccount(); } }
From source file:de.thm.arsnova.services.UserService.java
@Override public User getCurrentUser() { final Authentication authentication = SecurityContextHolder.getContext().getAuthentication(); if (authentication == null || authentication.getPrincipal() == null) { return null; }/* w w w . j a va 2 s. c om*/ User user = null; if (authentication instanceof OAuthAuthenticationToken) { user = getOAuthUser(authentication); } else if (authentication instanceof CasAuthenticationToken) { final CasAuthenticationToken token = (CasAuthenticationToken) authentication; user = new User(token.getAssertion().getPrincipal()); } else if (authentication instanceof AnonymousAuthenticationToken) { final AnonymousAuthenticationToken token = (AnonymousAuthenticationToken) authentication; user = new User(token); } else if (authentication instanceof UsernamePasswordAuthenticationToken) { final UsernamePasswordAuthenticationToken token = (UsernamePasswordAuthenticationToken) authentication; user = new User(token); if (authentication.getAuthorities().contains(new SimpleGrantedAuthority("ROLE_GUEST"))) { user.setType(User.GUEST); } else if (authentication.getAuthorities().contains(new SimpleGrantedAuthority("ROLE_DB_USER"))) { user.setType(User.ARSNOVA); } } if (user == null || user.getUsername().equals("anonymous")) { throw new UnauthorizedException(); } return user; }
From source file:com.bac.accountserviceapp.data.mysql.MysqlAccountServiceAppSpringAuthenticationTest.java
@Test public void testAuthentication_TwoApplications() throws NoSuchAlgorithmException { logger.info("testAuthentication_InactiveAccountUser"); Application application2;/*from www . j a v a 2 s.c o m*/ Application resultApplication2; final String applicationName2 = UUID.randomUUID().toString(); Integer applicationId2 = null; // Account account2; Account resultAccount2; final String resourceName2 = UUID.randomUUID().toString(); Integer accountId2 = null; // AccountUser accountUser2 = null; AccountUser resultAccountUser2; try { createUserAccount(); // // Create an additonal Application, Account and AccountUser // // // Create a simple application // application2 = new SimpleApplication(); application2.setName(applicationName2); application2.setEnabled(true); // // Persist it and test // resultApplication2 = accessor.createApplication(application2); assertThat(resultApplication2, is(notNullValue())); assertThat(resultApplication2.getId(), is(notNullValue())); applicationId2 = resultApplication2.getId(); // // Create a simple account // account2 = new SimpleAccount(); account2.setResourceName(resourceName2); account2.setEnabled(true); account2.setCreateDate(createDate); account2.setApplicationId(applicationId2); // // Persist it and test // resultAccount2 = accessor.createAccount(account2); assertThat(resultAccount2, is(notNullValue())); assertThat(resultAccount2.getId(), is(notNullValue())); accountId2 = resultAccount2.getId(); // // Create the Account User // accountUser2 = new SimpleAccountUser(); accountUser2.setAccountId(accountId2); accountUser2.setUserId(userId); accountUser2.setEnabled(true); accountUser2.setCreateDate(createDate); accountUser2.setLastAccessDate(createDate); accountUser2.setAccessLevelId(accessLevelId); // // Persist it and test // // resultAccountUser2 = accessor.createAccountUser(accountUser2); assertThat(resultAccountUser2, is(notNullValue())); // // Authenticate // UsernamePasswordAuthenticationToken authentication = new UsernamePasswordAuthenticationToken(userEmail, userPassword); Authentication resultAuthentication = instance.login(authentication); assertNotNull(resultAuthentication); // // Check the outcome // authenticateOutcome(resultAuthentication, AUTHENTICATED); // // Get the Authentication Principal: It should represent the UserDetails // authenticatePrincipal(resultAuthentication, AccountServiceUserDetails.class); authenticateUserDetails((UserDetails) resultAuthentication.getPrincipal(), userEmail); // // Ensure that both Authorities have been granted // Collection<? extends GrantedAuthority> authorities = resultAuthentication.getAuthorities(); assertNotNull(authorities); int expAuthoritySize = 2; int resultAuthoritySize = authorities.size(); assertEquals(expAuthoritySize, resultAuthoritySize); List<String> authoritiesList = getAuthorityList(authorities); assertNotNull(authoritiesList); final String expAuthority1 = applicationName + AUTHORITY_SEPARATOR + accessLevelRole.name(); assertTrue(authoritiesList.contains(expAuthority1)); final String expAuthority2 = applicationName2 + AUTHORITY_SEPARATOR + accessLevelRole.name(); assertTrue(authoritiesList.contains(expAuthority2)); } catch (InvalidKeySpecException ex) { logger.error("Password encryption error"); } finally { // Clean up logger.info("testAuthentication: Delete"); deleteUserAccount(); // // Clean up the second application account // // Remove Account // account2 = accessor.getAccount(accountId2); accessor.deleteAccount(account2); resultAccount2 = accessor.getAccount(accountId2); assertThat(resultAccount2, is(nullValue())); // // Remove Account User // // accountUser2 = accessor.getAccountUser(accountUser2); // accessor.deleteAccountUser(accountUser2); resultAccountUser2 = accessor.getAccountUser(accountUser2); assertThat(resultAccountUser2, is(nullValue())); // // Remove Application // application2 = accessor.getApplication(applicationId2); accessor.deleteApplication(application2); resultApplication2 = accessor.getApplication(applicationId2); assertThat(resultApplication2, is(nullValue())); } }
From source file:org.sharetask.security.StoreUserInformationAuthenticationSuccessHandler.java
@Override public void onAuthenticationSuccess(final HttpServletRequest request, final HttpServletResponse response, Authentication authentication) throws IOException, ServletException { if (authentication instanceof ClientAuthenticationToken) { log.debug("Token is pac4j token."); String language = Language.EN.getCode(); UsernamePasswordAuthenticationToken authentToken; final CommonProfile profile = (CommonProfile) ((ClientAuthenticationToken) authentication) .getUserProfile();//from w ww. j av a2 s. co m if (userRepository.findByUsername(profile.getEmail()) == null) { log.debug("User with name: {} doesne exist's. Will be created", profile.getEmail()); final UserInformation userInformation = new UserInformation(profile.getEmail()); userInformation.setName(profile.getFirstName()); userInformation.setSurName(profile.getFamilyName()); userInformation.setLanguage(language); final ArrayList<Role> list = new ArrayList<Role>(); list.add(Role.ROLE_USER); userInformation.setRoles(list); userRepository.save(userInformation); final List<GrantedAuthority> authorities = new ArrayList<GrantedAuthority>(); authorities.add(new SimpleGrantedAuthority(Role.ROLE_USER.name())); authentToken = new UsernamePasswordAuthenticationToken(profile.getEmail(), "", authorities); } else { final UserInformation user = userRepository.read(profile.getEmail()); language = user.getLanguage(); final Collection<? extends GrantedAuthority> authorities = authentication.getAuthorities(); authentToken = new UsernamePasswordAuthenticationToken(profile.getEmail(), "", authorities); } // language cookie final Cookie locale = new Cookie(RequestUltil.LOCALE, language); locale.setMaxAge(-1); locale.setPath("/"); response.addCookie(locale); SecurityContextHolder.getContext().setAuthentication(authentToken); } super.onAuthenticationSuccess(request, response, authentication); }
From source file:ch.entwine.weblounge.kernel.security.UserContextFilter.java
/** * Loads the user from the given site./*w ww . ja v a 2 s. com*/ * * @param site * the site * @return the user */ protected User getUser(Site site) { logger.trace("Looking up user from spring security context"); Authentication auth = SecurityContextHolder.getContext().getAuthentication(); User user = null; Set<Role> roles = new HashSet<Role>(); if (!securityService.isEnabled()) { user = new UserImpl(Security.ADMIN_USER, Security.SYSTEM_CONTEXT, Security.ADMIN_NAME); roles.add(SystemRole.SYSTEMADMIN); roles.add(getLocalRole(site, SystemRole.SYSTEMADMIN)); } else if (auth == null) { logger.debug("No spring security context available, setting current user to anonymous"); String realm = site != null ? site.getIdentifier() : Security.SYSTEM_CONTEXT; user = new UserImpl(Security.ANONYMOUS_USER, realm, Security.ANONYMOUS_NAME); roles.add(SystemRole.GUEST); roles.add(getLocalRole(site, SystemRole.GUEST)); } else { Object principal = auth.getPrincipal(); if (principal == null) { logger.warn("No principal found in spring security context, setting current user to anonymous"); user = new Guest(site.getIdentifier()); roles.add(getLocalRole(site, SystemRole.GUEST)); } else if (principal instanceof SpringSecurityUser) { user = ((SpringSecurityUser) principal).getUser(); logger.debug("Principal was identified as '{}'", user.getLogin()); } else if (principal instanceof UserDetails) { UserDetails userDetails = (UserDetails) principal; user = new UserImpl(userDetails.getUsername()); logger.debug("Principal was identified as '{}'", user.getLogin()); Collection<? extends GrantedAuthority> authorities = auth.getAuthorities(); if (authorities != null && authorities.size() > 0) { for (GrantedAuthority ga : authorities) { logger.debug("Principal '{}' gained role '{}'", user.getLogin(), ga.getAuthority()); roles.add(new RoleImpl(ga.getAuthority())); } } } else if (Security.ANONYMOUS_USER.equals(principal)) { user = new Guest(site.getIdentifier()); roles.add(getLocalRole(site, SystemRole.GUEST)); } else { logger.warn("Principal was not compatible with spring security, setting current user to anonymous"); user = new Guest(site.getIdentifier()); roles.add(getLocalRole(site, SystemRole.GUEST)); } } for (Role role : roles) { user.addPublicCredentials(role); } return user; }
From source file:org.geonode.security.GeoNodeCookieProcessingFilter.java
/** * //from w ww.j a v a2 s .c om * @see javax.servlet.Filter#doFilter(javax.servlet.ServletRequest, * javax.servlet.ServletResponse, javax.servlet.FilterChain) */ public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain) throws IOException, ServletException { final HttpServletRequest httpRequest = (HttpServletRequest) request; final SecurityContext securityContext = SecurityContextHolder.getContext(); final Authentication existingAuth = securityContext.getAuthentication(); final String gnCookie = getGeoNodeCookieValue(httpRequest); final boolean alreadyAuthenticated = existingAuth != null && existingAuth.isAuthenticated(); final boolean anonymous = existingAuth == null || existingAuth instanceof AnonymousAuthenticationToken; // if logging in via geoserver web form, we want to short circuit the cookie // check below which might get triggered with an anon geonode cookie // the result looks like the login worked but because we replace the // auth below, it functionaly fails final boolean loggedInWithPassword = existingAuth instanceof UsernamePasswordAuthenticationToken && alreadyAuthenticated; final boolean hasPreviouslyValidatedGeoNodeCookie = (existingAuth instanceof GeoNodeSessionAuthToken) && existingAuth.getCredentials().equals(gnCookie); if (hasPreviouslyValidatedGeoNodeCookie) existingAuth.setAuthenticated(true); // if we still need to authenticate and we find the cookie, consult GeoNode for // an authentication final boolean authenticationRequired = (!alreadyAuthenticated || anonymous || !hasPreviouslyValidatedGeoNodeCookie); if (!loggedInWithPassword && authenticationRequired && gnCookie != null) { if (LOGGER.isLoggable(Level.FINE)) { LOGGER.fine( "Found GeoNode cookie - checking if we have the authorizations in cache or if we have to reload from GeoNode"); } try { Object principal = existingAuth == null ? null : existingAuth.getPrincipal(); Collection<? extends GrantedAuthority> authorities = existingAuth == null ? null : existingAuth.getAuthorities(); Authentication authRequest = new GeoNodeSessionAuthToken(principal, gnCookie, authorities); final Authentication authResult = getSecurityManager().authenticate(authRequest); LOGGER.log(Level.FINE, "authResult : {0}", authResult); securityContext.setAuthentication(authResult); } catch (AuthenticationException e) { // we just go ahead and fall back on basic authentication LOGGER.log(Level.WARNING, "Error connecting to the GeoNode server for authentication purposes", e); } } // move forward along the chain chain.doFilter(request, response); }
From source file:com.sonymobile.backlogtool.JSONController.java
private boolean isLoggedIn() { Authentication auth = SecurityContextHolder.getContext().getAuthentication(); GrantedAuthority anonymous = new SimpleGrantedAuthority("ROLE_ANONYMOUS"); return !auth.getAuthorities().contains(anonymous); }
From source file:com.evolveum.midpoint.security.enforcer.impl.SecurityEnforcerImpl.java
private Collection<Authorization> getAuthorities(MidPointPrincipal principal) { if (principal == null) { // Anonymous access, possibly with elevated privileges Authentication authentication = SecurityContextHolder.getContext().getAuthentication(); Collection<Authorization> authorizations = new ArrayList<>(); if (authentication != null) { for (GrantedAuthority authority : authentication.getAuthorities()) { if (authority instanceof Authorization) { authorizations.add((Authorization) authority); }/*from www. j av a 2 s. c o m*/ } } return authorizations; } else { return principal.getAuthorities(); } }