Search in sources :

Example 1 with Token

use of com.macasaet.fernet.Token in project fernet-java8 by l0s.

the class AuthenticationResource method createSession.

/**
 * This is an example of an endpoint that generates a new Fernet token. The
 * client authenticates using this method then can use the token provided to
 * perform secured operations. The client may, at their discretion, store
 * the token insecurely (e.g. in a cookie or browser storage) since it will
 * no longer be valid after the TTL (60 seconds by default).
 *
 * @param request
 *            client credentials to create a new session token
 * @return a Fernet token
 */
@POST
@Produces(MediaType.TEXT_PLAIN)
@Consumes(MediaType.APPLICATION_JSON)
public String createSession(final LoginRequest request) {
    final User user = repository.findUser(request.getUsername());
    if (user != null && user.isPasswordCorrect(request.getSingleRoundPasswordHash())) {
        // password is correct, so generate an ephemeral session
        // store the session ID in the token payload
        final Session session = new Session(request.getUsername());
        sessionRepository.saveSession(session);
        final Key key = keySupplier.get().iterator().next();
        final Token token = Token.generate(random, key, session.getId().toString());
        return token.serialise();
    }
    throw new NotAuthorizedException(Response.status(Status.UNAUTHORIZED).entity("invalid login").build());
}
Also used : Token(com.macasaet.fernet.Token) NotAuthorizedException(javax.ws.rs.NotAuthorizedException) Key(com.macasaet.fernet.Key) POST(javax.ws.rs.POST) Produces(javax.ws.rs.Produces) Consumes(javax.ws.rs.Consumes)

Example 2 with Token

use of com.macasaet.fernet.Token in project fernet-java8 by l0s.

the class TokenInjectionIT method verifyFailedForgery.

/**
 * This demonstrates a client who attempts to forge a Fernet token but
 * cannot do so without knowing the secret key.
 */
@Test
public final void verifyFailedForgery() {
    // given
    final SecureRandom random = new SecureRandom();
    final Key invalidKey = Key.generateKey(random);
    final Token forgedToken = Token.generate(random, invalidKey, UUID.randomUUID().toString());
    final String tokenString = forgedToken.serialise();
    // when / then
    assertThrows(ForbiddenException.class, () -> target("secrets").request().header("Authorization", "Bearer\t" + tokenString).get(String.class));
}
Also used : SecureRandom(java.security.SecureRandom) Token(com.macasaet.fernet.Token) Key(com.macasaet.fernet.Key) Test(org.junit.Test) JerseyTest(org.glassfish.jersey.test.JerseyTest)

Example 3 with Token

use of com.macasaet.fernet.Token in project fernet-java8 by l0s.

the class TokenHeaderUtilityTest method verifyGetAuthorizationTokenIgnoresX.

@Test
public final void verifyGetAuthorizationTokenIgnoresX() {
    // given
    final Key key = Key.generateKey(random);
    final Token token = Token.generate(random, key, "hello");
    final ContainerRequest request = mock(ContainerRequest.class);
    given(request.getHeaderString("X-Authorization")).willReturn(token.serialise());
    // when
    final Token result = utility.getAuthorizationToken(request);
    // then
    assertNull(result);
}
Also used : Token(com.macasaet.fernet.Token) ContainerRequest(org.glassfish.jersey.server.ContainerRequest) Key(com.macasaet.fernet.Key) Test(org.junit.Test)

Example 4 with Token

use of com.macasaet.fernet.Token in project fernet-java8 by l0s.

the class ProtocolBuffersExampleIT method createSession.

/**
 * Start a new session.
 *
 * @return a serialised Fernet token with a {@link Session} embedded in the payload
 */
@POST
@Path("/api/sessions")
public String createSession(@Context final HttpServletResponse servletResponse) {
    final String sessionId = UUID.randomUUID().toString();
    final Builder builder = Session.newBuilder();
    builder.setSessionId(sessionId);
    builder.setRenewalCount(0);
    builder.setStartTime(Instant.now().getEpochSecond());
    servletResponse.addHeader("Location", "/api/sessions/" + sessionId);
    final Session session = builder.build();
    // persist session in server-side data store
    final Token token = Token.generate(random, key, session.toByteArray());
    return token.serialise();
}
Also used : Builder(com.macasaet.fernet.example.pb.Example.Session.Builder) Token(com.macasaet.fernet.Token) Session(com.macasaet.fernet.example.pb.Example.Session) Path(javax.ws.rs.Path) POST(javax.ws.rs.POST)

Example 5 with Token

use of com.macasaet.fernet.Token in project fernet-java8 by l0s.

the class ProtectedResource method issueToken.

/**
 * @param username a valid username
 * @param password the password for the user <em>username</em>
 * @return a new Fernet token if and only if the credentials are valid
 * @throws NotAuthorizedException if invalid credentials are provided
 */
@POST
@Path("token")
public String issueToken(final String username, final String password) {
    if ("username".equals(username) && "password".equals(password)) {
        // might be nice to have Token.generate(repository, payload)
        final Key primaryKey = getKeyRepository().getPrimaryKey();
        final Token token = Token.generate(random, primaryKey, username);
        return token.serialise();
    }
    throw new NotAuthorizedException("Bearer realm=\"secrets\"");
}
Also used : Token(com.macasaet.fernet.Token) NotAuthorizedException(javax.ws.rs.NotAuthorizedException) Key(com.macasaet.fernet.Key) Path(javax.ws.rs.Path) POST(javax.ws.rs.POST)

Aggregations

Token (com.macasaet.fernet.Token)17 Key (com.macasaet.fernet.Key)10 Test (org.junit.Test)9 Path (javax.ws.rs.Path)6 ContainerRequest (org.glassfish.jersey.server.ContainerRequest)6 NotAuthorizedException (javax.ws.rs.NotAuthorizedException)5 SecureRandom (java.security.SecureRandom)3 Consumes (javax.ws.rs.Consumes)3 POST (javax.ws.rs.POST)3 PUT (javax.ws.rs.PUT)3 JerseyTest (org.glassfish.jersey.test.JerseyTest)3 Session (com.macasaet.fernet.example.pb.Example.Session)2 Builder (com.macasaet.fernet.example.pb.Example.Session.Builder)2 FernetToken (com.macasaet.fernet.jaxrs.FernetToken)2 Produces (javax.ws.rs.Produces)2 Instant (java.time.Instant)1 IvParameterSpec (javax.crypto.spec.IvParameterSpec)1 BadRequestException (javax.ws.rs.BadRequestException)1 GET (javax.ws.rs.GET)1 WebApplicationException (javax.ws.rs.WebApplicationException)1