javax.security.enterprise.credential.Credential Java Examples

The following examples show how to use javax.security.enterprise.credential.Credential. 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: LoginBean.java    From javaee8-jsf-sample with GNU General Public License v3.0 6 votes vote down vote up
public void login() {

        FacesContext context = FacesContext.getCurrentInstance();
        Credential credential = new UsernamePasswordCredential(username, new Password(password));

        AuthenticationStatus status = securityContext.authenticate(
                getRequest(context),
                getResponse(context),
                withParams()
                        .credential(credential)
                        .newAuthentication(!continued)
                        .rememberMe(rememberMe)
        );

        LOG.info("authentication result:" + status);

        if (status.equals(SEND_CONTINUE)) {
            // Authentication mechanism has send a redirect, should not
            // send anything to response from JSF now.
            context.responseComplete();
        } else if (status.equals(SEND_FAILURE)) {
            addError(context, "Authentication failed");
        }

    }
 
Example #2
Source File: LoginBean.java    From ee8-sandbox with Apache License 2.0 6 votes vote down vote up
public void login() {

        FacesContext context = FacesContext.getCurrentInstance();
        Credential credential = new UsernamePasswordCredential(username, new Password(password));

        AuthenticationStatus status = securityContext.authenticate(
                getRequest(context),
                getResponse(context),
                withParams()
                        .credential(credential));

        LOG.log(Level.INFO, "authentication result:{0}", status);

        if (status.equals(SEND_CONTINUE)) {
            // Authentication mechanism has send a redirect, should not
            // send anything to response from JSF now.
            context.responseComplete();
        } else if (status.equals(SEND_FAILURE)) {
            addError(context, "Authentication failed");
        }

    }
 
Example #3
Source File: LoginBean.java    From ee8-sandbox with Apache License 2.0 6 votes vote down vote up
public void login() {

        FacesContext context = FacesContext.getCurrentInstance();
        Credential credential = new UsernamePasswordCredential(username, new Password(password));

        AuthenticationStatus status = securityContext.authenticate(
                getRequest(context),
                getResponse(context),
                withParams()
                        .credential(credential));

        LOG.info("authentication result:" + status);

        if (status.equals(SEND_CONTINUE)) {
            // Authentication mechanism has send a redirect, should not
            // send anything to response from JSF now.
            context.responseComplete();
        } else if (status.equals(SEND_FAILURE)) {
            addError(context, "Authentication failed");
        }

    }
 
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: LoginBean.java    From Java-EE-8-Sampler with MIT License 6 votes vote down vote up
public void login() {
    
    Credential credential = new UsernamePasswordCredential(username, new Password(password));
    
    AuthenticationStatus status = securityContext.authenticate(
        getRequestFrom(facesContext),
        getResponseFrom(facesContext),
        withParams().credential(credential));
    
    if (status.equals(SEND_CONTINUE)) {
        facesContext.responseComplete();
    } else if (status.equals(SEND_FAILURE)) {
        addError(facesContext, "Authentication failed");
    }
    
}
 
Example #6
Source File: AuthenticationMechanism.java    From javaee8-cookbook with Apache License 2.0 6 votes vote down vote up
@Override
public AuthenticationStatus validateRequest(HttpServletRequest request, HttpServletResponse response, HttpMessageContext httpMessageContext) throws AuthenticationException {

    if (httpMessageContext.isAuthenticationRequest()) {

        Credential credential = httpMessageContext.getAuthParameters().getCredential();
        if (!(credential instanceof CallerOnlyCredential)) {
            throw new IllegalStateException("Invalid mechanism");
        }

        CallerOnlyCredential callerOnlyCredential = (CallerOnlyCredential) credential;

        if ("user".equals(callerOnlyCredential.getCaller())) {
            return httpMessageContext.notifyContainerAboutLogin(callerOnlyCredential.getCaller(), new HashSet<>(Arrays.asList("role1","role2")));
        } else{
            throw new AuthenticationException();
        }

    }

    return httpMessageContext.doNothing();
}
 
Example #7
Source File: OperationServlet.java    From javaee8-cookbook with Apache License 2.0 5 votes vote down vote up
@Override
public void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {

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

    Credential credential = new UsernamePasswordCredential(name, new Password(password));

    AuthenticationStatus status = securityContext.authenticate(
            request, response, withParams().credential(credential));

    response.getWriter().write("Role \"admin\" access: " + request.isUserInRole(Roles.ADMIN) + "\n");
    response.getWriter().write("Role \"user\" access: " + request.isUserInRole(Roles.USER) + "\n");

    if (status.equals(AuthenticationStatus.SUCCESS)) {

        if (request.isUserInRole(Roles.ADMIN)) {
            userActivity.adminOperation();
            response.getWriter().write("adminOperation executed: true\n");
        } else if (request.isUserInRole(Roles.USER)) {
            userActivity.userOperation();
            response.getWriter().write("userOperation executed: true\n");
        }

        userActivity.everyoneCanDo();
        response.getWriter().write("everyoneCanDo executed: true\n");

    } else {
        response.getWriter().write("Authentication failed\n");
    }

}
 
Example #8
Source File: AuthenticationMechanism.java    From javaee8-cookbook with Apache License 2.0 5 votes vote down vote up
@Override
public AuthenticationStatus validateRequest(HttpServletRequest request, HttpServletResponse response, HttpMessageContext httpMessageContext) throws AuthenticationException {

    if (httpMessageContext.isAuthenticationRequest()) {

        Credential credential = httpMessageContext.getAuthParameters().getCredential();
        if (!(credential instanceof UsernamePasswordCredential)) {
            throw new IllegalStateException("Invalid mechanism");
        }

        return httpMessageContext.notifyContainerAboutLogin(identityStore.validate(credential));
    }

    return httpMessageContext.doNothing();
}
 
Example #9
Source File: AuthenticationMechanism.java    From javaee8-cookbook with Apache License 2.0 5 votes vote down vote up
@Override
public AuthenticationStatus validateRequest(HttpServletRequest request, HttpServletResponse response, HttpMessageContext httpMessageContext) throws AuthenticationException {

    if (httpMessageContext.isAuthenticationRequest()) {

        Credential credential = httpMessageContext.getAuthParameters().getCredential();
        if (!(credential instanceof CallerOnlyCredential)) {
            throw new IllegalStateException("Invalid mechanism");
        }

        CallerOnlyCredential callerOnlyCredential = (CallerOnlyCredential) credential;

        if (null == callerOnlyCredential.getCaller()) {
            throw new AuthenticationException();
        } else switch (callerOnlyCredential.getCaller()) {
            case "user1":
                return httpMessageContext.notifyContainerAboutLogin(callerOnlyCredential.getCaller(), new HashSet<>(asList(Roles.ROLE1)));
            case "user2":
                return httpMessageContext.notifyContainerAboutLogin(callerOnlyCredential.getCaller(), new HashSet<>(asList(Roles.ROLE2)));
            case "user3":
                return httpMessageContext.notifyContainerAboutLogin(callerOnlyCredential.getCaller(), new HashSet<>(asList(Roles.ROLE3)));
            default:
                throw new AuthenticationException();
        }

    }

    return httpMessageContext.doNothing();
}
 
Example #10
Source File: AuthenticationMechanism.java    From javaee8-cookbook with Apache License 2.0 5 votes vote down vote up
@Override
public AuthenticationStatus validateRequest(HttpServletRequest request, HttpServletResponse response, HttpMessageContext httpMessageContext) throws AuthenticationException {

    if (httpMessageContext.isAuthenticationRequest()) {

        Credential credential = httpMessageContext.getAuthParameters().getCredential();
        if (!(credential instanceof CallerOnlyCredential)) {
            throw new IllegalStateException("Invalid mechanism");
        }

        CallerOnlyCredential callerOnlyCredential = (CallerOnlyCredential) credential;

        if (null == callerOnlyCredential.getCaller()) {
            throw new AuthenticationException();
        } else switch (callerOnlyCredential.getCaller()) {
            case Roles.ADMIN:
                return httpMessageContext.notifyContainerAboutLogin(callerOnlyCredential.getCaller(), new HashSet<>(asList(Roles.ADMIN)));
            case Roles.USER:
                return httpMessageContext.notifyContainerAboutLogin(callerOnlyCredential.getCaller(), new HashSet<>(asList(Roles.USER)));
            default:
                throw new AuthenticationException();
        }

    }

    return httpMessageContext.doNothing();
}
 
Example #11
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 #12
Source File: CustomAuthenticationMechanism.java    From javaee8-jsf-sample with GNU General Public License v3.0 5 votes vote down vote up
@Override
public AuthenticationStatus validateRequest(
        HttpServletRequest request, 
        HttpServletResponse response, 
        HttpMessageContext context) throws AuthenticationException {
    
    Credential credential = context.getAuthParameters().getCredential();

    if (credential != null) {
        return context.notifyContainerAboutLogin(identityStore.validate(credential));
    } else {
        return context.doNothing();
    }
}
 
Example #13
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 #14
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 #15
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 #16
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 #17
Source File: LoginBean.java    From tutorials with MIT License 5 votes vote down vote up
public void login() {
    Credential credential = new UsernamePasswordCredential(username, new Password(password));
    AuthenticationStatus status = securityContext.authenticate(
            getHttpRequestFromFacesContext(),
            getHttpResponseFromFacesContext(),
            withParams().credential(credential));
    if (status.equals(SEND_CONTINUE)) {
        facesContext.responseComplete();
    } else if (status.equals(SEND_FAILURE)) {
        facesContext.addMessage(null,
                new FacesMessage(SEVERITY_ERROR, "Authentication failed", null));
    }
}
 
Example #18
Source File: AuthenticationParameters.java    From tomee with Apache License 2.0 4 votes vote down vote up
public Credential getCredential() {
    return credential;
}
 
Example #19
Source File: AuthenticationParameters.java    From tomee with Apache License 2.0 4 votes vote down vote up
public void setCredential(Credential credential) {
    this.credential = credential;
}
 
Example #20
Source File: IdentityStoreWrapper.java    From tomee with Apache License 2.0 4 votes vote down vote up
@Override
public CredentialValidationResult validate(Credential credential) {
    return getWrapped().validate(credential);
}
 
Example #21
Source File: IdentityStoreHandler.java    From tomee with Apache License 2.0 votes vote down vote up
CredentialValidationResult validate(Credential credential);