Code Monkey home page Code Monkey logo

auth0-java-mvc-common's Introduction

Auth0 SDK to add authentication to your Java Servlet applications.

Build Status Coverage Status License Maven Central javadoc

Note As part of our ongoing commitment to best security practices, we have rotated the signing keys used to sign previous releases of this SDK. As a result, new patch builds have been released using the new signing key. Please upgrade at your earliest convenience.

While this change won't affect most developers, if you have implemented a dependency signature validation step in your build process, you may notice a warning that past releases can't be verified. This is expected, and a result of the key rotation process. Updating to the latest version will resolve this for you.

๐Ÿ“š Documentation - ๐Ÿš€ Getting Started - ๐Ÿ’ป API Reference ๐Ÿ’ฌ Feedback

Documentation

  • Quickstart - our interactive guide for quickly adding login, logout and user information to a Java Servlet application using Auth0.
  • Sample App - a sample Java Servlet application integrated with Auth0.
  • Examples - code samples for common scenarios.
  • Docs site - explore our docs site and learn more about Auth0.

Getting Started

Requirements

Java 8 or above and javax.servlet version 3.

If you are using Spring, we recommend leveraging Spring's OIDC and OAuth2 support, as demonstrated by the Spring Boot Quickstart.

Installation

Add the dependency via Maven:

<dependency>
  <groupId>com.auth0</groupId>
  <artifactId>mvc-auth-commons</artifactId>
  <version>1.11.0</version>
</dependency>

or Gradle:

implementation 'com.auth0:mvc-auth-commons:1.11.0'

Configure Auth0

Create a Regular Web Application in the Auth0 Dashboard. Verify that the "Token Endpoint Authentication Method" is set to POST.

Next, configure the callback and logout URLs for your application under the "Application URIs" section of the "Settings" page:

  • Allowed Callback URLs: The URL of your application where Auth0 will redirect to during authentication, e.g., http://localhost:3000/callback.
  • Allowed Logout URLs: The URL of your application where Auth0 will redirect to after user logout, e.g., http://localhost:3000/login.

Note the Domain, Client ID, and Client Secret. These values will be used later.

Add login to your application

Create a new AuthenticationController using your Auth0 domain, and Auth0 application client ID and secret. Configure the builder with a JwkProvider for your Auth0 domain.

public class AuthenticationControllerProvider {
    private String domain = "YOUR-AUTH0-DOMAIN";
    private String clientId = "YOUR-CLIENT-ID";
    private String clientSecret = "YOUR-CLIENT-SECRET";
    
    private AuthenticationController authenticationController;
    
    static {
        JwkProvider jwkProvider = new JwkProviderBuilder("YOUR-AUTH0-DOMAIN").build();
        authenticationController = AuthenticationController.newBuilder(domain, clientId, clientSecret)
                .withJwkProvider(jwkProvider)
                .build();
    }
    
    public getInstance() {
        return authenticationController;
    }
}

Note: The AuthenticationController.Builder is not to be reused, and an IllegalStateException will be thrown if build() is called more than once.

Redirect users to the Auth0 login page using the AuthenticationController:

@WebServlet(urlPatterns = {"/login"})
public class LoginServlet extends HttpServlet {

    @Override
    protected void doGet(final HttpServletRequest req, final HttpServletResponse res) throws ServletException, IOException {
        // Where your application will handle the authoriztion callback
        String redirectUrl = "http://localhost:3000/callback";

        String authorizeUrl = AuthenticationControllerProvider
                .getInstance()
                .buildAuthorizeUrl(req, res, redirectUrl)
                .build();
        res.sendRedirect(authorizeUrl);
    }
}

Finally, complete the authentication and obtain the tokens by calling handle() on the AuthenticationController.

@WebServlet(urlPatterns = {"/callback"})
public class CallbackServlet extends HttpServlet {
    
    @Override
    public void doGet(HttpServletRequest req, HttpServletResponse res) throws IOException, ServletException {
        try {
            // authentication complete; the tokens can be stored as needed
            Tokens tokens = AuthenticationControllerProvider
                    .getInstance()
                    .handle(req, res);
            res.sendRedirect("URL-AFTER-AUTHENTICATED");
        } catch (IdentityVerificationException e) {
            // handle authentication error
        }
    }
}

That's it! You have authenticated the user using Auth0.

API Reference

Feedback

Contributing

We appreciate feedback and contribution to this repo! Before you get started, please see the following:

Raise an issue

To provide feedback or report a bug, please raise an issue on our issue tracker.

Vulnerability Reporting

Please do not report security vulnerabilities on the public Github issue tracker. The Responsible Disclosure Program details the procedure for disclosing security issues.


Auth0 Logo

Auth0 is an easy to implement, adaptable authentication and authorization platform. To learn more checkout Why Auth0?

This project is licensed under the MIT license. See the LICENSE file for more info.

auth0-java-mvc-common's People

Contributors

aaguiarz avatar adamjmcgrath avatar cocojoe avatar damieng avatar evansims avatar fossabot avatar jimmyjames avatar joshcanhelp avatar lbalmaceda avatar lgtm-com[bot] avatar luisrudge avatar mureinik avatar poovamraj avatar sre-57-opslevel[bot] avatar widcket avatar

Stargazers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

Watchers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

auth0-java-mvc-common's Issues

Change of dependency scope

Hello,

upgrading from 1.0.0 to 1.0.2, the compilation of my code broke because I was using the com.auth0.jwt.JWT class. Looking at the changes, I found that the scope of some dependencies was changed in revision 196c640#diff-c197962302397baf3a4cc36463dce5ea

In Maven (that I use), this translates into changing the dependency scope from compile to runtime. I assume this is a consequence of moving from "compile" to "implementation" in your build.graddle.

I am not sure why this change was made, or if I am misusing the library. I was for example using in my code the public static method JWT.decode(). Is this something you discourage on purpose?

Sessionless version

Could you create a sessionless version with support for Servlet API 2.5?

Thank you

Login error on certain devices

Description

Login error on certain devices (IOS 12.1.1)

I consulted with the community and they asked me to create an issue on this repository.
https://community.auth0.com/t/login-error-on-certain-devices-using-auth0-java-mvc-common/48286

Reproduction

I'm using this library, but
I'm having a login error on iPhoneXR (IOS12.1.1).
IOS 12.4 is fine.

  • stacktrace

https://community.auth0.com/uploads/short-url/iXilFGOCUUPr61DWmVFCo6oyTLx.txt

  • the code that is causing the error.
public Tokens handle(HttpServletRequest request, HttpServletResponse response) {
  try {
    log.debug("Session:com.auth0.state:" + (String) SessionUtils.get(request, "com.auth0.state")
        + " - getParam:state=" + request.getParameter("state"));

    return authenticationController.handle(request, response);
  } catch (IdentityVerificationException e) {
    var rp = String.format("Request Parameter :%s", LogUtil.toJson(request.getParameterMap()));
    throw new Auth0TokenException(rp, e, CidErrorCode.EAT00102, HttpStatus.BAD_REQUEST);
  }
}

Only on IOS12.1.1, "com.auth0.state" in the session is always null.

Session:com.auth0.state:null - getParam:state=UNE4ldefqJ9zCxAfmGy_hi5f3T1g4t2l7KhE6hYS79k

Environment

  • Version of this library used:
    1.2.0

  • Version of the platform or framework used, if applicable:

    http://jdk.java.net/java-se-ri/11

  • Other relevant versions (language, server software, OS, browser):
    iPhoneXRใ€€OS: 12.1.1 , Safari,Chrome

  • Other modules/plugins/libraries that might be involved:

Directly Support Jakarta 9.1

Describe the problem you'd like to have solved

Could this library be updated to support Jakarta 9.1 and pending version 10?

Describe the ideal solution

Would like to use the buildAuthorizeUrl method without having to cast jakarta.servlet.http.HttpServletRequest to javax.servlet.http.HttpServletRequest and jakarta.servlet.http.HttpServletResponse to javax.servlet.http.HttpServletResponse.

Alternatives and current work-arounds

Currently manually importing/loading the javax.servlet jar into Glassfish 6.2.2 container so that the old namespace is on the classpath of my application.

Sessionless authorization

Please do not report security vulnerabilities here. The Responsible Disclosure Program details the procedure for disclosing security issues.

Thank you in advance for helping us to improve this library! Your attention to detail here is greatly appreciated and will help us respond as quickly as possible. For general support or usage questions, use the Auth0 Community or Auth0 Support. Finally, to avoid duplicates, please search existing Issues before submitting one here.

By submitting an Issue to this repository, you agree to the terms within the Auth0 Code of Conduct.

I thought Auth0 promoted stateless sessions, or did I misunderstand? https://auth0.com/blog/stateless-auth-for-stateful-minds/

Still requesting sessionless/stateless version. Any hopes?

A clear and concise description of what the problem is. Ex. I'm always frustrated when [...]

Authorization with servlet without using sessions

A clear and concise description of what you want to happen.

Hack library

A clear and concise description of any alternatives you've considered or any work-arounds that are currently in place.

You promote sessionless states

Add any other context or screenshots about the feature request here.

https://auth0.com/blog/stateless-auth-for-stateful-minds/

Using Secure Cookie flag when using 'Authorization Code Flow'

TransientCookieStore creates cookie com.auth0.state, but while creating this cookie Secure flag is set only if SameSite is None. But SameSite is always set to Lax in AuthorizeUrl build function when we use default AuthorizationCodeFlow.

Is there a way to use Secure flag while still using default AuthorizationCodeFlow?

We are running some vulnerability scans and one of the issue being highlighted is that cooking com.auth0.state is not secure (Testing using: User-Agent: Mozilla/5.0 (Windows NT 10.0; WOW64; rv:56.0) Gecko/20100101 Firefox/56.0).

Apologies if my understanding is not correct, we are still in the process of learning OAuth. Highly appreciate your help to point us in right direction.

Proxy support

With this library, the tokens are requested internally using OkHttp but we have no way to configure the client. The builder of that client seems to be called inside AuthAPI so we don't have the option to do our own configuration or supply the library with a custom http client implementation.

We are behind a corporate proxy so we have to add the proxy configuration to the builder but this doesn't seem possible with the current implementation.

Add module-info.java

Checklist

  • I have looked into the Readme and the Examples, and have not found a suitable solution or answer.
  • I have looked into the API documentation and have not found a suitable solution or answer.
  • I have searched the issues and have not found a suitable solution or answer.
  • I have searched the Auth0 Community forums and have not found a suitable solution or answer.
  • I agree to the terms within the Auth0 Code of Conduct.

Describe the problem you'd like to have solved

Add support for Java Modules

Describe the ideal solution

Add module-info.java to this library

Alternatives and current workarounds

No response

Additional context

No response

Non-pubic `RandomStorage.setSessionState`

Hello,

When implementing a multi-tenant solution as described at https://auth0.com/docs/tutorials/building-multi-tenant-saas-applications-with-azure-active-directory I'm having some problems because of the limited visibilty of RandomStorage.setSessionState.

I need to (preferably) set the state in the session if I want to use this library for handling the callback etc.

But I cannot call the method RandomStorage.setSessionState

My current work-around is:

String state = secureRandomString();
String authorizeUrl = controller.buildAuthorizeUrl(req, redirectUri)
     .withState(state) // FIXME hack here, we cannot call RandomStorage.setSessionState(request, state); directly
     .build();

model.put("state", state);

It has the same effect but is very ugly, so if the class RandomStorage and the methods setSessionState and setNonce would be public my implementation would be way better.

If desired I can of course create a PR for it :-)

Dependency missing on 1.5.0

1.5.0 depends on com.auth0:java-jwt:3.13.0

Has this been published? Latest I can find in maven central is 3.12.1

README conflicts with actual implementation

The README states:

Keep in mind that this library will not store any value for you, but you can use the SessionUtils class as a helper to store key-value data in the request's Session Storage.

I wish this were true. But AuthorizeUrl.java, lines 181-184:

        // Also store in Session just in case developer uses deprecated
        // AuthenticationController.handle(HttpServletRequest) API
        RandomStorage.setSessionState(request, state);
        RandomStorage.setSessionNonce(request, nonce);

This was giving me NPEs on my tests because I wasn't mocking a session. I'd prefer if you didn't force creation of a session, but that or the documentation needs to be changed.

Support PKCE Flow

Describe the problem you'd like to have solved

What I'm trying to do, is follow the PKCE flow. Meaning I have code_verifier, code_challenge and code_challenge method. What I can do currently is add custom parameters to authorize url. This makes it easy to add code challenge and code challenge method. However, when it comes to using the code_verifier string, the API doesn't really appear to support this. AuthApi.exchangeCode seems to be pretty deadset about the parameters it can send. Meaning I cannot shove a code_verifier in there. The Auth0 request therefore returns a 400 -> missing code_verifier.

Describe the ideal solution

The ideal solution would be a way to work around the request that is actually sent there. Extra parameters, etc.

Alternatives and current work-arounds

I cannot think of a workaround.

Additional information, if any

Using code basically as is from the readme.

       AuthenticationController authController = AuthenticationController.newBuilder(domain, clientId, clientSecret) .build();            
      String authorizeUrl = authController.buildAuthorizeUrl(httpRequest, httpResponse, redirectUri).build()
      ....
      Tokens tokens = authController.handle(httpRequest, httpResponse);
    

https://oauth.net/2/pkce/ mentions:

PKCE is not a replacement for a client secret, and PKCE is recommended even if a client is using a client secret.

Note: Because PKCE is not a replacement for client authentication, it does not allow treating a public client as a confidential client.

PKCE was originally designed to protect the authorization code flow in mobile apps, but its ability to prevent authorization code injection makes it useful for every type of OAuth client, even web apps that use a client secret.

I understand that PKCE, atleast according to Auth0 is meant for single page apps (meaning Angular, ReactJS etc.). But is it really unnecessary as a security measure if we can store a client secret?

Upgrade Guava dependency

Checklist

  • I have looked into the Readme and the Examples, and have not found a suitable solution or answer.
  • I have looked into the API documentation and have not found a suitable solution or answer.
  • I have searched the issues and have not found a suitable solution or answer.
  • I have searched the Auth0 Community forums and have not found a suitable solution or answer.
  • I agree to the terms within the Auth0 Code of Conduct.

Describe the problem you'd like to have solved

This library depends on com.google.guava:guava-annotations:jar:r03:runtime which is over 13 (!!!!) years old. Not only is it no longer supported, it prevents anyone who uses the latest version of Guava from using your library because both JAR files export the same package name. This isn't allowed in Java Modules.

Describe the ideal solution

Upgrade the dependency to the latest version of Guava.

Alternatives and current workarounds

No response

Additional context

No response

Library does not work with recent Servlet containers

Describe the problem you'd like to have solved

The library does not work with recent Servlet containers that implement Jakarta EE.

Describe the ideal solution

A new major version of this library should be made available, that depends on jakarta.servlet instead of javax.servlet.

Whoever wants to use Java EE Servlet containers, can rely on the current major version of this library.

Alternatives and current work-arounds

Currently there does not seem to be an alternative in the com.auth0 group that could be used as a replacement for this library.

Additional information, if any

Jakarta EE was released more than two years ago and is broadly adopted.

Relates to #97

Recommend Projects

  • React photo React

    A declarative, efficient, and flexible JavaScript library for building user interfaces.

  • Vue.js photo Vue.js

    ๐Ÿ–– Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.

  • Typescript photo Typescript

    TypeScript is a superset of JavaScript that compiles to clean JavaScript output.

  • TensorFlow photo TensorFlow

    An Open Source Machine Learning Framework for Everyone

  • Django photo Django

    The Web framework for perfectionists with deadlines.

  • D3 photo D3

    Bring data to life with SVG, Canvas and HTML. ๐Ÿ“Š๐Ÿ“ˆ๐ŸŽ‰

Recommend Topics

  • javascript

    JavaScript (JS) is a lightweight interpreted programming language with first-class functions.

  • web

    Some thing interesting about web. New door for the world.

  • server

    A server is a program made to process requests and deliver data to clients.

  • Machine learning

    Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.

  • Game

    Some thing interesting about game, make everyone happy.

Recommend Org

  • Facebook photo Facebook

    We are working to build community through open source technology. NB: members must have two-factor auth.

  • Microsoft photo Microsoft

    Open source projects and samples from Microsoft.

  • Google photo Google

    Google โค๏ธ Open Source for everyone.

  • D3 photo D3

    Data-Driven Documents codes.