DZone
Thanks for visiting DZone today,
Edit Profile
  • Manage Email Subscriptions
  • How to Post to DZone
  • Article Submission Guidelines
Sign Out View Profile
  • Post an Article
  • Manage My Drafts
Over 2 million developers have joined DZone.
Log In / Join
Please enter at least three characters to search
Refcards Trend Reports
Events Video Library
Refcards
Trend Reports

Events

View Events Video Library

Zones

Culture and Methodologies Agile Career Development Methodologies Team Management
Data Engineering AI/ML Big Data Data Databases IoT
Software Design and Architecture Cloud Architecture Containers Integration Microservices Performance Security
Coding Frameworks Java JavaScript Languages Tools
Testing, Deployment, and Maintenance Deployment DevOps and CI/CD Maintenance Monitoring and Observability Testing, Tools, and Frameworks
Culture and Methodologies
Agile Career Development Methodologies Team Management
Data Engineering
AI/ML Big Data Data Databases IoT
Software Design and Architecture
Cloud Architecture Containers Integration Microservices Performance Security
Coding
Frameworks Java JavaScript Languages Tools
Testing, Deployment, and Maintenance
Deployment DevOps and CI/CD Maintenance Monitoring and Observability Testing, Tools, and Frameworks

Modernize your data layer. Learn how to design cloud-native database architectures to meet the evolving demands of AI and GenAI workkloads.

Secure your stack and shape the future! Help dev teams across the globe navigate their software supply chain security challenges.

Releasing software shouldn't be stressful or risky. Learn how to leverage progressive delivery techniques to ensure safer deployments.

Avoid machine learning mistakes and boost model performance! Discover key ML patterns, anti-patterns, data strategies, and more.

Related

  • OWASP TOP 10 API Security Part 2 (Broken Object Level Authorization)
  • The Anatomy of a Microservice, One Service, Multiple Servers
  • C# Applications Vulnerability Cheatsheet
  • What D'Hack Is DPoP?

Trending

  • Microsoft Azure Synapse Analytics: Scaling Hurdles and Limitations
  • Unlocking the Potential of Apache Iceberg: A Comprehensive Analysis
  • Create Your Own AI-Powered Virtual Tutor: An Easy Tutorial
  • How the Go Runtime Preempts Goroutines for Efficient Concurrency
  1. DZone
  2. Software Design and Architecture
  3. Cloud Architecture
  4. Custom SecurityContext in JAX-RS

Custom SecurityContext in JAX-RS

An article about how to override the default security-related information associated with a JAX-RS request using a custom SecurityContext.

By 
Abhishek Gupta user avatar
Abhishek Gupta
DZone Core CORE ·
May. 03, 16 · Tutorial
Likes (9)
Comment
Save
Tweet
Share
30.7K Views

Join the DZone community and get the full member experience.

Join For Free

And the JAX-RS juggernaut continues ….

This article briefly talks about how to override the default security-related information associated with a JAX-RS request (i.e., how to mess with the SecurityContext).

Wait... SecurityContext?

Think of it as a JAX-RS abstraction over HTTPServletRequest for security-related information only. This can be used for:

  • figuring out how the caller was authenticated
  • extracting authenticated Principal info
  • role membership confirmation (programmatic authorization)
  • and whether or not the request was initiated securely (over HTTPS)

OK, but why would I need a custom implementation?

It helps when you have a custom authentication mechanism not implemented using the standard Java EE security realm:

  • your web container will not be aware of the authentication details
  • as a result, the SecurityContext instance will not contain the subject, role, or other details (mentioned above)
  • a typical example is token-based authentication, based on custom (app-specific) HTTP headers
@Priority(Priorities.AUTHENTICATION)
public class JWTAuthFilter implements ContainerRequestFilter{
  @Override
  public void filter(ContainerRequestContext requestContext) throws IOException {
        String authHeaderVal = requestContext.getHeaderString("Authorization");

            //consume JWT i.e. execute signature validation
            if(authHeaderVal.startsWith("Bearer")){
            try {
                validate(authHeaderVal.split(" ")[1]);
            } catch (InvalidJwtException ex) {
                requestContext.abortWith(Response.status(Response.Status.UNAUTHORIZED).build());
            }
            }else{
                requestContext.abortWith(Response.status(Response.Status.UNAUTHORIZED).build());
            }
  }


Your RESTful application would definitely want to make use of the authenticated caller. The JAX-RS request pipeline needs to be aware of the associated ‘security context’ and make use of it within its business logic

How to…

SecurityContext is an interface after all...

  • just implement it
  • then inject it (using @Context) and use it in your resource methods
@Priority(Priorities.AUTHENTICATION)
public class AuthFilterWithCustomSecurityContext implements ContainerRequestFilter {
    @Context
    UriInfo uriInfo;

    @Override
    public void filter(ContainerRequestContext requestContext) throws IOException {
        String authHeaderVal = requestContext.getHeaderString("Auth-Token");
        String subject = validateToken(authHeaderVal); //execute custom authentication
        if (subject!=null) {
            final SecurityContext securityContext = requestContext.getSecurityContext();
            requestContext.setSecurityContext(new SecurityContext() {
                        @Override
                        public Principal getUserPrincipal() {
                            return new Principal() {
                                @Override
                                public String getName() {
                                    return subject;
                                }
                            };
                        }

                        @Override
                        public boolean isUserInRole(String role) {
                            List<Role> roles = findUserRoles(subject);
                            return roles.contains(role);
                        }

                        @Override
                        public boolean isSecure() {
                            return uriInfo.getAbsolutePath().toString().startsWith("https");
                        }

                        @Override
                        public String getAuthenticationScheme() {
                            return "Token-Based-Auth-Scheme";
                        }
                    });
        }

    }
}


Cheers!

Web container authentication Java EE Business logic Requests application Abstraction (computer science) Interface (computing) Implementation Web Protocols

Published at DZone with permission of Abhishek Gupta, DZone MVB. See the original article here.

Opinions expressed by DZone contributors are their own.

Related

  • OWASP TOP 10 API Security Part 2 (Broken Object Level Authorization)
  • The Anatomy of a Microservice, One Service, Multiple Servers
  • C# Applications Vulnerability Cheatsheet
  • What D'Hack Is DPoP?

Partner Resources

×

Comments
Oops! Something Went Wrong

The likes didn't load as expected. Please refresh the page and try again.

ABOUT US

  • About DZone
  • Support and feedback
  • Community research
  • Sitemap

ADVERTISE

  • Advertise with DZone

CONTRIBUTE ON DZONE

  • Article Submission Guidelines
  • Become a Contributor
  • Core Program
  • Visit the Writers' Zone

LEGAL

  • Terms of Service
  • Privacy Policy

CONTACT US

  • 3343 Perimeter Hill Drive
  • Suite 100
  • Nashville, TN 37211
  • support@dzone.com

Let's be friends:

Likes
There are no likes...yet! 👀
Be the first to like this post!
It looks like you're not logged in.
Sign in to see who liked this post!