Java Code Examples for org.springframework.security.core.Authentication#getName()

The following examples show how to use org.springframework.security.core.Authentication#getName() . You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example. You may check out the related API usage on the sidebar.
Example 1
Source File: PersistentTokenRememberMeServices.java    From TeamDojo with Apache License 2.0 6 votes vote down vote up
@Override
protected void onLoginSuccess(HttpServletRequest request, HttpServletResponse response, Authentication
    successfulAuthentication) {

    String login = successfulAuthentication.getName();

    log.debug("Creating new persistent login for user {}", login);
    PersistentToken token = userRepository.findOneByLogin(login).map(u -> {
        PersistentToken t = new PersistentToken();
        t.setSeries(RandomUtil.generateSeriesData());
        t.setUser(u);
        t.setTokenValue(RandomUtil.generateTokenData());
        t.setTokenDate(LocalDate.now());
        t.setIpAddress(request.getRemoteAddr());
        t.setUserAgent(request.getHeader("User-Agent"));
        return t;
    }).orElseThrow(() -> new UsernameNotFoundException("User " + login + " was not found in the database"));
    try {
        persistentTokenRepository.saveAndFlush(token);
        addCookie(token, request, response);
    } catch (DataAccessException e) {
        log.error("Failed to save persistent token ", e);
    }
}
 
Example 2
Source File: SpringSecurityUserContext.java    From maven-framework-project with MIT License 6 votes vote down vote up
/**
 * Get the {@link CalendarUser} by obtaining the currently logged in Spring Security user's
 * {@link Authentication#getName()} and using that to find the {@link CalendarUser} by email address (since for our
 * application Spring Security usernames are email addresses).
 */
@Override
public CalendarUser getCurrentUser() {
    SecurityContext context = SecurityContextHolder.getContext();
    Authentication authentication = context.getAuthentication();
    if (authentication == null) {
        return null;
    }
    String email = authentication.getName();
    if (email == null) {
        return null;
    }
    CalendarUser result = calendarService.findUserByEmail(email);
    if (result == null) {
        throw new IllegalStateException(
                "Spring Security is not in synch with CalendarUsers. Could not find user with email " + email);
    }
    return result;
}
 
Example 3
Source File: CustomAuthenticationProvider.java    From microservice-integration with MIT License 6 votes vote down vote up
@Override
public Authentication authenticate(Authentication authentication) throws AuthenticationException {
    String username = authentication.getName();
    String password;
    Map data = (Map) authentication.getDetails();
    String clientId = (String) data.get("client");
    Assert.hasText(clientId, "clientId must have value");
    String type = (String) data.get("type");
    Map map;

    password = (String) authentication.getCredentials();
    //如果你是调用user服务,这边不用注掉
    //map = userClient.checkUsernameAndPassword(getUserServicePostObject(username, password, type));
    map = checkUsernameAndPassword(getUserServicePostObject(username, password, type));


    String userId = (String) map.get("userId");
    if (StringUtils.isBlank(userId)) {
        String errorCode = (String) map.get("code");
        throw new BadCredentialsException(errorCode);
    }
    CustomUserDetails customUserDetails = buildCustomUserDetails(username, password, userId, clientId);
    return new CustomAuthenticationToken(customUserDetails);
}
 
Example 4
Source File: UseremailServiceImpl.java    From java-starthere with MIT License 6 votes vote down vote up
@Override
public void delete(long id,
                   boolean isAdmin)
{
    if (useremailrepos.findById(id)
                      .isPresent())
    {
        Authentication authentication = SecurityContextHolder.getContext()
                                                             .getAuthentication();
        if (useremailrepos.findById(id)
                          .get()
                          .getUser()
                          .getUsername()
                          .equalsIgnoreCase(authentication.getName()) || isAdmin)
        {
            useremailrepos.deleteById(id);
        } else
        {
            throw new ResourceNotFoundException(authentication.getName() + " not authorized to make change");
        }
    } else
    {
        throw new ResourceNotFoundException("Useremail with id " + id + " Not Found!");
    }
}
 
Example 5
Source File: MatchPermissionEvaluator.java    From fish-admin with MIT License 5 votes vote down vote up
@Override
public boolean hasPermission(Authentication authentication, Object targetDomainObject, Object permission) {

    String userName = authentication.getName();
    User user = userRepository.findByUserName(userName);
    if (user == null)
        throw new UsernameNotFoundException("not found");
    // admin with id == 1
    if (user.isAdmin()) return true;

    Role role = roleRepository.find(user.getRoleId());
    if (role == null) return false;

    return role.hasPermission(targetDomainObject, permission);
}
 
Example 6
Source File: TradeController.java    From pivotal-bank-demo with Apache License 2.0 5 votes vote down vote up
@RequestMapping(value = "/trade", method = RequestMethod.POST)
public String showTrade(Model model, @ModelAttribute("search") Search search) {
	logger.debug("/trade.POST - symbol: " + search.getName());
	
	//model.addAttribute("marketSummary", marketService.getMarketSummary());
	model.addAttribute("search", search);
	
	if (search.getName() == null || search.getName().equals("") ) {
		model.addAttribute("quotes", new ArrayList<Quote>());
	} else {
		List<Quote> newQuotes = getQuotes(search.getName());
		model.addAttribute("quotes", newQuotes);
	}
	//check if user is logged in!
	Authentication authentication = SecurityContextHolder.getContext().getAuthentication();
	if (!(authentication instanceof AnonymousAuthenticationToken)) {
	    String currentUserName = authentication.getName();
	    logger.debug("User logged in: " + currentUserName);
	    model.addAttribute("order", new Order());
	    
	    
	    //TODO: add portfolio and account summary.
	    try {
	    	model.addAttribute("portfolio",portfolioService.getPortfolio(currentUserName));
	    	model.addAttribute("accounts",accountService.getAccounts(currentUserName));
	    } catch (HttpServerErrorException e) {
	    	model.addAttribute("portfolioRetrievalError",e.getMessage());
	    }
	}
	
	return "trade";
}
 
Example 7
Source File: AuthenticationAuditorAware.java    From springlets with Apache License 2.0 5 votes vote down vote up
/**
 * Returns the object which represents the selected element for identifying
 * the user who modifies registers of an entity.
 * 
 * @return object which represents the user or null if the user is not logged.
 */
@Override
public String getCurrentAuditor() {
  Authentication authentication = SecurityContextHolder.getContext().getAuthentication();
  if (authentication == null || !authentication.isAuthenticated()) {
    return null;
  }
  return authentication.getName();
}
 
Example 8
Source File: CustomAuthenticationProvider.java    From tutorials with MIT License 5 votes vote down vote up
@Override
public Authentication authenticate(final Authentication authentication) throws AuthenticationException {
    final String name = authentication.getName();
    final String password = authentication.getCredentials().toString();
    if (name.equals("admin") && password.equals("system")) {
        final List<GrantedAuthority> grantedAuths = new ArrayList<>();
        grantedAuths.add(new SimpleGrantedAuthority("ROLE_USER"));
        final UserDetails principal = new User(name, password, grantedAuths);
        final Authentication auth = new UsernamePasswordAuthenticationToken(principal, password, grantedAuths);
        return auth;
    } else {
        return null;
    }
}
 
Example 9
Source File: AuthenticationRequestContextInterceptor.java    From wecube-platform with Apache License 2.0 5 votes vote down vote up
@Override
public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) {
    Principal userPrincipal = request.getUserPrincipal();
    if (userPrincipal != null && (userPrincipal instanceof Authentication)) {
        Authentication auth = (Authentication)userPrincipal;
        String authToken = (String) auth.getCredentials();
        AuthenticatedUser currentUser = new AuthenticatedUser(auth.getName(),
                authToken, extractAuthorities(userPrincipal));
        
        AuthenticationContextHolder.setAuthenticatedUser(currentUser);

        request.setAttribute(REQ_ATTR_KEY_CURRENT_USER, currentUser);
    }
    return true;
}
 
Example 10
Source File: SpringSecurityListener.java    From lemon with Apache License 2.0 5 votes vote down vote up
public void logCredentialExpired(ApplicationEvent event) throws Exception {
    AuthenticationFailureCredentialsExpiredEvent authenticationFailureCredentialsExpiredEvent = (AuthenticationFailureCredentialsExpiredEvent) event;
    Authentication authentication = authenticationFailureCredentialsExpiredEvent
            .getAuthentication();
    logger.info("logCredentialExpired : {}", authentication);

    String tenantId = this.getTenantId(authentication);

    Object principal = authentication.getPrincipal();
    String userId = null;

    if (principal instanceof SpringSecurityUserAuth) {
        userId = ((SpringSecurityUserAuth) principal).getId();
    } else {
        userId = authentication.getName();
    }

    AuditDTO auditDto = new AuditDTO();
    auditDto.setUserId(userId);
    auditDto.setAuditTime(new Date());
    auditDto.setAction("login");
    auditDto.setResult("failure");
    auditDto.setApplication("lemon");
    auditDto.setClient(getUserIp(authentication));
    auditDto.setServer(InetAddress.getLocalHost().getHostAddress());
    auditDto.setDescription(authenticationFailureCredentialsExpiredEvent
            .getException().getMessage());
    auditDto.setTenantId(tenantId);
    auditConnector.log(auditDto);

    ctx.publishEvent(new LoginEvent(authentication, userId, this
            .getSessionId(authentication), "credentialExpired", "default",
            tenantId));
}
 
Example 11
Source File: AtlasADAuthenticationProvider.java    From incubator-atlas with Apache License 2.0 5 votes vote down vote up
private Authentication getADAuthentication(Authentication authentication) {
     try {
         String userName = authentication.getName();
         String userPassword = "";
         if (authentication.getCredentials() != null) {
             userPassword = authentication.getCredentials().toString();
         }

         ActiveDirectoryLdapAuthenticationProvider adAuthenticationProvider =
                 new ActiveDirectoryLdapAuthenticationProvider(adDomain, adURL);
         adAuthenticationProvider.setConvertSubErrorCodesToExceptions(true);
adAuthenticationProvider.setUseAuthenticationRequestCredentials(true);

         if (userName != null && userPassword != null
                 && !userName.trim().isEmpty()
                 && !userPassword.trim().isEmpty()) {
             final List<GrantedAuthority> grantedAuths = getAuthorities(userName);
             final UserDetails principal = new User(userName, userPassword,
                     grantedAuths);
             final Authentication finalAuthentication = new UsernamePasswordAuthenticationToken(
                     principal, userPassword, grantedAuths);
             authentication = adAuthenticationProvider.authenticate(finalAuthentication);
             if(groupsFromUGI) {
                 authentication = getAuthenticationWithGrantedAuthorityFromUGI(authentication);
             }
             return authentication;
         } else {
             LOG.error("AD Authentication Failed userName or userPassword is null or empty");
             return null;
         }
     } catch (Exception e) {
         LOG.error("AD Authentication Failed:", e);
         return null;
     }
 }
 
Example 12
Source File: CustomUserDetailsService.java    From NFVO with Apache License 2.0 5 votes vote down vote up
@Override
public void changePassword(String oldPassword, String newPassword) {
  Authentication authentication = SecurityContextHolder.getContext().getAuthentication();
  String currentUserName = authentication.getName();
  log.debug("Changing password of user: " + currentUserName);
  User user = userRepository.findFirstByUsername(currentUserName);
  if (!BCrypt.checkpw(oldPassword, user.getPassword())) {
    throw new UnauthorizedUserException("Old password is wrong.");
  }
  if (!(authentication instanceof AnonymousAuthenticationToken)) { // TODO is this line needed?
    user.setPassword(BCrypt.hashpw(newPassword, BCrypt.gensalt(12)));
    userRepository.save(user);
    log.debug("Password of user " + currentUserName + " has been changed successfully.");
  }
}
 
Example 13
Source File: OauthTokenAspect.java    From microservices-platform with Apache License 2.0 5 votes vote down vote up
private String getClientId(Principal principal) {
    Authentication client = (Authentication) principal;
    if (!client.isAuthenticated()) {
        throw new InsufficientAuthenticationException("The client is not authenticated.");
    }
    String clientId = client.getName();
    if (client instanceof OAuth2Authentication) {
        clientId = ((OAuth2Authentication) client).getOAuth2Request().getClientId();
    }
    return clientId;
}
 
Example 14
Source File: Crust.java    From Milkomeda with MIT License 5 votes vote down vote up
/**
 * 从认证信息获取用户名
 *
 * @return 用户名
 */
public String getUsername() {
    Authentication authentication = getAuthentication();
    if (authentication != null) {
        return authentication.getName();
    }
    return null;
}
 
Example 15
Source File: RangerAuthenticationProvider.java    From ranger with Apache License 2.0 5 votes vote down vote up
private Authentication getADBindAuthentication(Authentication authentication) {
	try {
		String rangerADURL = PropertiesUtil.getProperty("ranger.ldap.ad.url", "");
		String rangerLdapADBase = PropertiesUtil.getProperty("ranger.ldap.ad.base.dn", "");
		String rangerADBindDN = PropertiesUtil.getProperty("ranger.ldap.ad.bind.dn", "");
		String rangerADBindPassword = PropertiesUtil.getProperty("ranger.ldap.ad.bind.password", "");
		String rangerLdapDefaultRole = PropertiesUtil.getProperty("ranger.ldap.default.role", "ROLE_USER");
		String rangerLdapReferral = PropertiesUtil.getProperty("ranger.ldap.ad.referral", "follow");
		String rangerLdapUserSearchFilter = PropertiesUtil.getProperty("ranger.ldap.ad.user.searchfilter", "(sAMAccountName={0})");
		boolean rangerIsStartTlsEnabled = Boolean.valueOf(PropertiesUtil.getProperty(
				"ranger.ldap.starttls", "false"));
		String userName = authentication.getName();
		String userPassword = "";
		if (authentication.getCredentials() != null) {
			userPassword = authentication.getCredentials().toString();
		}

		LdapContextSource ldapContextSource = new DefaultSpringSecurityContextSource(rangerADURL);
		ldapContextSource.setUserDn(rangerADBindDN);
		ldapContextSource.setPassword(rangerADBindPassword);
		ldapContextSource.setReferral(rangerLdapReferral);
		ldapContextSource.setCacheEnvironmentProperties(true);
		ldapContextSource.setAnonymousReadOnly(false);
		ldapContextSource.setPooled(true);
		if (rangerIsStartTlsEnabled) {
			ldapContextSource.setPooled(false);
			ldapContextSource.setAuthenticationStrategy(new DefaultTlsDirContextAuthenticationStrategy());
		}
		ldapContextSource.afterPropertiesSet();

		//String searchFilter="(sAMAccountName={0})";
		if (rangerLdapUserSearchFilter==null || rangerLdapUserSearchFilter.trim().isEmpty()) {
			rangerLdapUserSearchFilter="(sAMAccountName={0})";
		}
		FilterBasedLdapUserSearch userSearch=new FilterBasedLdapUserSearch(rangerLdapADBase, rangerLdapUserSearchFilter,ldapContextSource);
		userSearch.setSearchSubtree(true);

		BindAuthenticator bindAuthenticator = new BindAuthenticator(ldapContextSource);
		bindAuthenticator.setUserSearch(userSearch);
		bindAuthenticator.afterPropertiesSet();

		LdapAuthenticationProvider ldapAuthenticationProvider = new LdapAuthenticationProvider(bindAuthenticator);

		if (userName != null && userPassword != null && !userName.trim().isEmpty() && !userPassword.trim().isEmpty()) {
			final List<GrantedAuthority> grantedAuths = new ArrayList<>();
			grantedAuths.add(new SimpleGrantedAuthority(rangerLdapDefaultRole));
			final UserDetails principal = new User(userName, userPassword,grantedAuths);
			final Authentication finalAuthentication = new UsernamePasswordAuthenticationToken(principal, userPassword, grantedAuths);

			authentication = ldapAuthenticationProvider.authenticate(finalAuthentication);
			authentication=getAuthenticationWithGrantedAuthority(authentication);
			return authentication;
		} else {
			return authentication;
		}
	} catch (Exception e) {
		logger.debug("AD Authentication Failed:", e);
	}
	return authentication;
}
 
Example 16
Source File: DocsAuditorAware.java    From docs-manage with MIT License 4 votes vote down vote up
@Override
public String getCurrentAuditor() {
    Authentication authentication = SecurityContextHolder.getContext().getAuthentication();
    String username = authentication != null ? authentication.getName() : DocsConsts.DEV_USERNAME;
    return StringUtils.isBlank(username) ? DocsConsts.DEV_USERNAME : username;
}
 
Example 17
Source File: RangerAuthenticationProvider.java    From ranger with Apache License 2.0 4 votes vote down vote up
public Authentication getUnixAuthentication(Authentication authentication) {

		try {
			String rangerLdapDefaultRole = PropertiesUtil.getProperty(
					"ranger.ldap.default.role", "ROLE_USER");
			DefaultJaasAuthenticationProvider jaasAuthenticationProvider = new DefaultJaasAuthenticationProvider();
			String loginModuleName = "org.apache.ranger.authentication.unix.jaas.RemoteUnixLoginModule";
			LoginModuleControlFlag controlFlag = LoginModuleControlFlag.REQUIRED;
			Map<String, String> options = PropertiesUtil.getPropertiesMap();
			AppConfigurationEntry appConfigurationEntry = new AppConfigurationEntry(
					loginModuleName, controlFlag, options);
			AppConfigurationEntry[] appConfigurationEntries = new AppConfigurationEntry[] { appConfigurationEntry };
			Map<String, AppConfigurationEntry[]> appConfigurationEntriesOptions = new HashMap<String, AppConfigurationEntry[]>();
			appConfigurationEntriesOptions.put("SPRINGSECURITY",
					appConfigurationEntries);
			Configuration configuration = new InMemoryConfiguration(
					appConfigurationEntriesOptions);
			jaasAuthenticationProvider.setConfiguration(configuration);
			RoleUserAuthorityGranter authorityGranter = new RoleUserAuthorityGranter();
			RoleUserAuthorityGranter[] authorityGranters = new RoleUserAuthorityGranter[] { authorityGranter };
			jaasAuthenticationProvider.setAuthorityGranters(authorityGranters);
			jaasAuthenticationProvider.afterPropertiesSet();
			String userName = authentication.getName();
			String userPassword = "";
			if (authentication.getCredentials() != null) {
				userPassword = authentication.getCredentials().toString();
			}

			// getting user authenticated
			if (userName != null && userPassword != null
					&& !userName.trim().isEmpty()
					&& !userPassword.trim().isEmpty()) {
				final List<GrantedAuthority> grantedAuths = new ArrayList<>();
				grantedAuths.add(new SimpleGrantedAuthority(
						rangerLdapDefaultRole));
				final UserDetails principal = new User(userName, userPassword,
						grantedAuths);
				final Authentication finalAuthentication = new UsernamePasswordAuthenticationToken(
						principal, userPassword, grantedAuths);
				authentication = jaasAuthenticationProvider
						.authenticate(finalAuthentication);
				authentication=getAuthenticationWithGrantedAuthority(authentication);
				return authentication;
			} else {
				return authentication;
			}
		} catch (Exception e) {
			logger.debug("Unix Authentication Failed:", e);
		}

		return authentication;
	}
 
Example 18
Source File: DocsAuditorAware.java    From docs-manage with MIT License 4 votes vote down vote up
@Override
public String getCurrentAuditor() {
    Authentication authentication = SecurityContextHolder.getContext().getAuthentication();
    String username = authentication != null ? authentication.getName() : DocsConsts.DEV_USERNAME;
    return StringUtils.isBlank(username) ? DocsConsts.DEV_USERNAME : username;
}
 
Example 19
Source File: AbstractUserDetailsAuthenticationProvider.java    From Taroco with Apache License 2.0 4 votes vote down vote up
@Override
public Authentication authenticate(Authentication authentication) throws AuthenticationException {
    String username = authentication.getPrincipal() == null ? "NONE_PROVIDED" : authentication.getName();
    boolean cacheWasUsed = true;
    UserDetails user = this.userCache.getUserFromCache(username);
    if (user == null) {
        cacheWasUsed = false;

        try {
            user = this.retrieveUser(username, authentication);
        } catch (UsernameNotFoundException var6) {
            log.error("User \'" + username + "\' not found");
            if (this.hideUserNotFoundExceptions) {
                throw new BadCredentialsException(this.messages.getMessage("AbstractUserDetailsAuthenticationProvider.badCredentials", "Bad credentials"));
            }

            throw var6;
        }

        Assert.notNull(user, "retrieveUser returned null - a violation of the interface contract");
    }

    try {
        this.preAuthenticationChecks.check(user);
        this.additionalAuthenticationChecks(user, authentication);
    } catch (AuthenticationException var7) {
        if (!cacheWasUsed) {
            throw var7;
        }

        cacheWasUsed = false;
        user = this.retrieveUser(username, authentication);
        this.preAuthenticationChecks.check(user);
        this.additionalAuthenticationChecks(user, authentication);
    }

    this.postAuthenticationChecks.check(user);
    if (!cacheWasUsed) {
        this.userCache.putUserInCache(user);
    }

    Object principalToReturn = user;
    if (this.forcePrincipalAsString) {
        principalToReturn = user.getUsername();
    }

    return this.createSuccessAuthentication(principalToReturn, authentication, user);
}
 
Example 20
Source File: AtlasPamAuthenticationProvider.java    From atlas with Apache License 2.0 4 votes vote down vote up
private Authentication getPamAuthentication(Authentication authentication) {
    if (isDebugEnabled) {
        LOG.debug("==> AtlasPamAuthenticationProvider getPamAuthentication");
    }
    try {
        String userName = authentication.getName();
        String userPassword = "";
        if (authentication.getCredentials() != null) {
            userPassword = authentication.getCredentials().toString();
        }

        // getting user authenticated
        if (userName != null && userPassword != null
                && !userName.trim().isEmpty()
                && !userPassword.trim().isEmpty()) {
            final List<GrantedAuthority> grantedAuths = getAuthorities(userName);

            final UserDetails principal = new User(userName, userPassword,
                    grantedAuths);

            final Authentication finalAuthentication = new UsernamePasswordAuthenticationToken(
                    principal, userPassword, grantedAuths);

            authentication = jaasAuthenticationProvider
                    .authenticate(finalAuthentication);

            if(groupsFromUGI) {
                authentication = getAuthenticationWithGrantedAuthorityFromUGI(authentication);
            } else {
                authentication = getAuthenticationWithGrantedAuthority(authentication);
            }
            return authentication;
        } else {
            return authentication;
        }

    } catch (Exception e) {
        LOG.debug("Pam Authentication Failed:", e);
    }
    if (isDebugEnabled) {
        LOG.debug("<== AtlasPamAuthenticationProvider getPamAuthentication : " + jaasAuthenticationProvider);
    }
    return authentication;
}