javax.security.enterprise.credential.UsernamePasswordCredential Java Examples

The following examples show how to use javax.security.enterprise.credential.UsernamePasswordCredential. 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 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 #2
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 #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: 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 #5
Source File: SecurityContextTest.java    From tomee with Apache License 2.0 6 votes vote down vote up
@Override
protected void doGet(final HttpServletRequest req, final HttpServletResponse resp)
        throws ServletException, IOException {

    final AuthenticationParameters parameters =
            AuthenticationParameters.withParams()
                                    .credential(new UsernamePasswordCredential(req.getParameter("username"),
                                                                               req.getParameter("password")))
                                    .newAuthentication(true);

    securityContext.authenticate(req, resp, parameters);

    final Principal callerPrincipal = securityContext.getCallerPrincipal();

    resp.getWriter().write(callerPrincipal.getName());
}
 
Example #6
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 #7
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 #8
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 #9
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 #10
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 #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: 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 #13
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 #14
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 #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: 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 #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: FormAuthenticationMechanism.java    From tomee with Apache License 2.0 5 votes vote down vote up
@Override
public AuthenticationStatus validateRequest(final HttpServletRequest request, final HttpServletResponse response,
                                            final HttpMessageContext httpMessageContext)
        throws AuthenticationException {

    final String username = request.getParameter("j_username");
    final String password = request.getParameter("j_password");

    if (validateForm(httpMessageContext.getRequest(), username, password)) {
        return httpMessageContext.notifyContainerAboutLogin(
                identityStoreHandler.validate(new UsernamePasswordCredential(username, password)));
    }

    return httpMessageContext.doNothing();
}
 
Example #19
Source File: SecurityContextTest.java    From tomee with Apache License 2.0 5 votes vote down vote up
@Override
protected void doGet(final HttpServletRequest req, final HttpServletResponse resp)
        throws ServletException, IOException {

    final AuthenticationParameters parameters =
            AuthenticationParameters.withParams()
                                    .credential(new UsernamePasswordCredential(req.getParameter("username"),
                                                                               req.getParameter("password")))
                                    .newAuthentication(true);

    securityContext.authenticate(req, resp, parameters);

    resp.getWriter().write("ok!");
}
 
Example #20
Source File: SecurityContextTest.java    From tomee with Apache License 2.0 5 votes vote down vote up
@Override
protected void doGet(final HttpServletRequest req, final HttpServletResponse resp)
        throws ServletException, IOException {

    final AuthenticationParameters parameters =
            AuthenticationParameters.withParams()
                                    .credential(new UsernamePasswordCredential(req.getParameter("username"),
                                                                               req.getParameter("password")))
                                    .newAuthentication(true);

    securityContext.authenticate(req, resp, parameters);

    resp.getWriter().write(securityContext.isCallerInRole(req.getParameter("role")) ? "ok" : "nok");
}
 
Example #21
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 #22
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 #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: 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 #25
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 #26
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 #27
Source File: JwtAuthenticationMechanism.java    From javaee8-jaxrs-sample with GNU General Public License v3.0 5 votes vote down vote up
@Override
public AuthenticationStatus validateRequest(HttpServletRequest request, HttpServletResponse response, HttpMessageContext context) {

    LOGGER.log(Level.INFO, "validateRequest: {0}", request.getRequestURI());
    // 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
    String name = request.getParameter("username");
    String password = request.getParameter("password");
    String token = extractToken(context);

    if (name != null && password != null
        && "POST".equals(request.getMethod())
        && request.getRequestURI().endsWith("/auth/login")) {
        LOGGER.log(Level.INFO, "user credentials : {0}, {1}", new String[]{name, password});
        // validation of the credential using the identity store
        CredentialValidationResult result = identityStoreHandler.validate(new UsernamePasswordCredential(name, password));
        if (result.getStatus() == CredentialValidationResult.Status.VALID) {
            // Communicate the details of the authenticated user to the container and return SUCCESS.
            return createToken(result, context);
        }
        // if the authentication failed, we return the unauthorized status in the http response
        return context.responseUnauthorized();
    } else if (token != null) {
        // validation of the jwt credential
        return validateToken(token, context);
    } else if (context.isProtected()) {
        // A protected resource is a resource for which a constraint has been defined.
        // if there are no credentials and the resource is protected, we response with unauthorized status
        return context.responseUnauthorized();
    }
    // there are no credentials AND the resource is not protected, 
    // SO Instructs the container to "do nothing"
    return context.doNothing();
}
 
Example #28
Source File: TestIdentityStore.java    From Architecting-Modern-Java-EE-Applications with MIT License 5 votes vote down vote up
public CredentialValidationResult validate(UsernamePasswordCredential usernamePasswordCredential) {

        // validate
        // ...
        if (usernamePasswordCredential.compareTo("duke", "helloWorld")) {
            return new CredentialValidationResult("duke", singleton("admin"));
        }

        return CredentialValidationResult.INVALID_RESULT;
    }
 
Example #29
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();
    }

}
 
Example #30
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;
    }