List of usage examples for org.springframework.security.oauth2.provider OAuth2Authentication getPrincipal
public Object getPrincipal()
From source file:com.ar.dev.tierra.api.config.security.CustomTokenEnhancer.java
@Override public OAuth2AccessToken enhance(OAuth2AccessToken accessToken, OAuth2Authentication authentication) { User user = (User) authentication.getPrincipal(); final Map<String, Object> additionalInfo = new HashMap<>(); String hashedUsername = passwordEncoder.encode(user.getUsername()); additionalInfo.put("role", authentication.getAuthorities()); ((DefaultOAuth2AccessToken) accessToken).setAdditionalInformation(additionalInfo); return accessToken; }
From source file:am.ik.categolj2.domain.service.token.Categolj2TokenEnhancer.java
@Override public OAuth2AccessToken enhance(OAuth2AccessToken accessToken, OAuth2Authentication authentication) { if (authentication == null || authentication.getPrincipal() == null) { return accessToken; }/* www .j a v a 2 s . c o m*/ Categolj2UserDetails userDetails = (Categolj2UserDetails) authentication.getPrincipal(); DefaultOAuth2AccessToken defaultOAuth2AccessToken = (DefaultOAuth2AccessToken) accessToken; Map<String, Object> additionalInformation = new HashMap<>(); User user = userDetails.getUser(); user.setPassword(null); additionalInformation.put("user", user); defaultOAuth2AccessToken.setAdditionalInformation(additionalInformation); return defaultOAuth2AccessToken; }
From source file:com.ar.dev.tierra.api.config.security.CustomLogoutSuccessHandler.java
@Override public void onLogoutSuccess(HttpServletRequest request, HttpServletResponse response, Authentication authentication) throws IOException, ServletException { String token = request.getHeader(HEADER_AUTHORIZATION); if (token != null && token.startsWith(BEARER_AUTHENTICATION)) { OAuth2AccessToken oAuth2AccessToken = tokenStore.readAccessToken(token.split(" ")[1]); if (oAuth2AccessToken != null) { Calendar cal = Calendar.getInstance(); Date date = cal.getTime(); Map<String, Object> map = oAuth2AccessToken.getAdditionalInformation(); OAuth2Authentication auth = tokenStore.readAuthentication(oAuth2AccessToken); User user = (User) auth.getPrincipal(); Usuarios u = usuariosDAO.findUsuarioByUsername(user.getUsername()); u.setUltimaConexion(date);// ww w . j a va 2 s . com usuariosDAO.updateUsuario(u); tokenStore.removeAccessToken(oAuth2AccessToken); response.setStatus(HttpServletResponse.SC_OK); } else { response.setStatus(HttpServletResponse.SC_INTERNAL_SERVER_ERROR); } } }
From source file:org.osiam.auth.token.OsiamCompositeTokenGranter.java
public OAuth2AccessToken grant(String grantType, AuthorizationRequest authorizationRequest) { OAuth2AccessToken grant = super.grant(grantType, authorizationRequest); if (grant != null) { DefaultOAuth2AccessToken token = (DefaultOAuth2AccessToken) grant; Map<String, Object> additionalInformation = new HashMap<String, Object>(); additionalInformation.put("access_token", token.getValue()); additionalInformation.put("expires_at", token.getExpiration()); StringBuilder scopes = new StringBuilder(); for (String scopeString : token.getScope()) { scopes.append(scopeString).append(" "); }//from w w w.ja v a 2 s. c o m additionalInformation.put("scopes", scopes); if (token.getRefreshToken() != null) { DefaultExpiringOAuth2RefreshToken refreshToken = (DefaultExpiringOAuth2RefreshToken) token .getRefreshToken(); additionalInformation.put("refresh_token", refreshToken.getValue()); additionalInformation.put("refresh_token_expires_at", refreshToken.getExpiration()); } additionalInformation.put("token_type", token.getTokenType()); additionalInformation.put("client_id", authorizationRequest.getClientId()); OAuth2Authentication auth = tokenServices.loadAuthentication(token.getValue()); if (auth.getUserAuthentication() != null && auth.getPrincipal() instanceof User) { User user = (User) auth.getPrincipal(); additionalInformation.put("user_name", user.getUserName()); additionalInformation.put("user_id", user.getId()); } token.setAdditionalInformation(additionalInformation); } return grant; }
From source file:com.create.security.oauth2.provider.token.AuthenticatedUserTokenEnhancer.java
@Override public OAuth2AccessToken enhance(final OAuth2AccessToken accessToken, final OAuth2Authentication authentication) { final DefaultOAuth2AccessToken enhancedAccessToken = new DefaultOAuth2AccessToken(accessToken); enhancedAccessToken.getAdditionalInformation().put(AUTHENTICATED_USER, authentication.getPrincipal()); return enhancedAccessToken; }
From source file:org.openlmis.fulfillment.util.AuthenticationHelper.java
/** * Method returns current user based on Spring context * and fetches his data from reference-data service. * * @return UserDto entity of current user. * @throws AuthenticationException if user cannot be found. *///from w w w.j a va2 s . c o m public UserDto getCurrentUser() { OAuth2Authentication authentication = (OAuth2Authentication) SecurityContextHolder.getContext() .getAuthentication(); UserDto user = null; if (!authentication.isClientOnly()) { UUID userId = (UUID) authentication.getPrincipal(); user = userReferenceDataService.findOne(userId); if (user == null) { throw new AuthenticationException(USER_NOT_FOUND, userId.toString()); } } return user; }
From source file:com.ar.dev.tierra.api.controller.UsuariosController.java
@RequestMapping(value = "/detail", method = RequestMethod.GET, produces = MediaType.APPLICATION_JSON_VALUE) public ResponseEntity<Usuarios> detailsUsuario(OAuth2Authentication authentication) { User user = (User) authentication.getPrincipal(); Usuarios u = facadeService.getUsuariosDAO().findUsuarioByUsername(user.getUsername()); if (u == null) { throw new BadCredentialsException("Bad Credentials"); } else {/*from w ww . jav a 2 s .c om*/ return new ResponseEntity(u, HttpStatus.OK); } }
From source file:com.ar.dev.tierra.api.controller.UsuariosController.java
@RequestMapping(value = "/updateUsuario", method = RequestMethod.POST) public ResponseEntity<?> uploadFile(@RequestBody Usuarios usuario, OAuth2Authentication authentication) { try {/*from w w w.j a v a 2 s .c om*/ User user = (User) authentication.getPrincipal(); Usuarios u = facadeService.getUsuariosDAO().findUsuarioByUsername(user.getUsername()); if (u.getIdUsuario() == usuario.getIdUsuario() && u.getUsername().equals(usuario.getUsername()) && u.getRoles().getNombreRol().equals(usuario.getRoles().getNombreRol()) && u.getRoles().getIdRol() == usuario.getRoles().getIdRol()) { usuario.setIdUsuarioModificacion(u.getIdUsuario()); usuario.setFechaModificacion(new Date()); facadeService.getUsuariosDAO().updateUsuario(usuario); } else { return new ResponseEntity<>(HttpStatus.BAD_REQUEST); } } catch (Exception e) { return new ResponseEntity<>(HttpStatus.BAD_REQUEST); } return new ResponseEntity<>(HttpStatus.OK); }
From source file:com.ar.dev.tierra.api.controller.UsuariosController.java
@RequestMapping(value = "/updatePhoto", method = RequestMethod.POST) public @ResponseBody ResponseEntity<?> updateUsuario(@RequestParam("file") MultipartFile file, OAuth2Authentication authentication) { try {/*from w w w . ja va2 s .c o m*/ User user = (User) authentication.getPrincipal(); Usuarios u = facadeService.getUsuariosDAO().findUsuarioByUsername(user.getUsername()); if (file.getName().isEmpty() == false) { InputStream inputStream = file.getInputStream(); ByteArrayOutputStream buffer = new ByteArrayOutputStream(); int nRead; byte[] bytes = new byte[16384]; while ((nRead = inputStream.read(bytes, 0, bytes.length)) != -1) { buffer.write(bytes, 0, nRead); } buffer.flush(); u.setImagen(buffer.toByteArray()); facadeService.getUsuariosDAO().updateUsuario(u); } } catch (Exception e) { return new ResponseEntity<>(HttpStatus.BAD_REQUEST); } return new ResponseEntity<>(HttpStatus.OK); }
From source file:com.netflix.genie.web.security.oauth2.pingfederate.PingFederateRemoteTokenServices.java
/** * {@inheritDoc}//from w ww. j a v a 2 s . co m */ @Override public OAuth2Authentication loadAuthentication(final String accessToken) throws AuthenticationException, InvalidTokenException { final long start = System.nanoTime(); try { final MultiValueMap<String, String> formData = new LinkedMultiValueMap<>(); formData.add(TOKEN_NAME_KEY, accessToken); formData.add(CLIENT_ID_KEY, this.clientId); formData.add(CLIENT_SECRET_KEY, this.clientSecret); formData.add(GRANT_TYPE_KEY, GRANT_TYPE); final Map<String, Object> map = this.postForMap(this.checkTokenEndpointUrl, formData); if (map.containsKey(ERROR_KEY)) { final String error = map.get(ERROR_KEY).toString(); log.debug("Validating the token produced an error: {}", error); throw new InvalidTokenException(error); } Assert.state(map.containsKey(CLIENT_ID_KEY), "Client id must be present in response from auth server"); Assert.state(map.containsKey(SCOPE_KEY), "No scopes included in response from authentication server"); this.convertScopes(map); final OAuth2Authentication authentication = this.converter.extractAuthentication(map); log.info("User {} authenticated with authorities {}", authentication.getPrincipal(), authentication.getAuthorities()); return authentication; } finally { final long finished = System.nanoTime(); this.authenticationTimer.record(finished - start, TimeUnit.NANOSECONDS); } }