javax.security.enterprise.authentication.mechanism.http.HttpMessageContext Java Examples

The following examples show how to use javax.security.enterprise.authentication.mechanism.http.HttpMessageContext. 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: 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 #2
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 #3
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 #4
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 #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: 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 #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: 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 #10
Source File: TomEESecurityServletAuthenticationMechanismMapper.java    From tomee with Apache License 2.0 5 votes vote down vote up
public HttpAuthenticationMechanism getCurrentAuthenticationMechanism(final HttpMessageContext httpMessageContext) {
    final HttpServletRequest request = httpMessageContext.getRequest();

    if (request.getRequestURI().endsWith("j_security_check")) {
        return CDI.current().select(FormAuthenticationMechanism.class).get();
    }

    final String servletName = request.getHttpServletMapping().getServletName();
    return servletAuthenticationMapper.getOrDefault(servletName, defaultAuthenticationMechanism);
}
 
Example #11
Source File: LoginToContinueInterceptor.java    From tomee with Apache License 2.0 5 votes vote down vote up
@AroundInvoke
public Object intercept(final InvocationContext invocationContext) throws Exception {
    if (invocationContext.getMethod().getName().equals("validateRequest") &&
        Arrays.equals(invocationContext.getMethod().getParameterTypes(), new Class<?>[]{
                HttpServletRequest.class,
                HttpServletResponse.class,
                HttpMessageContext.class
        })) {
        return validateRequest(invocationContext);
    }

    return invocationContext.proceed();
}
 
Example #12
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 #13
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 #14
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 #15
Source File: AutoApplySessionInterceptor.java    From tomee with Apache License 2.0 5 votes vote down vote up
@AroundInvoke
public Object intercept(final InvocationContext invocationContext) throws Exception {
    if (invocationContext.getMethod().getName().equals("validateRequest") &&
        Arrays.equals(invocationContext.getMethod().getParameterTypes(), new Class<?>[]{
                HttpServletRequest.class,
                HttpServletResponse.class,
                HttpMessageContext.class
        })) {
        return validateRequest(invocationContext);
    }

    return invocationContext.proceed();
}
 
Example #16
Source File: RememberMeInterceptor.java    From tomee with Apache License 2.0 5 votes vote down vote up
@AroundInvoke
public Object intercept(final InvocationContext invocationContext) throws Exception {
    if (invocationContext.getMethod().getName().equals("validateRequest") &&
        Arrays.equals(invocationContext.getMethod().getParameterTypes(), new Class<?>[]{
                HttpServletRequest.class,
                HttpServletResponse.class,
                HttpMessageContext.class
        })) {

        if (rememberMeIdentityStore.isUnsatisfied()) {
            throw new IllegalStateException("RememberMe annotated AuthenticationMechanism  " +
                                            httpMechanismBean.getBeanClass() +
                                            " required an implementation of RememberMeIndentityStore");
        }

        if (rememberMeIdentityStore.isAmbiguous()) {
            throw new IllegalStateException(
                    "Multiple implementations of RememberMeIndentityStore found. Only one should be supplied.");
        }

        return validateRequest(invocationContext);
    }

    if (invocationContext.getMethod().getName().equals("cleanSubject") &&
        Arrays.equals(invocationContext.getMethod().getParameterTypes(), new Class<?>[]{
                HttpServletRequest.class,
                HttpServletResponse.class,
                HttpMessageContext.class
        })) {
        cleanSubject(invocationContext);
    }

    return invocationContext.proceed();
}
 
Example #17
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 #18
Source File: RememberMeInterceptor.java    From tomee with Apache License 2.0 5 votes vote down vote up
private void cleanSubject(final InvocationContext invocationContext) throws Exception {
    final HttpMessageContext httpMessageContext = (HttpMessageContext) invocationContext.getParameters()[2];

    final RememberMe rememberMe = getRememberMe();
    getCookie(httpMessageContext.getRequest(), rememberMe.cookieName())
            .ifPresent(cookie -> {
                rememberMeIdentityStore.get().removeLoginToken(cookie.getValue());

                cookie.setMaxAge(0);
                httpMessageContext.getResponse().addCookie(cookie);
            });

    invocationContext.proceed();
}
 
Example #19
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 #20
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 #21
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 #22
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 #23
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 #24
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 #25
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 #26
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 #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: 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 #29
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 #30
Source File: JwtAuthenticationMechanism.java    From javaee8-jaxrs-sample with GNU General Public License v3.0 5 votes vote down vote up
/**
 * To extract the JWT from Authorization HTTP header
 *
 * @param context
 * @return The JWT access tokens
 */
private String extractToken(HttpMessageContext context) {
    String authorizationHeader = context.getRequest().getHeader(HttpHeaders.AUTHORIZATION);
    if (authorizationHeader != null && authorizationHeader.startsWith(AUTHORIZATION_PREFIX)) {
        String token = authorizationHeader.substring(AUTHORIZATION_PREFIX.length(), authorizationHeader.length());
        return token;
    }
    return null;
}