Example usage for org.springframework.security.core Authentication getName

List of usage examples for org.springframework.security.core Authentication getName

Introduction

In this page you can find the example usage for org.springframework.security.core Authentication getName.

Prototype

public String getName();

Source Link

Document

Returns the name of this principal.

Usage

From source file:org.mitre.openid.connect.token.TofuUserApprovalHandler.java

@Override
public AuthorizationRequest updateAfterApproval(AuthorizationRequest authorizationRequest,
        Authentication userAuthentication) {

    String userId = userAuthentication.getName();
    String clientId = authorizationRequest.getClientId();
    ClientDetails client = clientDetailsService.loadClientByClientId(clientId);

    // This must be re-parsed here because SECOAUTH forces us to call things in a strange order
    if (Boolean.parseBoolean(authorizationRequest.getApprovalParameters().get("user_oauth_approval"))) {

        authorizationRequest.setApproved(true);

        // process scopes from user input
        Set<String> allowedScopes = Sets.newHashSet();
        Map<String, String> approvalParams = authorizationRequest.getApprovalParameters();

        Set<String> keys = approvalParams.keySet();

        for (String key : keys) {
            if (key.startsWith("scope_")) {
                //This is a scope parameter from the approval page. The value sent back should
                //be the scope string. Check to make sure it is contained in the client's
                //registered allowed scopes.

                String scope = approvalParams.get(key);
                Set<String> approveSet = Sets.newHashSet(scope);

                //Make sure this scope is allowed for the given client
                if (systemScopes.scopesMatch(client.getScope(), approveSet)) {

                    // If it's structured, assign the user-specified parameter
                    SystemScope systemScope = systemScopes.getByValue(scope);
                    if (systemScope != null && systemScope.isStructured()) {
                        String paramValue = approvalParams.get("scopeparam_" + scope);
                        allowedScopes.add(scope + ":" + paramValue);
                        // .. and if it's unstructured, we're all set
                    } else {
                        allowedScopes.add(scope);
                    }//from  w  w w  . j a va  2 s  .  co m
                }

            }
        }

        // inject the user-allowed scopes into the auth request
        authorizationRequest.setScope(allowedScopes);

        //Only store an ApprovedSite if the user has checked "remember this decision":
        String remember = authorizationRequest.getApprovalParameters().get("remember");
        if (!Strings.isNullOrEmpty(remember) && !remember.equals("none")) {

            Date timeout = null;
            if (remember.equals("one-hour")) {
                // set the timeout to one hour from now
                Calendar cal = Calendar.getInstance();
                cal.add(Calendar.HOUR, 1);
                timeout = cal.getTime();
            }

            ApprovedSite newSite = approvedSiteService.createApprovedSite(clientId, userId, timeout,
                    allowedScopes);
            String newSiteId = newSite.getId().toString();
            authorizationRequest.getExtensions().put(APPROVED_SITE, newSiteId);
        }

        setAuthTime(authorizationRequest);

    }

    return authorizationRequest;
}

From source file:org.sharetask.security.TaskAssigneePermission.java

@Override
public boolean isAllowed(final Authentication authentication, final Object targetDomainObject) {
    boolean result;
    Assert.isTrue(isAuthenticated(authentication), "UserAuthentication is not authenticated!");
    Assert.isTrue(targetDomainObject instanceof Long);
    final Long taskId = (Long) targetDomainObject;
    final String userName = authentication.getName();
    final Task task = this.taskRepository.read(taskId);
    if (task.getAssignee().getUsername().equals(userName)) {
        result = true;/*from   w w w.ja v  a 2s .c  om*/
    } else {
        result = false;
    }
    return result;
}

From source file:org.sharetask.security.TaskCreatorPermission.java

@Override
public boolean isAllowed(final Authentication authentication, final Object targetDomainObject) {
    boolean result;
    Assert.isTrue(isAuthenticated(authentication), "UserAuthentication is not authenticated!");
    Assert.isTrue(targetDomainObject instanceof Long);
    final Long taskId = (Long) targetDomainObject;
    final String userName = authentication.getName();
    final Task task = taskRepository.read(taskId);
    if (task.getCreatedBy().getUsername().equals(userName)) {
        result = true;// w ww  .  j av  a  2 s  .c o m
    } else {
        result = false;
    }
    return result;
}

From source file:com.formkiq.core.service.SpringSecurityService.java

/**
 * Get logged in username.//from w  w w  . j  a  v a 2  s.  co m
 * @return {@link String}
 */
public String getUsername() {
    Authentication auth = SecurityContextHolder.getContext().getAuthentication();

    return auth != null ? auth.getName() : null;
}

From source file:com.cruz.sec.config.ItemBasedLogoutSuccessHandler.java

@Override
public void onLogoutSuccess(HttpServletRequest request, HttpServletResponse response, Authentication a)
        throws IOException, ServletException {
    //Se enva a refrescar la ventana de todos los clientes para que cierre la sessin
    //        requestNodeJS.sendRequestWithUsernameAndMethod(a.getName(), "/session-close");
    try {// w w w .j  a  v  a 2  s  .c o m
        System.out.println("-----------------------------SESIN CERRADA (" + a.getName()
                + ") -----------------------------");
    } catch (NullPointerException as) {
    }
    //        response.sendRedirect("login?out=1");
    request.setAttribute("ERRORSESSION", "Sesi&oacute;n cerrada exitosamente");
    request.getRequestDispatcher("/login").forward(request, response);
    //        response.sendRedirect(request.getContextPath() + "/login");
    //        RequestDispatcher dispatcher = request.getRequestDispatcher("/login");
    //        dispatcher.forward(request, response);
}

From source file:com.devicehive.auth.rest.HttpAuthenticationFilter.java

@Override
public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain)
        throws IOException, ServletException {
    HttpServletRequest httpRequest = (HttpServletRequest) request;
    HttpServletResponse httpResponse = (HttpServletResponse) response;

    Optional<String> authHeader = Optional.ofNullable(httpRequest.getHeader(HttpHeaders.AUTHORIZATION));

    String resourcePath = new UrlPathHelper().getPathWithinApplication(httpRequest);
    logger.debug("Security intercepted request to {}", resourcePath);

    try {//w ww  .  j  av  a 2s.  com
        if (authHeader.isPresent()) {
            String header = authHeader.get();
            if (header.startsWith(Constants.BASIC_AUTH_SCHEME)) {
                processBasicAuth(header);
            } else if (header.startsWith(Constants.TOKEN_SCHEME)) {
                processJwtAuth(authHeader.get().substring(6).trim());
            }
        } else {
            processAnonymousAuth();
        }

        Authentication authentication = SecurityContextHolder.getContext().getAuthentication();
        if (authentication != null && authentication instanceof AbstractAuthenticationToken) {
            MDC.put("usrinf", authentication.getName());
            HiveAuthentication.HiveAuthDetails details = createUserDetails(httpRequest);
            ((AbstractAuthenticationToken) authentication).setDetails(details);
        }

        chain.doFilter(request, response);
    } catch (InternalAuthenticationServiceException e) {
        SecurityContextHolder.clearContext();
        logger.error("Internal authentication service exception", e);
        httpResponse.sendError(HttpServletResponse.SC_INTERNAL_SERVER_ERROR);
    } catch (AuthenticationException e) {
        SecurityContextHolder.clearContext();
        httpResponse.sendError(HttpServletResponse.SC_UNAUTHORIZED, e.getMessage());
    } finally {
        MDC.remove("usrinf");
    }
}

From source file:org.sharetask.security.TaskAssigneeOrCreatorPermission.java

@Override
public boolean isAllowed(final Authentication authentication, final Object targetDomainObject) {
    boolean result;
    Assert.isTrue(isAuthenticated(authentication), "UserAuthentication is not authenticated!");
    Assert.isTrue(targetDomainObject instanceof Long);
    final Long taskId = (Long) targetDomainObject;
    final String userName = authentication.getName();
    final Task task = this.taskRepository.read(taskId);
    if (task.getAssignee() != null && task.getAssignee().getUsername().equals(userName)) {
        result = true;//w w w .  j ava 2s .c o  m
    } else if (task.getCreatedBy() != null && task.getCreatedBy().getUsername().equals(userName)) {
        result = true;
    } else {
        result = false;
    }
    return result;
}

From source file:org.shredzone.cilla.service.security.CillaUserDetailsManager.java

@Override
public void changePassword(String oldPassword, String newPassword) {
    Authentication currentUser = SecurityContextHolder.getContext().getAuthentication();
    if (currentUser == null) {
        throw new AccessDeniedException("No user is logged in");
    }//from  w ww .  j a v  a2 s . c o  m

    String username = currentUser.getName();
    User user = userDao.fetchByLogin(username);
    if (user == null) {
        throw new AccessDeniedException("User without account");
    }

    try {
        userService.changePassword(user, oldPassword, newPassword);
    } catch (CillaServiceException ex) {
        throw new AccessDeniedException("Could not change password", ex);
    }
}

From source file:br.ufac.sion.audit.CustomRevisionEntityListener.java

@Override
public void newRevision(Object revisionEntity) {
    try {/*from w  w w . j  a v a2  s  .  c o m*/
        CustomRevisionEntity customRevisionEntity = (CustomRevisionEntity) revisionEntity;
        Authentication authentication = SecurityContextHolder.getContext().getAuthentication();
        System.out.println("authentication == null : " + (authentication == null));
        if (authentication == null) {
            customRevisionEntity.setUsername("Sion - tarefa automatizada!");
        } else {
            customRevisionEntity.setUsername(authentication.getName());
        }
        customRevisionEntity.setIp(InetAddress.getLocalHost().getHostAddress());
    } catch (Exception ex) {
        log.error("Erro de sistema (sion-web): " + ex.getMessage(), ex);
    }
}

From source file:com.companyname.services.PlatUserAuthenticationCache.java

public Authentication get(Authentication authentication) {
    Assert.notNull(authentication, "cann't retreive a null authentication");
    init();/*from   w  ww.j av  a 2s .  com*/
    String key = getHashKey(authentication);

    if (cache.containsKey(key)) {
        logger.info("authentication request is retreived from cache for user " + authentication.getName());
        return cache.get(key);
    } else {
        logger.info("authentication request is not found in cache for user " + authentication.getName());
        return null;
    }
}