Search in sources :

Example 1 with User

use of com.aidanwhiteley.books.domain.User in project books by aidanwhiteley.

the class UserControllerTest method getUserDetailsWithAuthentication.

@Test
public void getUserDetailsWithAuthentication() {
    User user = BookControllerTestUtils.getTestUser();
    String token = jwtUtils.createTokenForUser(user);
    String xsrfToken = BookControllerTestUtils.getXsrfToken(testRestTemplate);
    HttpEntity<Book> request = BookControllerTestUtils.getBookHttpEntity(null, user, token, xsrfToken);
    ResponseEntity<User> response = testRestTemplate.exchange("/secure/api/user", HttpMethod.GET, request, User.class);
    assertEquals(HttpStatus.OK, response.getStatusCode());
    assertEquals(BookControllerTestUtils.USER_WITH_ALL_ROLES_FULL_NAME, response.getBody().getFullName());
}
Also used : User(com.aidanwhiteley.books.domain.User) Book(com.aidanwhiteley.books.domain.Book) IntegrationTest(com.aidanwhiteley.books.util.IntegrationTest) Test(org.junit.Test)

Example 2 with User

use of com.aidanwhiteley.books.domain.User in project books by aidanwhiteley.

the class JwtAuthenticationService method readAndValidateAuthenticationData.

public JwtAuthentication readAndValidateAuthenticationData(HttpServletRequest request, HttpServletResponse response) {
    JwtAuthentication auth = null;
    Cookie[] cookies = request.getCookies();
    if (cookies != null) {
        for (Cookie cookie : cookies) {
            LOGGER.debug("Found cookie named: {}", cookie.getName());
            switch(cookie.getName()) {
                case JWT_COOKIE_NAME:
                    String token = cookie.getValue();
                    if (token == null || token.trim().isEmpty()) {
                        LOGGER.warn("JWT cookie found but was empty - we will look to remove this later");
                    } else {
                        try {
                            User user = jwtUtils.getUserFromToken(token);
                            // TODO - add support for interval based checking of whether the user is still in the database.
                            // Will require adding a "lastChecked" field to the JWT and calling the database appropriately.
                            auth = new JwtAuthentication(user);
                            // If we got to here with no exceptions thrown
                            // then we can assume we have a valid token
                            auth.setAuthenticated(true);
                            LOGGER.debug("JWT found and validated - setting authentication true");
                        } catch (ExpiredJwtException eje) {
                            expireJwtCookie(response);
                            LOGGER.info("JWT expired so cookie deleted");
                        } catch (RuntimeException re) {
                            expireJwtCookie(response);
                            LOGGER.error("Error validating jwt token: {}. So cookie deleted", re.getMessage());
                        }
                    }
                    break;
                case JSESSIONID_COOKIE_NAME:
                    // With the use of Spring Security Oauth2 and the custom
                    // HttpCookieOAuth2AuthorizationRequestRepository there
                    // should be no JSESSIONIDs being writtem
                    LOGGER.warn("Unexpectedly found a JSESSIONID based cookie - killing it!");
                    expireJsessionIdCookie(response);
                    break;
                default:
                    LOGGER.debug("Found cookie named {}", cookie.getName());
                    break;
            }
        }
    }
    return auth;
}
Also used : Cookie(javax.servlet.http.Cookie) User(com.aidanwhiteley.books.domain.User) ExpiredJwtException(io.jsonwebtoken.ExpiredJwtException)

Example 3 with User

use of com.aidanwhiteley.books.domain.User in project books by aidanwhiteley.

the class LimitDataVisibilityAspect method limitBookDataImpl.

@Around("limitBookData()")
public Object limitBookDataImpl(ProceedingJoinPoint joinPoint) throws Throwable {
    Object retVal = joinPoint.proceed();
    Principal principal = getPrincipal(joinPoint);
    // Note - we only look at data from the JWT to build the User here - we
    // are
    // only interested in the users roles and they are in the JWT.
    Optional<User> user = authUtils.extractUserFromPrincipal(principal, true);
    if (retVal instanceof Book) {
        if (LOGGER.isInfoEnabled()) {
            LOGGER.info("About to call setPermissionsAndContentForUser for {}", joinPoint.getSignature());
        }
        ((Book) retVal).setPermissionsAndContentForUser(user.orElse(null));
    } else {
        LOGGER.error("Unexpected return type found by aspect");
    }
    return retVal;
}
Also used : User(com.aidanwhiteley.books.domain.User) Book(com.aidanwhiteley.books.domain.Book) Principal(java.security.Principal) Around(org.aspectj.lang.annotation.Around)

Example 4 with User

use of com.aidanwhiteley.books.domain.User in project books by aidanwhiteley.

the class JwtAuthenticationFilter method createDummyUser.

private User createDummyUser() {
    User dummyUser = new User();
    // The data below must match the corresponding entry in users.data
    dummyUser.setFirstName("Auto");
    dummyUser.setLastName("Logon");
    dummyUser.setFullName("Auto Logon");
    dummyUser.addRole(User.Role.ROLE_ADMIN);
    dummyUser.setLastLogon(LocalDateTime.MIN);
    dummyUser.setEmail("example@example.com");
    dummyUser.setAuthProvider(User.AuthenticationProvider.LOCAL);
    dummyUser.setAuthenticationServiceId("Dummy12345678");
    return dummyUser;
}
Also used : User(com.aidanwhiteley.books.domain.User)

Example 5 with User

use of com.aidanwhiteley.books.domain.User in project books by aidanwhiteley.

the class BookControllerTest method testSensitiveDataIsReturnedToAdminUser.

@Test
void testSensitiveDataIsReturnedToAdminUser() {
    Book testBook = BookRepositoryTest.createTestBook();
    User user = BookControllerTestUtils.getTestUser();
    String token = jwtUtils.createTokenForUser(user);
    String xsrfToken = BookControllerTestUtils.getXsrfToken(testRestTemplate);
    HttpEntity<Book> request = BookControllerTestUtils.getBookHttpEntity(testBook, token, xsrfToken);
    ResponseEntity<Book> response = testRestTemplate.exchange("/secure/api/books", HttpMethod.POST, request, Book.class);
    String location = response.getHeaders().getLocation().toString();
    Book book = testRestTemplate.exchange(location, HttpMethod.GET, request, Book.class).getBody();
    // Title should be available to everyone
    assertEquals(J_UNIT_TESTING_FOR_BEGINNERS, book.getTitle());
    // Email should only be available to admins
    assertEquals(BookControllerTestUtils.DUMMY_EMAIL, book.getCreatedBy().getEmail());
    // Now update the book and check that details about who updated the book are returned to an authorised user
    String updatedTitle = "Another updated title";
    BookSecureControllerTest.updateBook(user, book, updatedTitle, this.jwtUtils, this.testRestTemplate);
    Book updatedBook = testRestTemplate.exchange(location, HttpMethod.GET, request, Book.class).getBody();
    assertEquals(updatedBook.getTitle(), updatedTitle);
    // Check that details about who did the update ARE returned
    assertEquals(updatedBook.getLastModifiedBy().getFullName(), user.getFullName());
}
Also used : User(com.aidanwhiteley.books.domain.User) Book(com.aidanwhiteley.books.domain.Book) BookRepositoryTest(com.aidanwhiteley.books.repository.BookRepositoryTest) Test(org.junit.jupiter.api.Test) IntegrationTest(com.aidanwhiteley.books.util.IntegrationTest)

Aggregations

User (com.aidanwhiteley.books.domain.User)61 Test (org.junit.jupiter.api.Test)35 Book (com.aidanwhiteley.books.domain.Book)25 IntegrationTest (com.aidanwhiteley.books.util.IntegrationTest)24 BookRepositoryTest (com.aidanwhiteley.books.repository.BookRepositoryTest)13 URI (java.net.URI)5 DefaultOAuth2User (org.springframework.security.oauth2.core.user.DefaultOAuth2User)4 OAuth2User (org.springframework.security.oauth2.core.user.OAuth2User)4 Principal (java.security.Principal)3 HttpHeaders (org.springframework.http.HttpHeaders)3 Comment (com.aidanwhiteley.books.domain.Comment)2 Around (org.aspectj.lang.annotation.Around)2 LoggerContext (ch.qos.logback.classic.LoggerContext)1 ClientRoles (com.aidanwhiteley.books.controller.dtos.ClientRoles)1 NotAuthorisedException (com.aidanwhiteley.books.controller.exceptions.NotAuthorisedException)1 Owner (com.aidanwhiteley.books.domain.Owner)1 Item (com.aidanwhiteley.books.domain.googlebooks.Item)1 Claims (io.jsonwebtoken.Claims)1 ExpiredJwtException (io.jsonwebtoken.ExpiredJwtException)1 LocalDateTime (java.time.LocalDateTime)1