List of usage examples for org.springframework.security.core Authentication isAuthenticated
boolean isAuthenticated();
AuthenticationManager
. From source file:eu.trentorise.smartcampus.permissionprovider.oauth.ClientCredentialsFilter.java
@Override public Authentication attemptAuthentication(HttpServletRequest request, HttpServletResponse response) throws AuthenticationException, IOException, ServletException { String clientId = request.getParameter("client_id"); String clientSecret = request.getParameter("client_secret"); // If the request is already authenticated we can assume that this filter is not needed Authentication authentication = SecurityContextHolder.getContext().getAuthentication(); if (authentication != null && authentication.isAuthenticated()) { return authentication; }/* w ww . j av a 2 s .co m*/ if (clientId == null) { throw new BadCredentialsException("No client credentials presented"); } if (clientSecret == null) { clientSecret = ""; } clientId = clientId.trim(); // UsernamePasswordAuthenticationToken authRequest = new UsernamePasswordAuthenticationToken(clientId, clientSecret); ClientDetailsEntity clientDetails = clientDetailsRepository.findByClientId(clientId); boolean isTrusted = false; if (clientDetails.getAuthorities() != null) { for (GrantedAuthority ga : clientDetails.getAuthorities()) if (Config.AUTHORITY.ROLE_CLIENT_TRUSTED.toString().equals(ga.getAuthority())) { isTrusted = true; break; } } if (!isTrusted) { throw new InvalidGrantException("Unauthorized client access by client " + clientId); } String clientSecretServer = clientDetails.getClientSecret(); ClientAppInfo info = ClientAppInfo.convert(clientDetails.getAdditionalInformation()); String clientSecretMobile = clientDetails.getClientSecretMobile(); if (clientSecretMobile.equals(clientSecret) && !info.isNativeAppsAccess()) { throw new InvalidGrantException("Native app access is not enabled"); } if (!clientSecretServer.equals(clientSecret) && !clientSecretMobile.equals(clientSecret)) { throw new BadCredentialsException(messages .getMessage("AbstractUserDetailsAuthenticationProvider.badCredentials", "Bad credentials")); } User user = new User(clientId, clientSecret, clientDetails.getAuthorities()); UsernamePasswordAuthenticationToken result = new UsernamePasswordAuthenticationToken(user, clientSecretServer, user.getAuthorities()); // result.setDetails(authRequest.getDetails()); return result; }
From source file:org.mitre.oauth2.model.SavedUserAuthentication.java
/** * Create a Saved Auth from an existing Auth token *//*from w w w.j a v a 2s. c o m*/ public SavedUserAuthentication(Authentication src) { setName(src.getName()); setAuthorities(src.getAuthorities()); setAuthenticated(src.isAuthenticated()); if (src instanceof SavedUserAuthentication) { // if we're copying in a saved auth, carry over the original class name setSourceClass(((SavedUserAuthentication) src).getSourceClass()); } else { setSourceClass(src.getClass().getName()); } }
From source file:es.mdef.clientmanager.ui.GestionClientesUI.java
private String getNombreUsuario() { String nombre = ""; SecurityContext context = SecurityContextHolder.getContext(); Authentication authentication = context.getAuthentication(); if (authentication != null && authentication.isAuthenticated() && !authentication.getAuthorities().contains(new SimpleGrantedAuthority("ROLE_ANONYMOUS"))) { UserDetail userDetail = (UserDetail) authentication.getDetails(); nombre = userDetail.getAppUser().getUserName(); }/*from w w w . j ava 2 s . co m*/ return nombre; }
From source file:com.epam.storefront.security.AcceleratorAuthenticationProvider.java
/** * @param authentication/*from w w w .ja v a 2 s.c o m*/ * @param username * @return */ private Authentication doAuth(final Authentication authentication, final String username) { try { final Authentication authResult = super.authenticate(authentication); if (authResult.isAuthenticated() && !StringUtils.isEmpty(username)) { final UserModel userModel = getUserService().getUserForUID(StringUtils.lowerCase(username)); if (userModel instanceof CustomerModel) { final CustomerModel customerModel = (CustomerModel) userModel; customerModel.setAttemptCount(Integer.valueOf(0)); getModelService().save(customerModel); bruteForceAttackCounter.resetUserCounter(userModel.getUid()); } } return authResult; } catch (BadCredentialsException badCredentialsException) { if (!StringUtils.isEmpty(username)) { final UserModel userModel = getUserService().getUserForUID(StringUtils.lowerCase(username)); if (userModel instanceof CustomerModel) { final CustomerModel customerModel = (CustomerModel) userModel; final int attemptCount = customerModel.getAttemptCount() != null ? customerModel.getAttemptCount().intValue() : 0; customerModel.setAttemptCount(Integer.valueOf(attemptCount + 1)); getModelService().save(customerModel); } } throw badCredentialsException; } catch (AuthenticationException authenticationException) { throw authenticationException; } }
From source file:eu.freme.broker.security.AuthenticationFilter.java
private Authentication tryToAuthenticate(Authentication requestAuthentication) { Authentication responseAuthentication = authenticationManager.authenticate(requestAuthentication); if (responseAuthentication == null || !responseAuthentication.isAuthenticated()) { throw new InternalAuthenticationServiceException( "Unable to authenticate Domain User for provided credentials"); }//from w ww . ja v a2 s . c o m logger.debug("User successfully authenticated"); return responseAuthentication; }
From source file:waffle.spring.ImpersonateTests.java
/** * Test impersonate disabled.//from w ww . j av a 2 s. com * * @throws IOException * Signals that an I/O exception has occurred. * @throws ServletException * the servlet exception */ @Test public void testImpersonateDisabled() throws IOException, ServletException { Assertions.assertNotEquals("Current user shouldn't be the test user prior to the test", MockWindowsAccount.TEST_USER_NAME, Advapi32Util.getUserName()); final SimpleHttpRequest request = new SimpleHttpRequest(); request.setMethod("GET"); final String userHeaderValue = MockWindowsAccount.TEST_USER_NAME + ":" + MockWindowsAccount.TEST_PASSWORD; final String basicAuthHeader = "Basic " + Base64.getEncoder().encodeToString(userHeaderValue.getBytes(StandardCharsets.UTF_8)); request.addHeader("Authorization", basicAuthHeader); final SimpleHttpResponse response = new SimpleHttpResponse(); final RecordUserNameFilterChain filterChain = new RecordUserNameFilterChain(); this.filter.setImpersonate(false); this.filter.doFilter(request, response, filterChain); final Authentication authentication = SecurityContextHolder.getContext().getAuthentication(); Assertions.assertTrue(authentication.isAuthenticated(), "Test user should be authenticated"); final Principal principal = (Principal) authentication.getPrincipal(); assertThat(principal).isInstanceOf(WindowsPrincipal.class); final WindowsPrincipal windowsPrincipal = (WindowsPrincipal) principal; try { Assertions.assertNotEquals(MockWindowsAccount.TEST_USER_NAME, filterChain.getUserName(), "Test user should not be impersonated"); Assertions.assertNotEquals(MockWindowsAccount.TEST_USER_NAME, Advapi32Util.getUserName(), "Impersonation context should have been reverted"); } finally { windowsPrincipal.getIdentity().dispose(); } }
From source file:waffle.spring.ImpersonateTests.java
/** * Test impersonate enabled./*www. j a v a2s . c om*/ * * @throws IOException * Signals that an I/O exception has occurred. * @throws ServletException * the servlet exception */ @Test public void testImpersonateEnabled() throws IOException, ServletException { Assertions.assertNotEquals("Current user shouldn't be the test user prior to the test", MockWindowsAccount.TEST_USER_NAME, Advapi32Util.getUserName()); final SimpleHttpRequest request = new SimpleHttpRequest(); request.setMethod("GET"); final String userHeaderValue = MockWindowsAccount.TEST_USER_NAME + ":" + MockWindowsAccount.TEST_PASSWORD; final String basicAuthHeader = "Basic " + Base64.getEncoder().encodeToString(userHeaderValue.getBytes(StandardCharsets.UTF_8)); request.addHeader("Authorization", basicAuthHeader); final SimpleHttpResponse response = new SimpleHttpResponse(); final RecordUserNameFilterChain filterChain = new RecordUserNameFilterChain(); this.filter.setImpersonate(true); this.filter.doFilter(request, response, filterChain); final Authentication authentication = SecurityContextHolder.getContext().getAuthentication(); Assertions.assertTrue(authentication.isAuthenticated(), "Test user should be authenticated"); final Principal principal = (Principal) authentication.getPrincipal(); assertThat(principal).isInstanceOf(AutoDisposableWindowsPrincipal.class); final AutoDisposableWindowsPrincipal windowsPrincipal = (AutoDisposableWindowsPrincipal) principal; try { Assertions.assertEquals(MockWindowsAccount.TEST_USER_NAME, filterChain.getUserName(), "Test user should be impersonated"); Assertions.assertNotEquals(MockWindowsAccount.TEST_USER_NAME, Advapi32Util.getUserName(), "Impersonation context should have been reverted"); } finally { windowsPrincipal.getIdentity().dispose(); } }
From source file:com.github.djabry.platform.service.security.DefaultSpringAuthenticationService.java
/** * @return The current logged in user/*from www.j a va2 s . c o m*/ */ @Override public DBUser getCurrentUser() { Authentication auth = SecurityContextHolder.getContext().getAuthentication(); if (auth.isAuthenticated() && currentUser != null) { String username = auth.getName(); if (username.equals(currentUser.getUsername())) { return currentUser; } } currentUser = null; return null; }
From source file:org.openmrs.contrib.metadatarepository.service.impl.UserSecurityAdviceTest.java
@Test public void testAddUserWithoutAdminRole() throws Exception { Authentication auth = SecurityContextHolder.getContext().getAuthentication(); assertTrue(auth.isAuthenticated()); UserManager userManager = makeInterceptedTarget(); User user = new User("admin"); user.setId(2L);//from www . j a v a 2 s .com try { userManager.saveUser(user); fail("AccessDeniedException not thrown"); } catch (AccessDeniedException expected) { assertNotNull(expected); Assert.assertEquals(expected.getMessage(), UserSecurityAdvice.ACCESS_DENIED); } }
From source file:com.bisone.saiku.security.replace.SessionService.java
private void createSession(Authentication auth, String username, String password) { if (auth == null || !auth.isAuthenticated()) { return;// w w w. j av a2 s .c om } boolean isAnonymousUser = (auth instanceof AnonymousAuthenticationToken); Object p = auth.getPrincipal(); String authUser = getUsername(p); boolean isAnonymous = (isAnonymousUser || StringUtils.equals("anonymousUser", authUser)); boolean isAnonOk = (!isAnonymous || (isAnonymous && anonymous)); if (isAnonOk && auth.isAuthenticated() && p != null && !sessionHolder.containsKey(p)) { Map<String, Object> session = new HashMap<String, Object>(); if (isAnonymous) { log.debug("Creating Session for Anonymous User"); } if (StringUtils.isNotBlank(username)) { session.put("username", username); } else { session.put("username", authUser); } if (StringUtils.isNotBlank(password)) { session.put("password", password); } session.put("sessionid", UUID.randomUUID().toString()); session.put("authid", RequestContextHolder.currentRequestAttributes().getSessionId()); List<String> roles = new ArrayList<String>(); for (GrantedAuthority ga : SecurityContextHolder.getContext().getAuthentication().getAuthorities()) { roles.add(ga.getAuthority()); } session.put("roles", roles); sessionHolder.put(p, session); } }