Java Code Examples for javax.security.enterprise.authentication.mechanism.http.HttpMessageContext#notifyContainerAboutLogin()

The following examples show how to use javax.security.enterprise.authentication.mechanism.http.HttpMessageContext#notifyContainerAboutLogin() . 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: 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 2
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 3
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 4
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 5
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 6
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 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: 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 9
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 10
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();
}
 
Example 11
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 12
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 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: 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: 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 16
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 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 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 18
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 19
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();
    }
}