javax.security.enterprise.AuthenticationStatus Java Examples

The following examples show how to use javax.security.enterprise.AuthenticationStatus. 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: TomEESecurityContext.java    From tomee with Apache License 2.0 6 votes vote down vote up
@Override
public AuthenticationStatus authenticate(final HttpServletRequest request,
                                         final HttpServletResponse response,
                                         final AuthenticationParameters parameters) {

    try {
        final MessageInfo messageInfo = new TomEEMessageInfo(request, response, true, parameters);
        final ServerAuthContext serverAuthContext = getServerAuthContext(request);
        final AuthStatus authStatus = serverAuthContext.validateRequest(messageInfo, new Subject(), null);

        return mapToAuthenticationStatus(authStatus);

    } catch (final AuthException e) {
        return AuthenticationStatus.SEND_FAILURE;
    }
}
 
Example #2
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 #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.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 #4
Source File: AutoApplySessionInterceptor.java    From tomee with Apache License 2.0 6 votes vote down vote up
private AuthenticationStatus validateRequest(final InvocationContext invocationContext)
        throws Exception {

    final HttpMessageContext httpMessageContext = (HttpMessageContext) invocationContext.getParameters()[2];

    final Principal principal = httpMessageContext.getRequest().getUserPrincipal();
    if (principal == null) {
        final Object authenticationStatus = invocationContext.proceed();

        if (AuthenticationStatus.SUCCESS.equals(authenticationStatus)) {
            httpMessageContext.getMessageInfo().getMap().put("javax.servlet.http.registerSession", "true");
        }

        return (AuthenticationStatus) authenticationStatus;
    } else {
        final CallerPrincipalCallback callerPrincipalCallback =
                new CallerPrincipalCallback(httpMessageContext.getClientSubject(), principal);

        httpMessageContext.getHandler().handle(new Callback[] {callerPrincipalCallback});

        return AuthenticationStatus.SUCCESS;
    }
}
 
Example #5
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 #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: JwtAuthenticationMechanism.java    From javaee8-jaxrs-sample with GNU General Public License v3.0 6 votes vote down vote up
/**
 * To validate the JWT token e.g Signature check, JWT claims check(expiration) etc
 *
 * @param token The JWT access tokens
 * @param context
 * @return the AuthenticationStatus to notify the container
 */
private AuthenticationStatus validateToken(String token, HttpMessageContext context) {
    try {
        if (tokenProvider.validateToken(token)) {
            JwtCredential credential = tokenProvider.getCredential(token);

            //fire an @Authenticated CDI event.
            authenticatedEvent.fire(new UserInfo(credential.getPrincipal(), credential.getAuthorities()));

            return context.notifyContainerAboutLogin(credential.getPrincipal(), credential.getAuthorities());
        }
        // if token invalid, response with unauthorized status
        return context.responseUnauthorized();
    } catch (ExpiredJwtException eje) {
        LOGGER.log(Level.INFO, "Security exception for user {0} - {1}", new String[]{eje.getClaims().getSubject(), eje.getMessage()});
        return context.responseUnauthorized();
    }
}
 
Example #8
Source File: JWTHttpAuthenticationMechanism.java    From smallrye-jwt with Apache License 2.0 6 votes vote down vote up
@Override
public AuthenticationStatus validateRequest(HttpServletRequest request,
        HttpServletResponse response,
        HttpMessageContext httpMessageContext)
        throws AuthenticationException {

    AbstractBearerTokenExtractor extractor = new BearerTokenExtractor(request, authContextInfo);
    String bearerToken = extractor.getBearerToken();

    if (bearerToken != null) {
        try {
            JsonWebToken jwtPrincipal = jwtParser.parse(bearerToken);
            producer.setJsonWebToken(jwtPrincipal);
            Set<String> groups = jwtPrincipal.getGroups();
            MechanismLogging.log.success();
            return httpMessageContext.notifyContainerAboutLogin(jwtPrincipal, groups);
        } catch (Exception e) {
            MechanismLogging.log.unableToValidateBearerToken(e);
            return httpMessageContext.responseUnauthorized();
        }
    } else {
        MechanismLogging.log.noUsableBearerTokenFound();
        return httpMessageContext.isProtected() ? httpMessageContext.responseUnauthorized()
                : httpMessageContext.doNothing();
    }
}
 
Example #9
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 #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: 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 #12
Source File: TomEEHttpMessageContext.java    From tomee with Apache License 2.0 6 votes vote down vote up
@Override
public AuthenticationStatus notifyContainerAboutLogin(final Principal principal, final Set<String> groups) {

    try {
        handler.handle(new Callback[] {
                new CallerPrincipalCallback(clientSubject, principal),
                new GroupPrincipalCallback(clientSubject, groups.toArray(new String[groups.size()]))
        });
    } catch (final IOException | UnsupportedCallbackException e) {
        e.printStackTrace();
    }

    this.principal = principal;
    this.groups = groups;

    TomEESecurityContext.registerContainerAboutLogin(principal, groups);

    return SUCCESS;
}
 
Example #13
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 #14
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 #15
Source File: UserAuthenticationServlet.java    From javaee8-cookbook with Apache License 2.0 6 votes vote down vote up
@Override
public void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {

    String name = request.getParameter("name");
    if (null != name || !"".equals(name)) {
        AuthenticationStatus status = securityContext.authenticate(
                request, response, AuthenticationParameters.withParams().credential(new CallerOnlyCredential(name)));

        response.getWriter().write("Authentication status: " + status.name() + "\n");
    }

    String principal = null;
    if (request.getUserPrincipal() != null) {
        principal = request.getUserPrincipal().getName();
    }

    response.getWriter().write("User: " + principal + "\n");
    response.getWriter().write("Role \"role1\" access: " + request.isUserInRole("role1") + "\n");
    response.getWriter().write("Role \"role2\" access: " + request.isUserInRole("role2") + "\n");
    response.getWriter().write("Role \"role3\" access: " + request.isUserInRole("role3") + "\n");
    response.getWriter().write("Access to /authServlet? " + securityContext.hasAccessToWebResource("/authServlet") + "\n");
}
 
Example #16
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 #17
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 #18
Source File: TomEESecurityContext.java    From tomee with Apache License 2.0 5 votes vote down vote up
private AuthenticationStatus mapToAuthenticationStatus(final AuthStatus authStatus) {
    if (SUCCESS.equals(authStatus)) {
        return AuthenticationStatus.SUCCESS;
    }

    if (SEND_FAILURE.equals(authStatus)) {
        return AuthenticationStatus.SEND_FAILURE;
    }

    if (SEND_CONTINUE.equals(authStatus)) {
        return AuthenticationStatus.SEND_CONTINUE;
    }

    throw new IllegalArgumentException();
}
 
Example #19
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 #20
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 #21
Source File: TomEESecurityServerAuthModule.java    From tomee with Apache License 2.0 5 votes vote down vote up
@Override
public AuthStatus validateRequest(final MessageInfo messageInfo, final Subject clientSubject,
                                  final Subject serviceSubject)
        throws AuthException {

    final HttpMessageContext httpMessageContext =
            httpMessageContext(handler, messageInfo, clientSubject, serviceSubject);

    final HttpAuthenticationMechanism authenticationMechanism =
            CDI.current()
               .select(TomEESecurityServletAuthenticationMechanismMapper.class)
               .get()
               .getCurrentAuthenticationMechanism(httpMessageContext);

    final AuthenticationStatus authenticationStatus;
    try {
        authenticationStatus =
                authenticationMechanism.validateRequest(httpMessageContext.getRequest(),
                                                        httpMessageContext.getResponse(),
                                                        httpMessageContext);


    } catch (final AuthenticationException e) {
        final AuthException authException = new AuthException(e.getMessage());
        authException.initCause(e);
        throw authException;
    }

    return mapToAuthStatus(authenticationStatus);
}
 
Example #22
Source File: TomEESecurityServerAuthModule.java    From tomee with Apache License 2.0 5 votes vote down vote up
private AuthStatus mapToAuthStatus(final AuthenticationStatus authenticationStatus) {
    switch (authenticationStatus) {
        case SUCCESS:
        case NOT_DONE:
            return AuthStatus.SUCCESS;
        case SEND_FAILURE:
            return AuthStatus.SEND_FAILURE;
        case SEND_CONTINUE:
            return AuthStatus.SEND_CONTINUE;
        default:
            throw new IllegalArgumentException();
    }
}
 
Example #23
Source File: LoginToContinueInterceptor.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];
    clearStaleState(httpMessageContext);

    if (httpMessageContext.getAuthParameters().isNewAuthentication()) {
        return processCallerInitiatedAuthentication(httpMessageContext);
    } else {
        return processContainerInitiatedAuthentication(invocationContext, httpMessageContext);
    }
}
 
Example #24
Source File: DefaultAuthenticationMechanism.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 {
    return httpMessageContext.doNothing();
}
 
Example #25
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 #26
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 #27
Source File: HttpAuthenticationMechanismWrapper.java    From tomee with Apache License 2.0 5 votes vote down vote up
@Override
public AuthenticationStatus validateRequest(HttpServletRequest request,
                                            HttpServletResponse response,
                                            HttpMessageContext httpMessageContext)
        throws AuthenticationException {
    return getWrapped().validateRequest(request, response, httpMessageContext);
}
 
Example #28
Source File: HttpAuthenticationMechanismWrapper.java    From tomee with Apache License 2.0 5 votes vote down vote up
@Override
public AuthenticationStatus secureResponse(HttpServletRequest request,
                                           HttpServletResponse response,
                                           HttpMessageContext httpMessageContext)
        throws AuthenticationException {
    return getWrapped().secureResponse(request, response, httpMessageContext);
}
 
Example #29
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 #30
Source File: CustomAuthentication.java    From tutorials with MIT License 5 votes vote down vote up
@Override
public AuthenticationStatus validateRequest(HttpServletRequest httpServletRequest,
                                            HttpServletResponse httpServletResponse,
                                            HttpMessageContext httpMessageContext) throws AuthenticationException {
    String username = httpServletRequest.getParameter("username");
    String password = httpServletRequest.getParameter("password");
    //Mocking UserDetail, but in real life, we can find it from a database.
    UserDetail userDetail = findByUserNameAndPassword(username, password);
    if (userDetail != null) {
        return httpMessageContext.notifyContainerAboutLogin(
                new CustomPrincipal(userDetail),
                new HashSet<>(userDetail.getRoles()));
    }
    return httpMessageContext.responseUnauthorized();
}