List of usage examples for org.springframework.security.core Authentication getDetails
Object getDetails();
From source file:org.cloudfoundry.identity.uaa.login.ChainedAuthenticationManager.java
@Override public Authentication authenticate(Authentication authentication) throws AuthenticationException { if (authentication == null) { return authentication; }//from w w w .ja v a 2 s . co m UsernamePasswordAuthenticationToken output = null; if (authentication instanceof UsernamePasswordAuthenticationToken) { output = (UsernamePasswordAuthenticationToken) authentication; } else { output = new UsernamePasswordAuthenticationToken(authentication.getPrincipal(), authentication.getCredentials(), authentication.getAuthorities()); output.setAuthenticated(authentication.isAuthenticated()); output.setDetails(authentication.getDetails()); } boolean authenticated = false; Authentication auth = null; AuthenticationException lastException = null; for (int i = 0; i < delegates.length && (!authenticated); i++) { try { if (logger.isDebugEnabled()) { logger.debug( "Attempting chained authentication of " + output + " with manager:" + delegates[i]); } auth = delegates[i].authenticate(output); authenticated = auth.isAuthenticated(); } catch (AuthenticationException x) { if (logger.isDebugEnabled()) { logger.debug("Chained authentication exception:", x); } lastException = x; } if (logger.isDebugEnabled()) { logger.debug("Chained Authentication status of " + output + " with manager:" + delegates[i] + "; Authenticated:" + authenticated); } } if (authenticated) { return auth; } else if (lastException != null) { //we had at least one authentication exception, throw it throw lastException; } else { //not authenticated, but return the last of the result return auth; } }
From source file:eu.freme.common.security.AuthenticationController.java
@RequestMapping(value = "/authenticate", method = RequestMethod.POST, produces = "application/json") public ResponseEntity<String> authenticate( @RequestHeader(value = "X-Auth-Username", required = true) String username, @RequestHeader(value = "X-Auth-Password", required = true) String password) { UsernamePasswordAuthenticationToken requestAuthentication = new UsernamePasswordAuthenticationToken( username, password);//from ww w.ja v a 2 s . c o m Authentication resultOfAuthentication = null; try { Authentication responseAuthentication = authenticationManager.authenticate(requestAuthentication); if (responseAuthentication == null || !responseAuthentication.isAuthenticated()) { throw new AuthenticationFailedException(); } logger.debug("User successfully authenticated"); resultOfAuthentication = responseAuthentication; } catch (Exception e) { logger.error(e); throw new AuthenticationFailedException(); } SecurityContextHolder.getContext().setAuthentication(resultOfAuthentication); Token token = (Token) resultOfAuthentication.getDetails(); JSONObject json = new JSONObject(); json.put("token", token.getToken()); ResponseEntity<String> response = new ResponseEntity<String>(json.toString(), HttpStatus.OK); return response; }
From source file:org.cloudfoundry.identity.uaa.audit.event.AbstractUaaEvent.java
protected String getOrigin(Principal principal) { if (principal instanceof Authentication) { Authentication caller = (Authentication) principal; StringBuilder builder = new StringBuilder(); if (caller instanceof OAuth2Authentication) { OAuth2Authentication oAuth2Authentication = (OAuth2Authentication) caller; builder.append("client=").append(oAuth2Authentication.getAuthorizationRequest().getClientId()); if (!oAuth2Authentication.isClientOnly()) { builder.append(", ").append("user=").append(oAuth2Authentication.getName()); }/* ww w . j a v a 2s . c o m*/ } else { builder.append("caller=").append(caller.getName()).append(", "); } if (caller.getDetails() != null) { builder.append(", details=("); try { @SuppressWarnings("unchecked") Map<String, Object> map = mapper.convertValue(caller.getDetails(), Map.class); if (map.containsKey("remoteAddress")) { builder.append("remoteAddress=").append(map.get("remoteAddress")).append(", "); } builder.append("type=").append(caller.getDetails().getClass().getSimpleName()); } catch (Exception e) { // ignore builder.append(caller.getDetails()); } builder.append(")"); } return builder.toString(); } return principal == null ? null : principal.getName(); }
From source file:se.kth.csc.config.MockAuthConfig.java
@Bean @Autowired//from w w w .ja v a2 s. co m public AuthenticationProvider authenticationProvider( final AuthenticationUserDetailsService<Authentication> authenticationUserDetailsService) { return new AuthenticationProvider() { @Override public Authentication authenticate(final Authentication authentication) throws AuthenticationException { final UserDetails userDetails = authenticationUserDetailsService.loadUserDetails(authentication); return new Authentication() { @Override public Collection<? extends GrantedAuthority> getAuthorities() { return userDetails.getAuthorities(); } @Override public Object getCredentials() { return authentication.getCredentials(); } @Override public Object getDetails() { return authentication.getDetails(); } public UserDetails getUserDetails() { return userDetails; } @Override public Object getPrincipal() { return userDetails; } @Override public boolean isAuthenticated() { return authentication.isAuthenticated(); } @Override public void setAuthenticated(boolean isAuthenticated) throws IllegalArgumentException { authentication.setAuthenticated(isAuthenticated); } @Override public String getName() { return authentication.getName(); } }; } @Override public boolean supports(Class<?> authentication) { return true; } }; }
From source file:org.taverna.server.master.identity.StrippedDownAuthProvider.java
/** * Creates a successful {@link Authentication} object. * <p>/*from ww w. j a va 2 s . c o m*/ * Protected so subclasses can override. * </p> * <p> * Subclasses will usually store the original credentials the user supplied * (not salted or encoded passwords) in the returned * <code>Authentication</code> object. * </p> * * @param principal * that should be the principal in the returned object (defined * by the {@link #isForcePrincipalAsString()} method) * @param authentication * that was presented to the provider for validation * @param user * that was loaded by the implementation * * @return the successful authentication token */ private Authentication createSuccessAuthentication(Object principal, Authentication authentication, UserDetails user) { /* * Ensure we return the original credentials the user supplied, so * subsequent attempts are successful even with encoded passwords. Also * ensure we return the original getDetails(), so that future * authentication events after cache expiry contain the details */ UsernamePasswordAuthenticationToken result = new UsernamePasswordAuthenticationToken(principal, authentication.getCredentials(), user.getAuthorities()); result.setDetails(authentication.getDetails()); return result; }
From source file:com.liangc.hq.base.service.permissions.BaseSessionInitializationStrategy.java
public void onAuthentication(Authentication authentication, HttpServletRequest request, HttpServletResponse response) throws SessionAuthenticationException { final boolean debug = log.isDebugEnabled(); if (debug)// w w w . j a va2 s.com log.debug("Initializing UI session parameters..."); boolean updateRoles = false; String username = authentication.getName(); //If this is an organization authentication (ldap\kerberos) we will add a 'org\' prefix to the //user name so we will know it's an organization user if (null != authentication.getDetails() && (authentication.getDetails() instanceof HQAuthenticationDetails)) { HQAuthenticationDetails authDetails = (HQAuthenticationDetails) authentication.getDetails(); if (authDetails.isUsingExternalAuth()) { username = HQConstants.ORG_AUTH_PREFIX + username; //If this is a Ldap user we will update his roles if (null != authentication.getPrincipal() && authentication.getPrincipal().getClass().getName().contains("Ldap")) { updateRoles = true; } } } try { // The following is logic taken from the old HQ Authentication Filter int sessionId = sessionManager.put(authzSubjectManager.findSubjectByName(username)); HttpSession session = request.getSession(); ServletContext ctx = session.getServletContext(); // look up the subject record AuthzSubject subj = authzBoss.getCurrentSubject(sessionId); boolean needsRegistration = false; if (subj == null || updateRoles) { try { AuthzSubject overlord = authzSubjectManager.getOverlordPojo(); if (null == subj) { needsRegistration = true; subj = authzSubjectManager.createSubject(overlord, username, true, HQConstants.ApplicationName, "", "", "", "", "", "", false); } //For LDAP users we first want to remove all the existing 'LDAP' roles and then add the current roles he belongs to. //We are doing that because for LDAP users we do an automatic mapping of the roles according to the group the //user belongs to, and if the user has been removed or added from some group we want this to be reflected in his roles. if (updateRoles) { Collection<RoleValue> roles = roleManager.getRoles(subj, PageControl.PAGE_ALL); for (RoleValue role : roles) { String roleName = role.getName().toLowerCase(); if (roleName.startsWith(HQConstants.ORG_AUTH_PREFIX)) { roleManager.removeSubjects(authzSubjectManager.getOverlordPojo(), role.getId(), new Integer[] { subj.getId() }); } } } //every user has ROLE_HQ_USER. If other roles assigned, automatically assign them to new user if (authentication.getAuthorities().size() > 1) { Collection<Role> roles = roleManager.getAllRoles(); for (GrantedAuthority authority : authentication.getAuthorities()) { if (authority.getAuthority().equals("ROLE_HQ_USER")) { continue; } for (Role role : roles) { String roleName = role.getName().toLowerCase(); String ldapRoleName = ""; if (roleName.startsWith(HQConstants.ORG_AUTH_PREFIX)) { ldapRoleName = roleName.substring(roleName.indexOf(HQConstants.ORG_AUTH_PREFIX) + HQConstants.ORG_AUTH_PREFIX.length()).trim(); } if ((("ROLE_" + role.getName()).equalsIgnoreCase(authority.getAuthority())) || (("ROLE_" + ldapRoleName).equalsIgnoreCase(authority.getAuthority()))) { roleManager.addSubjects(authzSubjectManager.getOverlordPojo(), role.getId(), new Integer[] { subj.getId() }); } } } } } catch (ApplicationException e) { throw new SessionAuthenticationException("Unable to add user to authorization system"); } sessionId = sessionManager.put(subj); } else { needsRegistration = subj.getEmailAddress() == null || subj.getEmailAddress().length() == 0; } userAuditFactory.loginAudit(subj); AuthzSubjectValue subject = subj.getAuthzSubjectValue(); // figure out if the user has a principal boolean hasPrincipal = authBoss.isUser(sessionId, subject.getName()); ConfigResponse preferences = needsRegistration ? new ConfigResponse() : getUserPreferences(ctx, sessionId, subject.getId(), authzBoss); WebUser webUser = new WebUser(subject, sessionId, preferences, hasPrincipal); // Add WebUser to Session session.setAttribute(Constants.WEBUSER_SES_ATTR, webUser); if (debug) log.debug("WebUser object created and stashed in the session"); // TODO - We should use Spring Security for handling user // permissions... Map<String, Boolean> userOperationsMap = new HashMap<String, Boolean>(); if (webUser.getPreferences().getKeys().size() > 0) { userOperationsMap = loadUserPermissions(webUser.getSessionId(), authzBoss); } session.setAttribute(Constants.USER_OPERATIONS_ATTR, userOperationsMap); if (debug) log.debug("Stashing user operations in the session"); if (debug && needsRegistration) { log.debug("Authentic user but no HQ entity, must have authenticated outside of " + "HQ...needs registration"); } } catch (SessionException e) { if (debug) { log.debug("Authentication of user {" + username + "} failed due to an session error."); } throw new SessionAuthenticationException("login.error.application"); } catch (PermissionException e) { if (debug) { log.debug("Authentication of user {" + username + "} failed due to an permissions error."); } throw new SessionAuthenticationException("login.error.application"); } }
From source file:com.ctb.prism.login.security.provider.AbstractUserDetailsAuthenticationProvider.java
/** * Creates a successful {@link Authentication} object.<p>Protected so subclasses can override.</p> * <p>Subclasses will usually store the original credentials the user supplied (not salted or encoded * passwords) in the returned <code>Authentication</code> object.</p> * * @param principal that should be the principal in the returned object (defined by the {@link * #isForcePrincipalAsString()} method) * @param authentication that was presented to the provider for validation * @param user that was loaded by the implementation * * @return the successful authentication token */// www . j av a 2 s. co m protected Authentication createSuccessAuthentication(Object principal, Authentication authentication, UserDetails user) { // Ensure we return the original credentials the user supplied, // so subsequent attempts are successful even with encoded passwords. // Also ensure we return the original getDetails(), so that future // authentication events after cache expiry contain the details UsernamePasswordAuthenticationToken result = new UsernamePasswordAuthenticationToken(principal, authentication.getCredentials(), authoritiesMapper.mapAuthorities(user.getAuthorities())); result.setDetails(authentication.getDetails()); return result; }
From source file:com.bac.accountserviceapp.data.mysql.MysqlAccountServiceAppSpringAuthenticationTest.java
private void authenticateOutcome(Authentication resultAuthentication, AccountServiceAuthenticationOutcome expOutcome) { Object authenticationDetails = resultAuthentication.getDetails(); assertNotNull(authenticationDetails); Class<?> expDetailsClass = AccountServiceAuthenticationOutcome.class; Class<?> resultDetailsClass = authenticationDetails.getClass(); assertEquals(expDetailsClass, resultDetailsClass); AccountServiceAuthenticationOutcome authenticationOutcome = (AccountServiceAuthenticationOutcome) authenticationDetails; assertEquals(expOutcome, authenticationOutcome); }