List of usage examples for org.springframework.security.core Authentication getDetails
Object getDetails();
From source file:fr.xebia.audit.AuditAspect.java
protected String buildMessage(String template, Object invokedObject, Object[] args, Object returned, Throwable throwned, long durationInNanos) { try {//w w w .j a v a2 s. com Expression expression = expressionCache.get(template); if (expression == null) { expression = expressionParser.parseExpression(template, parserContext); expressionCache.put(template, expression); } String evaluatedMessage = expression.getValue(new RootObject(invokedObject, args, returned, throwned), String.class); StringBuilder msg = new StringBuilder(); SimpleDateFormat simpleDateFormat = (SimpleDateFormat) dateFormatPrototype.clone(); msg.append(simpleDateFormat.format(new Date())); msg.append(" ").append(evaluatedMessage); if (throwned != null) { msg.append(" threw '"); appendThrowableCauses(throwned, ", ", msg); msg.append("'"); } msg.append(" by "); Authentication authentication = SecurityContextHolder.getContext().getAuthentication(); if (authentication == null) { msg.append("anonymous"); } else { msg.append(authentication.getName()); if (authentication.getDetails() instanceof WebAuthenticationDetails) { WebAuthenticationDetails details = (WebAuthenticationDetails) authentication.getDetails(); msg.append(" coming from " + details.getRemoteAddress()); } } msg.append(" in ").append(TimeUnit.MILLISECONDS.convert(durationInNanos, TimeUnit.NANOSECONDS)) .append(" ms"); return msg.toString(); } catch (RuntimeException e) { StringBuilder msg = new StringBuilder("Exception evaluating template '" + template + "': "); appendThrowableCauses(e, ", ", msg); return msg.toString(); } }
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;/* www. j ava 2 s. co 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:com.bac.accountserviceapp.AccountServiceApp.java
@Override public AccountServiceAuthentication createLogin(AccountServiceAuthentication authentication) { Objects.requireNonNull(authentication, noAuthenticationMsg); ////from w w w. j a v a2 s . com // Is the application active... Application application = strategy.getApplication(authentication.getApplicationName()); if (application == null || !application.isEnabled()) { return setFailedCreateLoginAuthentication(authentication, NO_APPLICATION); } // ...and accepting registrations? if (!application.isRegistrationOpen()) { return setFailedCreateLoginAuthentication(authentication, APPLICATION_CLOSED); } // // Does the Principal already exist?... User user = strategy.getUser(authentication.getAccountKey()); if (user != null) { // validate it to see if we can proceed UsernamePasswordAuthenticationToken validation = new UsernamePasswordAuthenticationToken( authentication.getAccountKey(), authentication.getAccountPassword()); Authentication loginAuthentication = login(validation); if (loginAuthentication == null || !Objects.equals(AUTHENTICATED, loginAuthentication.getDetails())) { // // Can't create this account // return setFailedCreateLoginAuthentication(authentication, PRINCIPAL_EXISTS); } } // // ...does it have an application account? Account account = strategy.getAccountForApplication(authentication.getApplicationName(), authentication.getAccountKey()); if (account != null) { // // Can't create this account // return setFailedCreateLoginAuthentication(authentication, PRINCIPAL_EXISTS); } // Create Account/User as appropriate // Date createDate = new Date(System.currentTimeMillis()); if (user == null) { user = new SimpleUser(); user.setUserEmail(authentication.getAccountKey()); try { logger.info("Set the password to '{}'", authentication.getAccountPassword()); user.setUserPassword(authentication.getAccountPassword().getBytes()); } catch (NullPointerException e) { return setFailedCreateLoginAuthentication(authentication, BAD_CREDENTIALS); } user.setUserPassword(encoder.encode(authentication.getAccountPassword()).getBytes()); user.setUserName(authentication.getAccountName()); user.setEnabled(false); user.setCreateDate(createDate); user = strategy.newUser(user); if (user == null) { return setFailedCreateLoginAuthentication(authentication, UNKNOWN_PRINCIPAL); } } // create User account account = new SimpleAccount(); String accountResource = authentication.getAccountResource() instanceof String ? (String) authentication.getAccountResource() : ""; account.setApplicationId(application.getId()); account.setResourceName(accountResource); account.setEnabled(false); account.setCreateDate(createDate); AccountUser accountUser = strategy.newAccountUser(account, user); if (accountUser == null) { return setFailedCreateLoginAuthentication(authentication, NO_ROLE); } authentication.setAccountRole(strategy.getDefaultAccountServiceRole()); authentication.setAuthenticationOutcome(PENDING_CREATION); // Clear down the password authentication.setAccountPassword(null); return authentication; }
From source file:org.carewebframework.security.spring.AbstractSecurityService.java
/** * Returns the authenticated user object from the current security context. * /*from www . j a v a 2s . c om*/ * @return The authenticated user object, or null if none present. */ @Override public IUser getAuthenticatedUser() { Authentication authentication = getAuthentication(); Object details = authentication == null ? null : authentication.getDetails(); return (details instanceof CWFAuthenticationDetails) ? (IUser) ((CWFAuthenticationDetails) details).getDetail("user") : null; }
From source file:eu.trentorise.smartcampus.permissionprovider.controller.AuthController.java
/** * Handles the redirection to the specified target after the login has been * performed. Given the user data collected during the login, updates the * user information in DB and populates the security context with the user * credentials.//from w w w . j av a 2 s . c o m * * @param authorityUrl * the authority used by the user to sign in. * @param target * target functionality address. * @param req * @return * @throws Exception */ @RequestMapping("/eauth/{authorityUrl}") public ModelAndView forward(@PathVariable String authorityUrl, @RequestParam(required = false) String target, HttpServletRequest req, HttpServletResponse res) throws Exception { List<GrantedAuthority> list = Collections .<GrantedAuthority>singletonList(new SimpleGrantedAuthority("ROLE_USER")); String nTarget = (String) req.getSession().getAttribute("redirect"); if (nTarget == null) return new ModelAndView("redirect:/logout"); String clientId = (String) req.getSession().getAttribute("client_id"); if (clientId != null) { Set<String> idps = clientDetailsAdapter.getIdentityProviders(clientId); if (!idps.contains(authorityUrl)) { Map<String, Object> model = new HashMap<String, Object>(); model.put("message", "incorrect identity provider for the app"); return new ModelAndView("oauth_error", model); } } // HOOK for testing if (testMode && target == null) { target = "/eauth/" + authorityUrl + "?target=" + URLEncoder.encode(nTarget, "UTF8") + "&OIDC_CLAIM_email=my@mail&OIDC_CLAIM_given_name=name&OIDC_CLAIM_family_name=surname"; } else { if (!testMode && nTarget != null) { target = nTarget; } Authentication old = SecurityContextHolder.getContext().getAuthentication(); if (old != null && old instanceof UsernamePasswordAuthenticationToken) { if (!authorityUrl.equals(old.getDetails())) { new SecurityContextLogoutHandler().logout(req, res, old); SecurityContextHolder.getContext().setAuthentication(null); req.getSession().setAttribute("redirect", target); req.getSession().setAttribute("client_id", clientId); return new ModelAndView("redirect:/eauth/" + authorityUrl); // return new ModelAndView("redirect:/logout"); } } List<NameValuePair> pairs = URLEncodedUtils.parse(URI.create(nTarget), "UTF-8"); eu.trentorise.smartcampus.permissionprovider.model.User userEntity = null; if (old != null && old instanceof UsernamePasswordAuthenticationToken) { String userId = old.getName(); userEntity = userRepository.findOne(Long.parseLong(userId)); } else { userEntity = providerServiceAdapter.updateUser(authorityUrl, toMap(pairs), req); } UserDetails user = new User(userEntity.getId().toString(), "", list); AbstractAuthenticationToken a = new UsernamePasswordAuthenticationToken(user, null, list); a.setDetails(authorityUrl); SecurityContextHolder.getContext().setAuthentication(a); } return new ModelAndView("redirect:" + target); }
From source file:com.rockagen.gnext.service.spring.security.extension.BasicPrincipal.java
/** * Instantiates a new smart principal./*from w w w . j a v a 2 s .co m*/ * * @param authentication * the authentication */ public BasicPrincipal(Authentication authentication) { Assert.notNull(authentication, "authentication cannot be null (violation of interface contract)"); String username = null; if (authentication.getPrincipal() instanceof UserDetails) { username = ((UserDetails) authentication.getPrincipal()).getUsername(); } else { username = (String) authentication.getPrincipal(); } String ip = ((BasicWebAuthenticationDetails) authentication.getDetails()).getRemoteAddress(); this.username = username; this.ip = ip; }
From source file:org.musicrecital.service.UserSecurityAdvice.java
private User getCurrentUser(Authentication auth, UserManager userManager) { User currentUser;//from www . j a v a 2s . c o m if (auth.getPrincipal() instanceof LdapUserDetails) { LdapUserDetails ldapDetails = (LdapUserDetails) auth.getPrincipal(); String username = ldapDetails.getUsername(); currentUser = userManager.getUserByUsername(username); } else if (auth.getPrincipal() instanceof UserDetails) { currentUser = (User) auth.getPrincipal(); } else if (auth.getDetails() instanceof UserDetails) { currentUser = (User) auth.getDetails(); } else { throw new AccessDeniedException("User not properly authenticated."); } return currentUser; }
From source file:com.bac.accountserviceapp.AccountServiceApp.java
@Override public AccountServiceAuthentication login(AccountServiceAuthentication authentication) { ////from w w w . j av a2s .c om // Validate authentication content // Objects.requireNonNull(authentication, noAuthenticationMsg); Objects.requireNonNull(authentication.getApplicationName(), noApplicationName); Objects.requireNonNull(authentication.getAccountKey(), incompleteLogin); Objects.requireNonNull(authentication.getAccountPassword(), incompleteLogin); // // Clear out any pre-set values // authentication.setAccountResource(null); authentication.setAccountRole(null); authentication.setAuthenticationOutcome(null); // // // UsernamePasswordAuthenticationToken authenticationToken = new UsernamePasswordAuthenticationToken( authentication.getAccountKey(), authentication.getAccountPassword()); Authentication loginToken = login(authenticationToken); authentication.setAccountPassword(null); // // If the token is not authenticated then return // AccountServiceAuthenticationOutcome loginOutcome = (AccountServiceAuthenticationOutcome) loginToken .getDetails(); if (loginOutcome != AUTHENTICATED) { authentication.setAuthenticationOutcome(loginOutcome); return authentication; } // // Temporarily set outcome to no role and then verify that // authentication.setAuthenticationOutcome(NO_ROLE); final String expectedApplicationName = authentication.getApplicationName(); if (loginToken.getAuthorities() != null) { for (GrantedAuthority authority : loginToken.getAuthorities()) { String authorityString = authority.getAuthority(); matcher = pattern.matcher(authorityString); if (!matcher.matches() || matcher.groupCount() != AUTHORITY_PATTERN_COUNT) { continue; } String authorityApplicationName = matcher.group(AUTHORITY_PATTERN_APPLICATION_ITEM); String authorityRole = matcher.group(AUTHORITY_PATTERN_ROLE_ITEM); if (!expectedApplicationName.equals(authorityApplicationName)) { continue; } // // Look up the AccountRole and add it to the outgoing authentication // AccountServiceRole accountRole; try { accountRole = AccountServiceRole.valueOf(authorityRole); } catch (IllegalArgumentException e) { logger.warn("Unable to find a valid Account Servie Role for '{}'", authorityRole); accountRole = null; } authentication.setAccountRole(accountRole); authentication.setAuthenticationOutcome(AUTHENTICATED); break; } } // // If NO_ROLE is overidden then populate the outgoing authentication with the Account resource // if (authentication.getAuthenticationOutcome() == AUTHENTICATED) { Account account = strategy.getAccountForApplication(expectedApplicationName, authentication.getAccountKey()); if (account == null) { authentication.setAuthenticationOutcome(NO_RESOURCE); } else { authentication.setAccountResource(account.getResourceName()); } } // // Complete so return // return authentication; }
From source file:it.smartcommunitylab.aac.controller.AuthController.java
/** * Handles the redirection to the specified target after the login has been * performed. Given the user data collected during the login, updates the * user information in DB and populates the security context with the user * credentials.// ww w . j a v a 2 s. c o m * * @param authorityUrl * the authority used by the user to sign in. * @param target * target functionality address. * @param req * @return * @throws Exception */ @RequestMapping("/eauth/{authorityUrl}") public ModelAndView forward(@PathVariable String authorityUrl, @RequestParam(required = false) String target, HttpServletRequest req, HttpServletResponse res) { String nTarget = (String) req.getSession().getAttribute("redirect"); if (nTarget == null) return new ModelAndView("redirect:/logout"); String clientId = (String) req.getSession().getAttribute(OAuth2Utils.CLIENT_ID); if (clientId != null) { Set<String> idps = clientDetailsAdapter.getIdentityProviders(clientId); if (!idps.contains(authorityUrl)) { Map<String, Object> model = new HashMap<String, Object>(); model.put("message", "incorrect identity provider for the app"); return new ModelAndView("oauth_error", model); } } AACOAuthRequest oauthRequest = (AACOAuthRequest) req.getSession() .getAttribute(Config.SESSION_ATTR_AAC_OAUTH_REQUEST); if (oauthRequest != null) { oauthRequest.setAuthority(authorityUrl); req.getSession().setAttribute(Config.SESSION_ATTR_AAC_OAUTH_REQUEST, oauthRequest); } target = nTarget; Authentication old = SecurityContextHolder.getContext().getAuthentication(); if (old != null && old instanceof AACAuthenticationToken) { AACOAuthRequest oldDetails = (AACOAuthRequest) old.getDetails(); if (oldDetails != null && !authorityUrl.equals(oldDetails.getAuthority())) { new SecurityContextLogoutHandler().logout(req, res, old); SecurityContextHolder.getContext().setAuthentication(null); req.getSession().setAttribute("redirect", target); req.getSession().setAttribute(OAuth2Utils.CLIENT_ID, clientId); return new ModelAndView("redirect:" + Utils.filterRedirectURL(authorityUrl)); } } List<NameValuePair> pairs = URLEncodedUtils.parse(URI.create(nTarget), "UTF-8"); it.smartcommunitylab.aac.model.User userEntity = null; if (old != null && (old instanceof AACAuthenticationToken || old instanceof RememberMeAuthenticationToken)) { String userId = old.getName(); userEntity = userRepository.findOne(Long.parseLong(userId)); } else { userEntity = providerServiceAdapter.updateUser(authorityUrl, toMap(pairs), req); } List<GrantedAuthority> list = roleManager.buildAuthorities(userEntity); UserDetails user = new User(userEntity.getId().toString(), "", list); AbstractAuthenticationToken a = new AACAuthenticationToken(user, null, authorityUrl, list); a.setDetails(oauthRequest); SecurityContextHolder.getContext().setAuthentication(a); if (rememberMeServices != null) { rememberMeServices.loginSuccess(req, res, a); } return new ModelAndView("redirect:" + target); }