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:de.hybris.telcotrail.storefront.security.AcceleratorAuthenticationProvider.java

@Override
public Authentication authenticate(final Authentication authentication) throws AuthenticationException {
    final String username = (authentication.getPrincipal() == null) ? "NONE_PROVIDED"
            : authentication.getName();

    if (getBruteForceAttackCounter().isAttack(username)) {
        try {//from  ww  w  .  ja v a2  s  .  c  o m
            final UserModel userModel = getUserService().getUserForUID(StringUtils.lowerCase(username));
            userModel.setLoginDisabled(true);
            getModelService().save(userModel);
            bruteForceAttackCounter.resetUserCounter(userModel.getUid());
        } catch (final UnknownIdentifierException e) {
            LOG.warn("Brute force attack attempt for non existing user name " + username);
        } finally {
            throw new BadCredentialsException(
                    messages.getMessage("CoreAuthenticationProvider.badCredentials", "Bad credentials"));
        }
    }

    // check if the user of the cart matches the current user and if the
    // user is not anonymous. If otherwise, remove delete the session cart as it might
    // be stolen / from another user
    final String sessionCartUserId = getCartService().getSessionCart().getUser().getUid();

    if (!username.equals(sessionCartUserId)
            && !sessionCartUserId.equals(userService.getAnonymousUser().getUid())) {
        getCartService().setSessionCart(null);
    }

    return super.authenticate(authentication);
}

From source file:business.security.CustomPermissionEvaluator.java

@Override
public boolean hasPermission(Authentication authentication, Serializable targetId, String targetType,
        Object permission) {/* ww  w  .ja va  2s . c o m*/
    log.trace("hasPermission[2]: user = " + authentication.getName() + ", targetId = " + targetId.toString()
            + ", targetType = " + targetType + ", permission = " + permission.toString());
    return false;
}

From source file:org.osiam.auth.login.internal.InternalAuthenticationProvider.java

@Override
public Authentication authenticate(Authentication authentication) {
    Preconditions.checkArgument(authentication instanceof InternalAuthentication,
            "InternalAuthenticationProvider only supports InternalAuthentication.");

    String username = authentication.getName();
    String password = (String) authentication.getCredentials();

    if (Strings.isNullOrEmpty(username)) {
        throw new BadCredentialsException("InternalAuthenticationProvider: Empty Username");
    }/*from w  w  w.j  a v a2 s.c o  m*/

    if (Strings.isNullOrEmpty(password)) {
        throw new BadCredentialsException("InternalAuthenticationProvider: Empty Password");
    }

    // Determine username
    User user = resourceServerConnector.getUserByUsername(username);

    if (user == null) {
        throw new BadCredentialsException("The user with the username '" + username + "' not exists!");
    }

    String hashedPassword = passwordEncoder.encodePassword(password, user.getId());

    if (resourceServerConnector.searchUserByUserNameAndPassword(username, hashedPassword) == null) {
        throw new BadCredentialsException("Bad credentials");
    }

    User authUser = new User.Builder(username).setId(user.getId()).build();

    List<GrantedAuthority> grantedAuthorities = new ArrayList<GrantedAuthority>();

    for (Role role : user.getRoles()) {
        grantedAuthorities.add(new SimpleGrantedAuthority(role.getValue()));
    }

    return new InternalAuthentication(authUser, password, grantedAuthorities);
}

From source file:com.alliander.osgp.shared.security.KeycloakAuthenticationManager.java

@Override
public Authentication authenticate(final Authentication authentication) {
    if (authentication == null) {
        LOGGER.debug(NULL_AUTHENTICATION);
        throw new BadCredentialsException(NULL_AUTHENTICATION);
    }/* ww w.  ja  v a2  s . c om*/

    final String username = authentication.getName();

    final LoginRequest loginRequest = new LoginRequest(username, null, this.application);
    LoginResponse loginResponse = null;

    try {
        loginResponse = this.authenticationClient.loginMellon(loginRequest, this.mellonSharedSecret);
    } catch (final Exception e) {
        LOGGER.debug(LOGIN_ATTEMPT_FAILED, e);
        throw new BadCredentialsException(LOGIN_ATTEMPT_FAILED, e);
    }

    if (loginResponse == null) {
        LOGGER.debug(LOGIN_RESPONSE_IS_NULL);
        throw new BadCredentialsException(LOGIN_RESPONSE_IS_NULL);
    }

    if (!loginResponse.getFeedbackMessage().equals(OK)) {
        LOGGER.debug(LOGIN_RESPONSE_IS_NOT_OK);
        throw new BadCredentialsException(LOGIN_RESPONSE_IS_NOT_OK);
    }

    return this.createCustomAuthenticationInstance(username, loginResponse);
}

From source file:com.sf.springsecurityregistration1.web.controllers.RegistrationController.java

/**
* Method is used to support login page./*  w w w  .  java 2s  .  c  o m*/
*
* @param error
* @param logout
* @return model of the login page
*/
@RequestMapping(value = { "/login", "/user/**/login" }, method = RequestMethod.GET)
public ModelAndView login(@RequestParam(value = "error", required = false) String error,
        @RequestParam(value = "logout", required = false) String logout) {

    System.out.println("login: logout = " + logout);
    ModelAndView model = new ModelAndView();
    if (error != null) {
        model.addObject("error", "Invalid username and password!");
    }

    if (logout != null) {
        model.addObject("msg", "You've been logged out successfully.");
    }
    model.setViewName("login");
    Authentication auth = SecurityContextHolder.getContext().getAuthentication();
    String name = auth.getName(); //get logged in username

    return model;

}

From source file:com.castlemock.web.basis.web.mvc.controller.AbstractController.java

/**
 * Get the current logged in user username
 * @return The username of the current logged in user
 * @see User//  ww w.  j ava 2s  .  c om
 */
protected String getLoggedInUsername() {
    final Authentication authentication = SecurityContextHolder.getContext().getAuthentication();
    if (authentication == null) {
        return ANONYMOUS_USER; // Should never happened except during unit tests
    }
    return authentication.getName();
}

From source file:it.geosolutions.geostore.services.rest.security.TokenAuthenticationFilter.java

protected void authenticate(HttpServletRequest req) {
    String authHeader = req.getHeader(tokenHeader);

    if (authHeader != null && authHeader.trim().toUpperCase().startsWith(tokenPrefix.toUpperCase())) {
        String token = authHeader.substring(tokenPrefix.length()).trim();
        Authentication auth;
        try {//from   ww  w. j  a  v  a 2  s . c  om
            auth = getCache().get(token).orNull();
            if (auth != null) {
                LOGGER.info("User authenticated using token: " + auth.getName());
                SecurityContextHolder.getContext().setAuthentication(auth);
            }
        } catch (ExecutionException e) {
            LOGGER.error("Error authenticating token", e);
        }
    }

}

From source file:org.openinfinity.sso.security.spring.InjectableSecurityContextFilterBean.java

private void injectIdentityBasedSecurityContext(String sessionId) {
    SecurityContext securityContext = SecurityContextHolder.createEmptyContext();
    SecurityContextHolder.setContext(securityContext);
    Authentication authentication = IdentityContext.loadIdentity(sessionId);
    SecurityContextHolder.getContext().setAuthentication(authentication);
    LOGGER.info("SecurityContext created for active session based on IdentityContext for user: "
            + authentication.getName());
}

From source file:de.iew.services.impl.AuditServiceImpl.java

protected void persistMessage(Object source, Date date, Authentication authentication, Severity severity,
        String message, Throwable throwable) {
    String principal = null;/*from w  w  w . j a  v  a  2s  . c o  m*/

    if (authentication != null) {
        principal = authentication.getName();
    }

    AuditEventMessage auditEventMessage;
    try {
        auditEventMessage = new AuditEventMessage();
        auditEventMessage.setTimestamp(date);
        auditEventMessage.setPrincipal(principal);
        auditEventMessage.setSeverity(severity);
        auditEventMessage.setMessage(toAuditEventMessage(message, throwable));

        this.auditEventMessageDao.save(auditEventMessage);
    } catch (Exception e) {
        if (log.isFatalEnabled()) {
            log.fatal("AuditEvent was not persisted due to an unexpected error", e);
        }
    }
}

From source file:com.alliander.osgp.shared.security.MellonTokenProcessingFilter.java

private boolean authenticationExistsForUsername(final Authentication authentication, final String username) {

    final boolean userIsAuthenticated = authentication != null && username != null
            && username.equals(authentication.getName());

    if (userIsAuthenticated) {
        LOGGER.info(/*from  ww w .j  av  a2  s . c om*/
                "SecurityContext already has an authentication for user {}, stop further Mellon authentication",
                username);
    }

    return userIsAuthenticated;
}