List of usage examples for org.springframework.security.core Authentication isAuthenticated
boolean isAuthenticated();
AuthenticationManager
. From source file:org.vaadin.spring.security.AbstractVaadinSecurity.java
@Override public boolean isAuthenticatedAnonymously() { final Authentication authentication = getAuthentication(); return authentication instanceof AnonymousAuthenticationToken && authentication.isAuthenticated(); }
From source file:org.vaadin.spring.security.AbstractVaadinSecurity.java
@Override public boolean isRememberMeAuthenticated() { final Authentication authentication = getAuthentication(); return authentication instanceof RememberMeAuthenticationToken && authentication.isAuthenticated(); }
From source file:org.apache.cxf.fediz.service.idp.kerberos.KerberosAuthenticationProcessingFilter.java
public void doFilter(ServletRequest req, ServletResponse res, FilterChain chain) throws IOException, ServletException { HttpServletRequest request = (HttpServletRequest) req; HttpServletResponse response = (HttpServletResponse) res; if (skipIfAlreadyAuthenticated) { Authentication existingAuth = SecurityContextHolder.getContext().getAuthentication(); if (existingAuth != null && existingAuth.isAuthenticated() && !(existingAuth instanceof AnonymousAuthenticationToken)) { chain.doFilter(request, response); return; }/*from w ww .j a va 2 s .co m*/ } String header = request.getHeader("Authorization"); if ((header != null) && header.startsWith("Negotiate ")) { if (logger.isDebugEnabled()) { logger.debug("Received Negotiate Header for request " + request.getRequestURL() + ": " + header); } byte[] base64Token = header.substring(10).getBytes("UTF-8"); byte[] kerberosTicket = Base64.decode(base64Token); KerberosServiceRequestToken authenticationRequest = new KerberosServiceRequestToken(kerberosTicket); authenticationRequest.setDetails(authenticationDetailsSource.buildDetails(request)); Authentication authentication; try { authentication = authenticationManager.authenticate(authenticationRequest); } catch (AuthenticationException e) { //That shouldn't happen, as it is most likely a wrong //configuration on the server side logger.warn("Negotiate Header was invalid: " + header, e); SecurityContextHolder.clearContext(); if (failureHandler != null) { failureHandler.onAuthenticationFailure(request, response, e); } else { response.setStatus(HttpServletResponse.SC_INTERNAL_SERVER_ERROR); response.flushBuffer(); } return; } sessionStrategy.onAuthentication(authentication, request, response); SecurityContextHolder.getContext().setAuthentication(authentication); if (successHandler != null) { successHandler.onAuthenticationSuccess(request, response, authentication); } } chain.doFilter(request, response); }
From source file:com.sibvisions.rad.server.security.spring.SpringSecurityManager.java
/** * {@inheritDoc}// w ww .ja va 2 s . co m */ public void validateAuthentication(ISession pSession) { SecurityContext securityContext = SecurityContextHolder.getContext(); if (securityContext != null) { Authentication authentication = securityContext.getAuthentication(); if (authentication != null && authentication.isAuthenticated()) { Hashtable<String, Object> metadataProperties = new Hashtable<String, Object>(); metadataProperties.put("authentication", authentication); ISpringMetaDataHandler metaDataHandler = getAuthenticationMetaDataHandler(metadataProperties, pSession); if (pSession instanceof AbstractSession) { ((AbstractSession) pSession).setUserName(metaDataHandler.getUsername()); ((AbstractSession) pSession).setPassword(metaDataHandler.getPassword()); } pSession.setProperty(METADATA_HANDLER, metaDataHandler); if (!(authentication instanceof WrappedAuthentication)) { authentication = new WrappedAuthentication(authentication); SecurityContextHolder.getContext().setAuthentication(authentication); } // set the jvx session id into the authentication object for the logout (success) handler ((WrappedAuthentication) authentication).setProperty(SESSION_ID, pSession.getId()); // set the logout process url Object logoutProcessUrl = ((WrappedAuthentication) authentication).getProperty(LOGOUT_PROCESS_URL); if (logoutProcessUrl == null) { HttpContext context = HttpContext.getCurrentInstance(); if (context != null) { HttpSession session = ((HttpServletRequest) context.getRequest()).getSession(false); if (session != null) { logoutProcessUrl = session.getAttribute(LOGOUT_PROCESS_URL); } } } pSession.setProperty(LOGOUT_PROCESS_URL, logoutProcessUrl); } else { throw new SecurityException("Access denied! The authentication could not be established."); } } else { throw new SecurityException("Access denied! The security context could not be established."); } }
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>/* ww w. java2s .co m*/ * <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:com.example.oauth2.loginprovider.oauth.OauthUserApprovalHandler.java
/** * Allows automatic approval for a white list of clients in the implicit grant case. * //from w w w .ja va2 s.c o m * @param authorizationRequest The authorization request. * @param userAuthentication the current user authentication * * @return Whether the specified request has been approved by the current user. */ @Override public boolean isApproved(AuthorizationRequest authorizationRequest, Authentication userAuthentication) { // If we are allowed to check existing approvals this will short circuit the decision if (useTokenServices && super.isApproved(authorizationRequest, userAuthentication)) { return true; } if (!userAuthentication.isAuthenticated()) { return false; } String flag = authorizationRequest.getApprovalParameters().get(AuthorizationRequest.USER_OAUTH_APPROVAL); boolean approved = flag != null && flag.toLowerCase().equals("true"); return approved || (authorizationRequest.getResponseTypes().contains("token") && autoApproveClients.contains(authorizationRequest.getClientId())); }
From source file:de.tudarmstadt.ukp.clarin.webanno.webapp.security.SpringAuthenticatedWebSession.java
@Override public boolean authenticate(String username, String password) { boolean authenticated = false; try {//from w ww.j a v a 2 s . co m Authentication authentication = authenticationManager .authenticate(new UsernamePasswordAuthenticationToken(username, password)); SecurityContextHolder.getContext().setAuthentication(authentication); authenticated = authentication.isAuthenticated(); } catch (AuthenticationException e) { log.warn(format("User '%s' failed to login. Reason: %s", username, e.getMessage())); authenticated = false; } return authenticated; }
From source file:shiver.me.timbers.spring.security.jwt.JwtPrincipalAuthenticationConverterTest.java
@Test @SuppressWarnings("unchecked") public void Can_convert_a_jwt_principle_to_a_jwt_authentication() { final JwtPrincipal principal = mock(JwtPrincipal.class); final List<String> roles = mock(List.class); final String username = someString(); final Collection<GrantedAuthority> authorities = asList(mock(GrantedAuthority.class), mock(GrantedAuthority.class), mock(GrantedAuthority.class)); // Given/*from ww w. j a va 2s . com*/ given(principal.getUsername()).willReturn(username); given(principal.getRoles()).willReturn(roles); given(grantedAuthorityConverter.convert(roles)).willReturn((Collection) authorities); // When final Authentication actual = converter.convert(principal); // Then assertThat(actual.getPrincipal(), is((Object) username)); assertThat(actual.getAuthorities(), is((Collection) authorities)); assertThat(actual.isAuthenticated(), is(true)); }
From source file:de.tudarmstadt.ukp.csniper.webapp.security.SpringAuthenticatedWebSession.java
@Override public boolean authenticate(String username, String password) { boolean authenticated = false; try {/*from www. ja v a 2 s . co m*/ Authentication authentication = authenticationManager .authenticate(new UsernamePasswordAuthenticationToken(username, password)); SecurityContextHolder.getContext().setAuthentication(authentication); authenticated = authentication.isAuthenticated(); } catch (AuthenticationException e) { log.warn(format("User '%s' failed to login. Reason: %s", username, e.getMessage())); error(format("User '%s' failed to login. Reason: %s", username, e.getMessage())); authenticated = false; } return authenticated; }
From source file:edu.zipcloud.cloudstreetmarket.core.authentication.CustomOAuth2RequestFilter.java
private boolean authenticationIsRequired(String username) { // Only reauthenticate if username doesn't match SecurityContextHolder and user // isn't authenticated // (see SEC-53) Authentication existingAuth = SecurityContextHolder.getContext().getAuthentication(); if (existingAuth == null || !existingAuth.isAuthenticated()) { return true; }/*from ww w .j a v a2 s.com*/ // Limit username comparison to providers which use usernames (ie // UsernamePasswordAuthenticationToken) // (see SEC-348) if (existingAuth instanceof UsernamePasswordAuthenticationToken && !existingAuth.getName().equals(username)) { return true; } if (!UserDetailsUtil.hasRole(existingAuth.getAuthorities(), ROLE_OAUTH2)) { return true; } // Handle unusual condition where an AnonymousAuthenticationToken is already // present // This shouldn't happen very often, as BasicProcessingFitler is meant to be // earlier in the filter // chain than AnonymousAuthenticationFilter. Nevertheless, presence of both an // AnonymousAuthenticationToken // together with a BASIC authentication request header should indicate // reauthentication using the // BASIC protocol is desirable. This behaviour is also consistent with that // provided by form and digest, // both of which force re-authentication if the respective header is detected (and // in doing so replace // any existing AnonymousAuthenticationToken). See SEC-610. if (existingAuth instanceof AnonymousAuthenticationToken) { return true; } return false; }