javax.security.enterprise.identitystore.CredentialValidationResult Java Examples

The following examples show how to use javax.security.enterprise.identitystore.CredentialValidationResult. 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: SecurityContextTest.java    From tomee with Apache License 2.0 6 votes vote down vote up
@Override
public AuthenticationStatus validateRequest(final HttpServletRequest request,
                                            final HttpServletResponse response,
                                            final HttpMessageContext httpMessageContext)
        throws AuthenticationException {

    if (httpMessageContext.isAuthenticationRequest()) {
        try {
            final CredentialValidationResult result =
                    identityStoreHandler.validate(httpMessageContext.getAuthParameters().getCredential());

            if (result.getStatus().equals(VALID)) {
                return httpMessageContext.notifyContainerAboutLogin(result);
            }

        } catch (final IllegalArgumentException | IllegalStateException e) {
            // Something was sent in the header was not valid.
        }

        return httpMessageContext.responseUnauthorized();
    }

    return httpMessageContext.doNothing();
}
 
Example #2
Source File: BasicAuthenticationMechanism.java    From tomee with Apache License 2.0 6 votes vote down vote up
@Override
public AuthenticationStatus validateRequest(final HttpServletRequest request,
                                            final HttpServletResponse response,
                                            final HttpMessageContext httpMessageContext)
        throws AuthenticationException {

    if (!httpMessageContext.isProtected()) {
        return httpMessageContext.doNothing();
    }

    try {
        final CredentialValidationResult result =
                identityStoreHandler.validate(parseAuthenticationHeader(request.getHeader(AUTHORIZATION)));

        if (result.getStatus().equals(VALID)) {
            return httpMessageContext.notifyContainerAboutLogin(result);
        }

    } catch (final IllegalArgumentException | IllegalStateException e) {
        // Something was sent in the header was not valid. Fallthrough to the authenticate challenge again.
    }

    response.setHeader("WWW-Authenticate", "Basic");
    return httpMessageContext.responseUnauthorized();
}
 
Example #3
Source File: UserIdentityStore.java    From javaee8-cookbook with Apache License 2.0 6 votes vote down vote up
public CredentialValidationResult validate(UsernamePasswordCredential usernamePasswordCredential) {

        if (usernamePasswordCredential.getCaller().equals(Roles.ADMIN)
                && usernamePasswordCredential.getPassword().compareTo("1234")) {

            return new CredentialValidationResult(
                    new CallerPrincipal(usernamePasswordCredential.getCaller()),
                    new HashSet<>(Arrays.asList(Roles.ADMIN)));
        } else if (usernamePasswordCredential.getCaller().equals(Roles.USER)
                && usernamePasswordCredential.getPassword().compareTo("1234")) {

            return new CredentialValidationResult(
                    new CallerPrincipal(usernamePasswordCredential.getCaller()),
                    new HashSet<>(Arrays.asList(Roles.USER)));
        }

        return CredentialValidationResult.INVALID_RESULT;
    }
 
Example #4
Source File: JpaIdentityStore.java    From javaee8-jaxrs-sample with GNU General Public License v3.0 6 votes vote down vote up
@Override
public CredentialValidationResult validate(Credential credential) {
    CredentialValidationResult result;

    if (credential instanceof UsernamePasswordCredential) {
        UsernamePasswordCredential usernamePassword = (UsernamePasswordCredential) credential;

        result = users.findByUsername(usernamePassword.getCaller())
            .map(
                u -> passwordHash.matches(new String(usernamePassword.getPassword().getValue()), u.getPassword())
                ? new CredentialValidationResult(usernamePassword.getCaller(), u.getAuthorities())
                : INVALID_RESULT
            )
            .orElse(INVALID_RESULT);

    } else {
        result = NOT_VALIDATED_RESULT;
    }
    return result;
}
 
Example #5
Source File: SimpleAuthenticationMechanism.java    From thorntail with Apache License 2.0 6 votes vote down vote up
@Override
public AuthenticationStatus validateRequest(HttpServletRequest request, HttpServletResponse response, HttpMessageContext httpMessageContext) throws AuthenticationException {

    String name = request.getParameter("name");
    Password password = new Password(request.getParameter("password"));

    // Delegate the {credentials in -> identity data out} function to
    // the Identity Store
    CredentialValidationResult result = identityStoreHandler.validate(
        new UsernamePasswordCredential(name, password));

    if (result.getStatus() == VALID) {
        // Communicate the details of the authenticated user to the
        // container. In many cases the underlying handler will just store the details
        // and the container will actually handle the login after we return from
        // this method.
        return httpMessageContext.notifyContainerAboutLogin(
            result.getCallerPrincipal(), result.getCallerGroups());
    }
    return httpMessageContext.responseUnauthorized();
}
 
Example #6
Source File: SimpleAuthenticationMechanism.java    From thorntail with Apache License 2.0 6 votes vote down vote up
@Override
public AuthenticationStatus validateRequest(HttpServletRequest request, HttpServletResponse response, HttpMessageContext httpMessageContext) throws AuthenticationException {

    String name = request.getParameter("name");
    Password password = new Password(request.getParameter("password"));

    // Delegate the {credentials in -> identity data out} function to
    // the Identity Store
    CredentialValidationResult result = identityStoreHandler.validate(
        new UsernamePasswordCredential(name, password));

    if (result.getStatus() == VALID) {
        // Communicate the details of the authenticated user to the
        // container. In many cases the underlying handler will just store the details
        // and the container will actually handle the login after we return from
        // this method.
        return httpMessageContext.notifyContainerAboutLogin(
            result.getCallerPrincipal(), result.getCallerGroups());
    }
    return httpMessageContext.responseUnauthorized();
}
 
Example #7
Source File: TestAuthenticationMechanism.java    From Architecting-Modern-Java-EE-Applications with MIT License 6 votes vote down vote up
@Override
public AuthenticationStatus validateRequest(HttpServletRequest request, HttpServletResponse response,
                                            HttpMessageContext httpMessageContext) throws AuthenticationException {

    // ...
    String name = request.getParameter("name");
    String password = request.getParameter("password");

    if (name != null && password != null) {
        CredentialValidationResult result = identityStoreHandler.validate(new UsernamePasswordCredential(name, password));

        return httpMessageContext.notifyContainerAboutLogin(result);
    }

    return httpMessageContext.doNothing();
}
 
Example #8
Source File: TestIdentityStore.java    From ee8-sandbox with Apache License 2.0 5 votes vote down vote up
public CredentialValidationResult validate(UsernamePasswordCredential usernamePasswordCredential) {

        if (usernamePasswordCredential.compareTo("user", "password")) {
            return new CredentialValidationResult("user", new HashSet<>(asList("foo", "bar")));
        }

        return INVALID_RESULT;
    }
 
Example #9
Source File: CustomInMemoryIdentityStore.java    From blog-tutorials with MIT License 5 votes vote down vote up
@Override
public CredentialValidationResult validate(Credential credential) {

    UsernamePasswordCredential login = (UsernamePasswordCredential) credential;

    if (login.getCaller().equals("[email protected]") && login.getPasswordAsString().equals("ADMIN1234")) {
        return new CredentialValidationResult("admin", new HashSet<>(Arrays.asList("ADMIN")));
    } else if (login.getCaller().equals("[email protected]") && login.getPasswordAsString().equals("USER1234")) {
        return new CredentialValidationResult("user", new HashSet<>(Arrays.asList("USER")));
    } else {
        return CredentialValidationResult.NOT_VALIDATED_RESULT;
    }
}
 
Example #10
Source File: TestAuthenticationMechanism.java    From ee8-sandbox with Apache License 2.0 5 votes vote down vote up
@Override
public AuthenticationStatus validateRequest(HttpServletRequest request, HttpServletResponse response, HttpMessageContext httpMessageContext) throws AuthenticationException {
    final String name = request.getParameter("name");
    final String pwd = request.getParameter("password");

    if (name != null && pwd != null ) {

        // Get the (caller) name and password from the request
        // NOTE: This is for the smallest possible example only. In practice
        // putting the password in a request query parameter is highly
        // insecure
        
        Password password = new Password(pwd);

        // Delegate the {credentials in -> identity data out} function to
        // the Identity Store
        CredentialValidationResult result = identityStoreHandler.validate(
                new UsernamePasswordCredential(name, password));

        if (result.getStatus() == VALID) {
            // Communicate the details of the authenticated user to the
            // container. In many cases the underlying handler will just store the details 
            // and the container will actually handle the login after we return from 
            // this method.
            return httpMessageContext.notifyContainerAboutLogin(
                    result.getCallerPrincipal(), result.getCallerGroups());
        }

        return httpMessageContext.responseUnauthorized();
    }

    return httpMessageContext.doNothing();
}
 
Example #11
Source File: TestIdentityStore.java    From ee8-sandbox with Apache License 2.0 5 votes vote down vote up
public CredentialValidationResult validate(UsernamePasswordCredential usernamePasswordCredential) {

        if (usernamePasswordCredential.compareTo("user", "password")) {
            return new CredentialValidationResult("user", new HashSet<>(asList("foo", "bar")));
        }

        return INVALID_RESULT;
    }
 
Example #12
Source File: TestIdentityStore.java    From ee8-sandbox with Apache License 2.0 5 votes vote down vote up
public CredentialValidationResult validate(UsernamePasswordCredential usernamePasswordCredential) {

        if (usernamePasswordCredential.compareTo("user", "password")) {
            return new CredentialValidationResult("user", new HashSet<>(asList("foo", "bar")));
        }

        return INVALID_RESULT;
    }
 
Example #13
Source File: TestAuthenticationMechanism.java    From ee8-sandbox with Apache License 2.0 5 votes vote down vote up
@Override
public AuthenticationStatus validateRequest(HttpServletRequest request, HttpServletResponse response, HttpMessageContext httpMessageContext) throws AuthenticationException {
    final String name = request.getParameter("name");
    final String pwd = request.getParameter("password");

    if (name != null && pwd != null ) {

        // Get the (caller) name and password from the request
        // NOTE: This is for the smallest possible example only. In practice
        // putting the password in a request query parameter is highly
        // insecure
        
        Password password = new Password(pwd);

        // Delegate the {credentials in -> identity data out} function to
        // the Identity Store
        CredentialValidationResult result = identityStoreHandler.validate(
                new UsernamePasswordCredential(name, password));

        if (result.getStatus() == VALID) {
            // Communicate the details of the authenticated user to the
            // container. In many cases the underlying handler will just store the details 
            // and the container will actually handle the login after we return from 
            // this method.
            return httpMessageContext.notifyContainerAboutLogin(
                    result.getCallerPrincipal(), result.getCallerGroups());
        }

        return httpMessageContext.responseUnauthorized();
    }

    return httpMessageContext.doNothing();
}
 
Example #14
Source File: SimpleIdentityStore.java    From thorntail with Apache License 2.0 5 votes vote down vote up
public CredentialValidationResult validate(UsernamePasswordCredential usernamePasswordCredential) {

        if (usernamePasswordCredential.compareTo("thorntail1", "secret1")) {
            return new CredentialValidationResult("thorntail1", new HashSet<>(asList("role1")));
        } else if (usernamePasswordCredential.compareTo("thorntail2", "secret2")) {
            return new CredentialValidationResult("thorntail2", new HashSet<>(asList("role2")));
        }

        return INVALID_RESULT;
    }
 
Example #15
Source File: SimpleIdentityStore.java    From thorntail with Apache License 2.0 5 votes vote down vote up
public CredentialValidationResult validate(UsernamePasswordCredential usernamePasswordCredential) {

        if (usernamePasswordCredential.compareTo("thorntail1", "secret1")) {
            return new CredentialValidationResult("thorntail1", new HashSet<>(asList("role1")));
        } else if (usernamePasswordCredential.compareTo("thorntail2", "secret2")) {
            return new CredentialValidationResult("thorntail2", new HashSet<>(asList("role2")));
        }

        return INVALID_RESULT;
    }
 
Example #16
Source File: TomEEIdentityStoreHandler.java    From tomee with Apache License 2.0 5 votes vote down vote up
@Override
public CredentialValidationResult validate(final Credential credential) {
    if (authenticationStores.isEmpty()) {
        return NOT_VALIDATED_RESULT;
    }

    CredentialValidationResult validationResult = null;
    IdentityStore authorizedStore = null;
    for (final IdentityStore identityStore : identityStores) {
        validationResult = identityStore.validate(credential);
        if (validationResult.getStatus().equals(VALID)) {
            authorizedStore = identityStore;
            break;
        }
    }

    if (authorizedStore == null) {
        return INVALID_RESULT;
    }

    final Set<String> groups = new HashSet<>();
    if (authorizedStore.validationTypes().contains(PROVIDE_GROUPS)) {
        groups.addAll(authorizedStore.getCallerGroups(validationResult));
    }

    final CredentialValidationResult authorizedValidationResult = validationResult;
    final Set<String> additionalGroups =
            authorizationStores.stream()
                               .map(as -> as.getCallerGroups(authorizedValidationResult))
                               .flatMap(Collection::stream)
                               .collect(Collectors.toSet());
    groups.addAll(additionalGroups);

    return new CredentialValidationResult(authorizedValidationResult.getIdentityStoreId(),
                                          authorizedValidationResult.getCallerPrincipal(),
                                          authorizedValidationResult.getCallerDn(),
                                          authorizedValidationResult.getCallerUniqueId(),
                                          groups);
}
 
Example #17
Source File: TomEEDefaultIdentityStore.java    From tomee with Apache License 2.0 5 votes vote down vote up
@Override
public CredentialValidationResult validate(final Credential credential) {
    if (credential instanceof UsernamePasswordCredential) {
        final UsernamePasswordCredential usernamePasswordCredential = (UsernamePasswordCredential) credential;
        return Optional.ofNullable(userDatabase.findUser(usernamePasswordCredential.getCaller()))
                       .filter(user -> user.getPassword().equals(usernamePasswordCredential.getPasswordAsString()))
                       .map(user -> new CredentialValidationResult(user.getUsername(), getUserRoles(user)))
                       .orElse(CredentialValidationResult.INVALID_RESULT);
    }

    return CredentialValidationResult.NOT_VALIDATED_RESULT;
}
 
Example #18
Source File: TomEEHttpMessageContext.java    From tomee with Apache License 2.0 5 votes vote down vote up
@Override
public AuthenticationStatus notifyContainerAboutLogin(final CredentialValidationResult result) {
    if (result.getStatus().equals(VALID)) {
        return notifyContainerAboutLogin(result.getCallerPrincipal(), result.getCallerGroups());
    }

    return SEND_FAILURE;
}
 
Example #19
Source File: RememberMeInterceptor.java    From tomee with Apache License 2.0 5 votes vote down vote up
private AuthenticationStatus validateRequest(final InvocationContext invocationContext) throws Exception {
    final HttpMessageContext httpMessageContext = (HttpMessageContext) invocationContext.getParameters()[2];

    final RememberMe rememberMe = getRememberMe();
    final Optional<Cookie> cookie = getCookie(httpMessageContext.getRequest(), rememberMe.cookieName());

    if (cookie.isPresent()) {
        final RememberMeCredential rememberMeCredential = new RememberMeCredential(cookie.get().getValue());
        final CredentialValidationResult validate = rememberMeIdentityStore.get().validate(rememberMeCredential);

        if (VALID.equals(validate.getStatus())) {
            return httpMessageContext.notifyContainerAboutLogin(validate);
        } else {
            cookie.get().setMaxAge(0);
            httpMessageContext.getResponse().addCookie(cookie.get());
        }
    }

    final AuthenticationStatus status = (AuthenticationStatus) invocationContext.proceed();

    if (SUCCESS.equals(status) && rememberMe.isRememberMe()) {
        final CallerPrincipal principal = new CallerPrincipal(httpMessageContext.getCallerPrincipal().getName());
        final Set<String> groups = httpMessageContext.getGroups();
        final String loginToken = rememberMeIdentityStore.get().generateLoginToken(principal, groups);

        final Cookie rememberMeCookie = new Cookie(rememberMe.cookieName(), loginToken);
        rememberMeCookie.setMaxAge(rememberMe.cookieMaxAgeSeconds());
        rememberMeCookie.setHttpOnly(rememberMe.cookieHttpOnly());
        rememberMeCookie.setSecure(rememberMe.cookieSecureOnly());
        httpMessageContext.getResponse().addCookie(rememberMeCookie);
    }

    return status;
}
 
Example #20
Source File: UserIdentityStore.java    From tutorials with MIT License 5 votes vote down vote up
@Override
public CredentialValidationResult validate(Credential credential) {
    UsernamePasswordCredential usernamePasswordCredential = (UsernamePasswordCredential) credential;
    String userId = usernamePasswordCredential.getCaller();
    User user = appDataRepository.getUser(userId);
    Objects.requireNonNull(user, "User should be not null");
    if (usernamePasswordCredential.getPasswordAsString().equals(user.getPassword())) {
        return new CredentialValidationResult(userId, new HashSet<>(Arrays.asList(user.getRoles().split(","))));
    }
    return INVALID_RESULT;
}
 
Example #21
Source File: InMemoryIdentityStore4Authentication.java    From tutorials with MIT License 5 votes vote down vote up
public CredentialValidationResult validate(UsernamePasswordCredential credential) {
    String password = users.get(credential.getCaller());
    if (password != null && password.equals(credential.getPasswordAsString())) {
        return new CredentialValidationResult(credential.getCaller());
    }
    return INVALID_RESULT;
}
 
Example #22
Source File: JwtAuthenticationMechanism.java    From javaee8-jaxrs-sample with GNU General Public License v3.0 5 votes vote down vote up
/**
 * Create the JWT using CredentialValidationResult received from IdentityStoreHandler
 *
 * @param result the result from validation of UsernamePasswordCredential
 * @param context
 * @return the AuthenticationStatus to notify the container
 */
private AuthenticationStatus createToken(CredentialValidationResult result, HttpMessageContext context) {
    if (!isRememberMe(context)) {
        String jwt = tokenProvider.createToken(result.getCallerPrincipal().getName(), result.getCallerGroups(), false);
        context.getResponse().setHeader(HttpHeaders.AUTHORIZATION, AUTHORIZATION_PREFIX + jwt);
    }

    //fire an @Authenticated CDI event.
    authenticatedEvent.fire(new UserInfo(result.getCallerPrincipal().getName(), result.getCallerGroups()));

    return context.notifyContainerAboutLogin(result.getCallerPrincipal(), result.getCallerGroups());
}
 
Example #23
Source File: InMemoryIdentityStore.java    From blog-tutorials with MIT License 5 votes vote down vote up
public CredentialValidationResult validate(UsernamePasswordCredential credential) {

        if (credential.getPassword().compareTo("SECRET")) {
            return new CredentialValidationResult(credential.getCaller(), defaultRoles);
        }
        return INVALID_RESULT;
    }
 
Example #24
Source File: UserIdentityStore.java    From javaee8-cookbook with Apache License 2.0 5 votes vote down vote up
@Override
public CredentialValidationResult validate(Credential credential) {
    if (credential instanceof UsernamePasswordCredential) {
        return validate((UsernamePasswordCredential) credential);
    }

    return CredentialValidationResult.NOT_VALIDATED_RESULT;
}
 
Example #25
Source File: InMemoryIdentityStore.java    From piranha with BSD 3-Clause "New" or "Revised" License 5 votes vote down vote up
public CredentialValidationResult validate(UsernamePasswordCredential usernamePasswordCredential) {
    Credential credential = CALLER_TO_CREDENTIALS.get(usernamePasswordCredential.getCaller());

    if (credential != null && usernamePasswordCredential.getPassword().compareTo(credential.getPassword())) {
        return new CredentialValidationResult(
            new CallerPrincipal(credential.getCallerName()), 
            new HashSet<>(credential.getGroups())
        );
    }

    return INVALID_RESULT;
}
 
Example #26
Source File: IdentityStoreLoginHandler.java    From piranha with BSD 3-Clause "New" or "Revised" License 5 votes vote down vote up
@Override
public AuthenticatedIdentity login(HttpServletRequest request, String username, String password) {

    CredentialValidationResult result = CDI.current()
       .select(IdentityStoreHandler.class)
       .get()
       .validate(new UsernamePasswordCredential(username, new Password(password)));

    if (result.getStatus() == VALID) {
        return new DefaultAuthenticatedIdentity(result.getCallerPrincipal(), result.getCallerGroups());
    }
    
    return null;
}
 
Example #27
Source File: TestIdentityStore.java    From piranha with BSD 3-Clause "New" or "Revised" License 5 votes vote down vote up
public CredentialValidationResult validate(UsernamePasswordCredential usernamePasswordCredential) {

        if (usernamePasswordCredential.compareTo("test", "test")) {
            return new CredentialValidationResult("test", new HashSet<>(asList("architect")));
        }

        return INVALID_RESULT;
    }
 
Example #28
Source File: TestIdentityStore.java    From piranha with BSD 3-Clause "New" or "Revised" License 5 votes vote down vote up
public CredentialValidationResult validate(UsernamePasswordCredential usernamePasswordCredential) {

        if (usernamePasswordCredential.compareTo("test", "test")) {
            return new CredentialValidationResult("test", new HashSet<>(asList("architect")));
        }

        return INVALID_RESULT;
    }
 
Example #29
Source File: LiteWeightIdentityStore.java    From Java-EE-8-Sampler with MIT License 5 votes vote down vote up
public CredentialValidationResult validate(UsernamePasswordCredential userCredential) {

        if (userCredential.compareTo("admin", "pwd1")) {
            return new CredentialValidationResult("admin", new HashSet<>(asList("admin", "user", "demo")));
        }

        return INVALID_RESULT;
    }
 
Example #30
Source File: LiteAuthenticationMechanism.java    From Java-EE-8-Sampler with MIT License 5 votes vote down vote up
@Override
public AuthenticationStatus validateRequest(HttpServletRequest req, HttpServletResponse res, HttpMessageContext context) {

    CredentialValidationResult result = idStoreHandler.validate(
            new UsernamePasswordCredential(
                    req.getParameter("name"), req.getParameter("password")));

    if (result.getStatus() == VALID) {
        return context.notifyContainerAboutLogin(result);
    } else {
        return context.responseUnauthorized();
    }

}