Example usage for org.springframework.security.authentication AuthenticationCredentialsNotFoundException AuthenticationCredentialsNotFoundException

List of usage examples for org.springframework.security.authentication AuthenticationCredentialsNotFoundException AuthenticationCredentialsNotFoundException

Introduction

In this page you can find the example usage for org.springframework.security.authentication AuthenticationCredentialsNotFoundException AuthenticationCredentialsNotFoundException.

Prototype

public AuthenticationCredentialsNotFoundException(String msg) 

Source Link

Document

Constructs an AuthenticationCredentialsNotFoundException with the specified message.

Usage

From source file:com.mothsoft.alexis.web.security.OutboundRestAuthenticationInterceptor.java

@Override
public void handleMessage(Message message) {

    if (!CurrentUserUtil.isAuthenticated()) {
        throw new AuthenticationCredentialsNotFoundException("Unauthenticated user!");
    }//from   ww  w  .  j  a  va 2s.  c o m

    @SuppressWarnings("unchecked")
    Map<String, List<String>> headers = (Map<String, List<String>>) message.get(Message.PROTOCOL_HEADERS);
    if (headers == null) {
        headers = new TreeMap<String, List<String>>(String.CASE_INSENSITIVE_ORDER);
        message.put(Message.PROTOCOL_HEADERS, headers);
    }

    final List<String> header = new ArrayList<String>();

    final String username = CurrentUserUtil.getCurrentUser().getUsername();
    final String apiToken = CurrentUserUtil.getCurrentUser().getApiToken();
    final String usernameToken = String.format("%s:%s", username, apiToken);
    try {
        header.add(String.format("Basic %s", new String(Base64.encodeBase64(usernameToken.getBytes("UTF-8")))));
    } catch (UnsupportedEncodingException e) {
        throw new RuntimeException(e);
    }

    headers.put("Authorization", header);
}

From source file:org.ngrinder.user.service.UserContext.java

/**
 * Get current user object from context.
 *
 * @return current user;//from   www .j  av  a2  s  .  com
 */
public User getCurrentUser() {
    Authentication auth = SecurityContextHolder.getContext().getAuthentication();
    if (auth == null) {
        throw new AuthenticationCredentialsNotFoundException("No authentication");
    }
    Object obj = auth.getPrincipal();
    if (!(obj instanceof SecuredUser)) {
        throw new AuthenticationCredentialsNotFoundException("Invalid authentication with " + obj);
    }
    SecuredUser securedUser = (SecuredUser) obj;
    return securedUser.getUser();
}

From source file:com.jiwhiz.rest.user.AbstractUserRestController.java

protected UserAccount getCurrentAuthenticatedUser() {
    UserAccount currentUser = this.userAccountService.getCurrentUser();
    if (currentUser == null) {
        throw new AuthenticationCredentialsNotFoundException("User not logged in.");
    }//w  w  w  . j  a va  2  s  .c  o  m
    return currentUser;
}

From source file:com.seyren.core.security.mongo.MongoAuthenticationProvider.java

@Override
public Authentication authenticate(Authentication authentication) throws AuthenticationException {
    User user = userStore.getUser(authentication.getName());
    if (user == null) {
        throw new AuthenticationCredentialsNotFoundException("User does not exist");
    }/*from w  w w  . ja va  2 s  . c  o  m*/
    String password = authentication.getCredentials().toString();
    if (passwordEncoder.matches(password, user.getPassword())) {
        return new UsernamePasswordAuthenticationToken(user.getUsername(), user.getPassword(),
                user.getAuthorities());
    } else {
        throw new BadCredentialsException("Bad Credentials");
    }
}

From source file:ch.wisv.areafiftylan.security.authentication.AuthenticationServiceImpl.java

@Override
public String createNewAuthToken(String username, String password) {
    User user = userService.getUserByUsername(username)
            .orElseThrow(() -> new UsernameNotFoundException(username));

    if (correctCredentials(user, password)) {
        // Delete the old Token
        authenticationTokenRepository.findByUserUsername(username)
                .ifPresent(t -> authenticationTokenRepository.delete(t));

        return authenticationTokenRepository.save(new AuthenticationToken(user)).getToken();
    }/*  ww w.  j a v a2s .com*/

    throw new AuthenticationCredentialsNotFoundException("Incorrect credentials");
}

From source file:org.vaadin.spring.security.config.AbstractVaadinSecurityConfiguration.java

@Bean(name = CURRENT_USER_BEAN)
Authentication currentUser() {/*w  w  w . j  ava2  s  .c o m*/

    return ProxyFactory.getProxy(Authentication.class, new MethodInterceptor() {

        @Override
        public Object invoke(MethodInvocation invocation) throws Throwable {
            SecurityContext securityContext = SecurityContextHolder.getContext();
            Authentication authentication = securityContext.getAuthentication();
            if (authentication == null) {
                throw new AuthenticationCredentialsNotFoundException(
                        "No authentication found in current security context");
            }
            return invocation.getMethod().invoke(authentication, invocation.getArguments());
        }

    });

}

From source file:org.vaadin.spring.security.config.VaadinSecurityConfiguration.java

@Bean
Authentication currentUser() {/*from   www  .  j a v  a2 s.c  o m*/
    return ProxyFactory.getProxy(Authentication.class, new MethodInterceptor() {
        @Override
        public Object invoke(MethodInvocation invocation) throws Throwable {
            SecurityContext securityContext = SecurityContextHolder.getContext();
            Authentication authentication = securityContext.getAuthentication();
            if (authentication == null) {
                throw new AuthenticationCredentialsNotFoundException(
                        "No authentication found in current security context");
            }
            return invocation.getMethod().invoke(authentication, invocation.getArguments());
        }
    });
}

From source file:com.javaeeeee.components.JpaAuthenticationProvider.java

@Override
public Authentication authenticate(Authentication authentication) throws AuthenticationException {
    Optional<User> optional = usersRepository.findByUsernameAndPassword(authentication.getName(),
            authentication.getCredentials().toString());
    if (optional.isPresent()) {
        return new UsernamePasswordAuthenticationToken(authentication.getPrincipal(),
                authentication.getCredentials(), authentication.getAuthorities());

    } else {// www  . j av a2 s.c  om
        throw new AuthenticationCredentialsNotFoundException("Wrong credentials.");
    }
}

From source file:org.apigw.authserver.web.controller.TrustedController.java

/**
 * Lets trusted clients create access tokens for themselves.
 * @param scope The requested scope// ww  w  .  j a  v a2 s .c  o  m
 * @param citizen The resident identification number of the citizen that is the subject of this access token
 * @param legalGuardian The resident identification number of the legal guardian that requested this access token. 
 * If this access token is not requested by a legal guardian this field shall be null or an empty string.
 * @return
 */
@RequestMapping(value = "/oauth/token", method = RequestMethod.POST)
public @ResponseBody OAuth2AccessToken createAccessToken(@RequestParam String scope,
        @RequestParam String citizen, @RequestParam(required = false) String legalGuardian) {
    log.debug("/trusted/oauth/token createAccessToken(scope:{}, citizen:{}, legalGuardian:{})", scope,
            "NOT LOGGED", "NOT LOGGED");

    UserDetails user = (UserDetails) SecurityContextHolder.getContext().getAuthentication().getPrincipal();
    if (user == null) {
        throw new AuthenticationCredentialsNotFoundException("Not authenticated!");
    }
    String clientId = user.getUsername();
    log.debug("Trusted client with with clientId:{} creating access token creation with scope: {}", clientId,
            scope);

    List<String> scopeList = new ArrayList<String>();
    if (scope != null) {
        String[] scopeArray = scope.trim().split(",");
        scopeList = Arrays.asList(scopeArray);
    }
    if (StringUtils.isBlank(legalGuardian) || citizen.equals(legalGuardian)) {
        return tokenServices.createAccessToken(citizen, clientId, scopeList);
    } else {
        return tokenServices.createAccessToken(legalGuardian, citizen, clientId, scopeList);
    }
}

From source file:com.example.ProxyAuthorizationServerTokenServices.java

@Override
public OAuth2AccessToken createAccessToken(OAuth2Authentication authentication) throws AuthenticationException {
    Authentication user = authentication.getUserAuthentication();
    if (user instanceof CloudFoundryAuthentication) {
        CloudFoundryAuthentication cfuser = (CloudFoundryAuthentication) user;
        OAuth2AccessToken token = cfuser.getToken();
        if (token.isExpired()) {
            CloudCredentials credentials = new CloudCredentials(token);
            CloudFoundryClient client = new CloudFoundryClient(credentials, properties.getApi());
            token = client.login();/*from  w ww . j  a  v  a2s .c  o m*/
            cfuser.setToken(token);
        }
        return token;
    }
    throw new AuthenticationCredentialsNotFoundException("No Cloud Foundy authentication found");
}