├── .gitignore ├── README.md ├── src ├── main │ ├── resources │ │ └── application.properties │ └── java │ │ └── guru │ │ └── nidi │ │ └── jwtspring │ │ ├── Application.java │ │ ├── repository │ │ ├── UserRepository.java │ │ ├── UserEventHandler.java │ │ └── CompanyRepository.java │ │ ├── domain │ │ ├── Company.java │ │ └── User.java │ │ ├── controller │ │ ├── AuthenticationResponse.java │ │ ├── AuthenticationRequest.java │ │ └── AuthenticationController.java │ │ └── config │ │ ├── UserDetailsServiceImpl.java │ │ ├── JwtTokenCodec.java │ │ ├── JwtToken.java │ │ ├── UserDetailsImpl.java │ │ ├── JwtAuthenticationTokenFilter.java │ │ └── SecurityConfig.java └── test │ └── java │ └── guru │ └── nidi │ └── jwtspring │ ├── AuthenticationTest.java │ ├── AbstractMvcTest.java │ └── AuthorizationTest.java ├── pom.xml └── LICENSE /.gitignore: -------------------------------------------------------------------------------- 1 | .idea/ 2 | target/ 3 | *.iml 4 | -------------------------------------------------------------------------------- /README.md: -------------------------------------------------------------------------------- 1 | # jwt-with-spring 2 | Example project to show how to use JWT and Spring 3 | -------------------------------------------------------------------------------- /src/main/resources/application.properties: -------------------------------------------------------------------------------- 1 | spring.data.mongodb.uri=mongodb://localhost:27017/mongo 2 | spring.data.rest.base-path=/api 3 | 4 | jwt.secret: mySecret 5 | jwt.expiration: 604800 6 | -------------------------------------------------------------------------------- /src/main/java/guru/nidi/jwtspring/Application.java: -------------------------------------------------------------------------------- 1 | package guru.nidi.jwtspring; 2 | 3 | import org.springframework.boot.SpringApplication; 4 | import org.springframework.boot.autoconfigure.SpringBootApplication; 5 | 6 | /** 7 | * 8 | */ 9 | @SpringBootApplication 10 | public class Application { 11 | public static void main(String[] args) { 12 | SpringApplication.run(Application.class, args); 13 | } 14 | } -------------------------------------------------------------------------------- /src/main/java/guru/nidi/jwtspring/repository/UserRepository.java: -------------------------------------------------------------------------------- 1 | package guru.nidi.jwtspring.repository; 2 | 3 | import guru.nidi.jwtspring.domain.User; 4 | import org.springframework.data.mongodb.repository.MongoRepository; 5 | import org.springframework.data.repository.query.Param; 6 | import org.springframework.data.rest.core.annotation.RepositoryRestResource; 7 | 8 | @RepositoryRestResource 9 | public interface UserRepository extends MongoRepository { 10 | User findByUsername(@Param("username") String username); 11 | } -------------------------------------------------------------------------------- /src/main/java/guru/nidi/jwtspring/domain/Company.java: -------------------------------------------------------------------------------- 1 | package guru.nidi.jwtspring.domain; 2 | 3 | 4 | import org.springframework.data.annotation.Id; 5 | 6 | public class Company { 7 | @Id 8 | private String id; 9 | private String name; 10 | 11 | public String getId() { 12 | return id; 13 | } 14 | 15 | public void setId(String id) { 16 | this.id = id; 17 | } 18 | 19 | public String getName() { 20 | return name; 21 | } 22 | 23 | public void setName(String name) { 24 | this.name = name; 25 | } 26 | } 27 | -------------------------------------------------------------------------------- /src/main/java/guru/nidi/jwtspring/controller/AuthenticationResponse.java: -------------------------------------------------------------------------------- 1 | package guru.nidi.jwtspring.controller; 2 | 3 | import guru.nidi.jwtspring.domain.User; 4 | 5 | public class AuthenticationResponse { 6 | private final String token; 7 | private final User user; 8 | 9 | public AuthenticationResponse(String token, User user) { 10 | this.token = token; 11 | this.user = user; 12 | } 13 | 14 | public String getToken() { 15 | return this.token; 16 | } 17 | 18 | public User getUser() { 19 | return this.user; 20 | } 21 | } -------------------------------------------------------------------------------- /src/main/java/guru/nidi/jwtspring/controller/AuthenticationRequest.java: -------------------------------------------------------------------------------- 1 | package guru.nidi.jwtspring.controller; 2 | 3 | public class AuthenticationRequest { 4 | private String username; 5 | private String password; 6 | 7 | public String getUsername() { 8 | return this.username; 9 | } 10 | 11 | public void setUsername(String username) { 12 | this.username = username; 13 | } 14 | 15 | public String getPassword() { 16 | return this.password; 17 | } 18 | 19 | public void setPassword(String password) { 20 | this.password = password; 21 | } 22 | } -------------------------------------------------------------------------------- /src/main/java/guru/nidi/jwtspring/repository/UserEventHandler.java: -------------------------------------------------------------------------------- 1 | package guru.nidi.jwtspring.repository; 2 | 3 | import guru.nidi.jwtspring.domain.User; 4 | import org.springframework.beans.factory.annotation.Autowired; 5 | import org.springframework.data.rest.core.annotation.HandleBeforeCreate; 6 | import org.springframework.data.rest.core.annotation.HandleBeforeSave; 7 | import org.springframework.data.rest.core.annotation.RepositoryEventHandler; 8 | import org.springframework.security.crypto.password.PasswordEncoder; 9 | import org.springframework.stereotype.Component; 10 | 11 | import java.util.Arrays; 12 | 13 | @Component 14 | @RepositoryEventHandler(User.class) 15 | public class UserEventHandler { 16 | @Autowired 17 | private PasswordEncoder passwordEncoder; 18 | 19 | @HandleBeforeCreate 20 | @HandleBeforeSave 21 | public void beforeSave(User user) { 22 | user.setPassword(passwordEncoder.encode(user.getPassword())); 23 | user.setRoles(Arrays.asList("ROLE_USER")); 24 | } 25 | 26 | } -------------------------------------------------------------------------------- /src/main/java/guru/nidi/jwtspring/config/UserDetailsServiceImpl.java: -------------------------------------------------------------------------------- 1 | package guru.nidi.jwtspring.config; 2 | 3 | import guru.nidi.jwtspring.domain.User; 4 | import guru.nidi.jwtspring.repository.UserRepository; 5 | import org.springframework.beans.factory.annotation.Autowired; 6 | import org.springframework.security.core.userdetails.UserDetails; 7 | import org.springframework.security.core.userdetails.UserDetailsService; 8 | import org.springframework.security.core.userdetails.UsernameNotFoundException; 9 | import org.springframework.stereotype.Service; 10 | 11 | @Service 12 | public class UserDetailsServiceImpl implements UserDetailsService { 13 | 14 | @Autowired 15 | private UserRepository userRepository; 16 | 17 | @Override 18 | public UserDetails loadUserByUsername(String username) throws UsernameNotFoundException { 19 | final User user = userRepository.findByUsername(username); 20 | if (user == null) { 21 | throw new UsernameNotFoundException(username); 22 | } 23 | return new UserDetailsImpl(user); 24 | } 25 | } -------------------------------------------------------------------------------- /src/main/java/guru/nidi/jwtspring/repository/CompanyRepository.java: -------------------------------------------------------------------------------- 1 | package guru.nidi.jwtspring.repository; 2 | 3 | import guru.nidi.jwtspring.domain.Company; 4 | import org.springframework.data.domain.Page; 5 | import org.springframework.data.domain.Pageable; 6 | import org.springframework.data.domain.Sort; 7 | import org.springframework.data.mongodb.repository.MongoRepository; 8 | import org.springframework.data.repository.query.Param; 9 | import org.springframework.data.rest.core.annotation.RepositoryRestResource; 10 | import org.springframework.security.access.prepost.PreAuthorize; 11 | 12 | import java.util.List; 13 | 14 | @RepositoryRestResource 15 | public interface CompanyRepository extends MongoRepository { 16 | @Override 17 | @PreAuthorize("hasRole('ROLE_ADMIN')") 18 | List findAll(); 19 | 20 | @Override 21 | @PreAuthorize("hasRole('ROLE_ADMIN')") 22 | List findAll(Sort sort); 23 | 24 | @Override 25 | @PreAuthorize("hasRole('ROLE_ADMIN')") 26 | Page findAll(Pageable pageable); 27 | 28 | @Override 29 | @PreAuthorize("hasRole('ROLE_ADMIN') or principal.companyId == #id") 30 | Company findOne(@Param("id") String id); 31 | } -------------------------------------------------------------------------------- /src/main/java/guru/nidi/jwtspring/config/JwtTokenCodec.java: -------------------------------------------------------------------------------- 1 | package guru.nidi.jwtspring.config; 2 | 3 | import io.jsonwebtoken.Jwts; 4 | import io.jsonwebtoken.SignatureAlgorithm; 5 | import org.springframework.beans.factory.annotation.Value; 6 | import org.springframework.stereotype.Component; 7 | 8 | import java.util.Date; 9 | 10 | @Component 11 | public class JwtTokenCodec { 12 | @Value("${jwt.secret}") 13 | private String secret; 14 | 15 | @Value("${jwt.expiration}") 16 | private Long expiration; 17 | 18 | public JwtToken decodeToken(String token) { 19 | return new JwtToken(Jwts.parser() 20 | .setSigningKey(secret) 21 | .parseClaimsJws(token) 22 | .getBody()); 23 | } 24 | 25 | private Date generateExpirationDate(Date issuedAt) { 26 | return new Date(issuedAt.getTime() + expiration * 1000); 27 | } 28 | 29 | public String encodeToken(JwtToken token) { 30 | return Jwts.builder() 31 | .setClaims(token.getClaims()) 32 | .setIssuedAt(new Date()) 33 | .setExpiration(generateExpirationDate(new Date())) 34 | .signWith(SignatureAlgorithm.HS512, secret) 35 | .compact(); 36 | } 37 | } -------------------------------------------------------------------------------- /src/main/java/guru/nidi/jwtspring/config/JwtToken.java: -------------------------------------------------------------------------------- 1 | package guru.nidi.jwtspring.config; 2 | 3 | import guru.nidi.jwtspring.domain.User; 4 | import io.jsonwebtoken.Claims; 5 | import io.jsonwebtoken.Jwts; 6 | 7 | import java.util.Arrays; 8 | import java.util.Date; 9 | import java.util.List; 10 | import java.util.stream.Collectors; 11 | 12 | public class JwtToken { 13 | private static class Key { 14 | public static final String COMPANY_ID = "cmp"; 15 | public static final String ROLES = "rol"; 16 | } 17 | 18 | private final Claims claims; 19 | 20 | public JwtToken(Claims claims) { 21 | this.claims = claims; 22 | } 23 | 24 | public static JwtToken ofUser(User user) { 25 | final Claims claims = Jwts.claims(); 26 | claims.put(JwtToken.Key.COMPANY_ID, user.getCompany() == null ? null : user.getCompany().getId()); 27 | claims.put(JwtToken.Key.ROLES, user.getRoles().stream().collect(Collectors.joining(","))); 28 | return new JwtToken(claims); 29 | } 30 | 31 | public Claims getClaims() { 32 | return claims; 33 | } 34 | 35 | public String getCompanyId() { 36 | return claims.get(Key.COMPANY_ID, String.class); 37 | } 38 | 39 | public List getRoles() { 40 | return Arrays.asList(claims.get(Key.ROLES, String.class).split(",")); 41 | } 42 | 43 | public String getUsername() { 44 | return claims.getSubject(); 45 | } 46 | 47 | public boolean isExpired() { 48 | return claims.getExpiration().before(new Date()); 49 | } 50 | } -------------------------------------------------------------------------------- /src/main/java/guru/nidi/jwtspring/config/UserDetailsImpl.java: -------------------------------------------------------------------------------- 1 | package guru.nidi.jwtspring.config; 2 | 3 | import guru.nidi.jwtspring.domain.User; 4 | import org.springframework.security.core.GrantedAuthority; 5 | import org.springframework.security.core.authority.SimpleGrantedAuthority; 6 | import org.springframework.security.core.userdetails.UserDetails; 7 | 8 | import java.util.Collection; 9 | import java.util.stream.Collectors; 10 | 11 | /** 12 | * 13 | */ 14 | public class UserDetailsImpl implements UserDetails { 15 | private final User user; 16 | 17 | public UserDetailsImpl(User user) { 18 | this.user = user; 19 | } 20 | 21 | public User getUser() { 22 | return user; 23 | } 24 | 25 | @Override 26 | public Collection getAuthorities() { 27 | return user.getRoles().stream().map(SimpleGrantedAuthority::new).collect(Collectors.toList()); 28 | } 29 | 30 | @Override 31 | public String getPassword() { 32 | return user.getPassword(); 33 | } 34 | 35 | @Override 36 | public String getUsername() { 37 | return user.getUsername(); 38 | } 39 | 40 | @Override 41 | public boolean isAccountNonExpired() { 42 | return true; 43 | } 44 | 45 | @Override 46 | public boolean isAccountNonLocked() { 47 | return true; 48 | } 49 | 50 | @Override 51 | public boolean isCredentialsNonExpired() { 52 | return true; 53 | } 54 | 55 | @Override 56 | public boolean isEnabled() { 57 | return true; 58 | } 59 | } 60 | -------------------------------------------------------------------------------- /src/main/java/guru/nidi/jwtspring/domain/User.java: -------------------------------------------------------------------------------- 1 | package guru.nidi.jwtspring.domain; 2 | 3 | import com.fasterxml.jackson.annotation.JsonProperty; 4 | import org.springframework.data.annotation.Id; 5 | import org.springframework.data.mongodb.core.mapping.DBRef; 6 | 7 | import java.util.List; 8 | 9 | public class User { 10 | @Id 11 | private String id; 12 | private String username; 13 | @JsonProperty(access = JsonProperty.Access.WRITE_ONLY) 14 | private String password; 15 | private String firstname; 16 | private String lastname; 17 | private List roles; 18 | 19 | @DBRef 20 | private Company company; 21 | 22 | public String getId() { 23 | return id; 24 | } 25 | 26 | public void setId(String id) { 27 | this.id = id; 28 | } 29 | 30 | public String getUsername() { 31 | return username; 32 | } 33 | 34 | public void setUsername(String username) { 35 | this.username = username; 36 | } 37 | 38 | public String getPassword() { 39 | return password; 40 | } 41 | 42 | public void setPassword(String password) { 43 | this.password = password; 44 | } 45 | 46 | public String getFirstname() { 47 | return firstname; 48 | } 49 | 50 | public void setFirstname(String firstname) { 51 | this.firstname = firstname; 52 | } 53 | 54 | public String getLastname() { 55 | return lastname; 56 | } 57 | 58 | public void setLastname(String lastname) { 59 | this.lastname = lastname; 60 | } 61 | 62 | public List getRoles() { 63 | return roles; 64 | } 65 | 66 | public void setRoles(List roles) { 67 | this.roles = roles; 68 | } 69 | 70 | public Company getCompany() { 71 | return company; 72 | } 73 | 74 | public void setCompany(Company company) { 75 | this.company = company; 76 | } 77 | } -------------------------------------------------------------------------------- /src/main/java/guru/nidi/jwtspring/controller/AuthenticationController.java: -------------------------------------------------------------------------------- 1 | package guru.nidi.jwtspring.controller; 2 | 3 | import guru.nidi.jwtspring.config.JwtToken; 4 | import guru.nidi.jwtspring.config.JwtTokenCodec; 5 | import guru.nidi.jwtspring.config.UserDetailsImpl; 6 | import guru.nidi.jwtspring.domain.User; 7 | import org.springframework.beans.factory.annotation.Autowired; 8 | import org.springframework.http.ResponseEntity; 9 | import org.springframework.security.authentication.AuthenticationManager; 10 | import org.springframework.security.authentication.UsernamePasswordAuthenticationToken; 11 | import org.springframework.security.core.Authentication; 12 | import org.springframework.security.core.AuthenticationException; 13 | import org.springframework.security.core.context.SecurityContextHolder; 14 | import org.springframework.web.bind.annotation.RequestBody; 15 | import org.springframework.web.bind.annotation.RequestMapping; 16 | import org.springframework.web.bind.annotation.RequestMethod; 17 | import org.springframework.web.bind.annotation.RestController; 18 | 19 | @RestController 20 | @RequestMapping("/api/public") 21 | public class AuthenticationController { 22 | @Autowired 23 | private AuthenticationManager authenticationManager; 24 | 25 | @Autowired 26 | private JwtTokenCodec jwtCodec; 27 | 28 | @RequestMapping(value = "/login", method = RequestMethod.POST) 29 | public ResponseEntity login(@RequestBody AuthenticationRequest authenticationRequest) throws AuthenticationException { 30 | final Authentication authentication = authenticationManager.authenticate( 31 | new UsernamePasswordAuthenticationToken( 32 | authenticationRequest.getUsername(), 33 | authenticationRequest.getPassword() 34 | )); 35 | SecurityContextHolder.getContext().setAuthentication(authentication); 36 | final UserDetailsImpl userDetails = (UserDetailsImpl) authentication.getPrincipal(); 37 | final User user = userDetails.getUser(); 38 | final String token = jwtCodec.encodeToken(JwtToken.ofUser(user)); 39 | return ResponseEntity.ok(new AuthenticationResponse(token, user)); 40 | } 41 | } -------------------------------------------------------------------------------- /src/test/java/guru/nidi/jwtspring/AuthenticationTest.java: -------------------------------------------------------------------------------- 1 | package guru.nidi.jwtspring; 2 | 3 | import org.junit.Test; 4 | import org.springframework.boot.test.context.SpringBootTest; 5 | import org.springframework.test.web.servlet.ResultActions; 6 | 7 | import static org.hamcrest.CoreMatchers.equalTo; 8 | import static org.springframework.test.web.servlet.request.MockMvcRequestBuilders.get; 9 | import static org.springframework.test.web.servlet.request.MockMvcRequestBuilders.post; 10 | import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.jsonPath; 11 | import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.status; 12 | 13 | public class AuthenticationTest extends AbstractMvcTest { 14 | @Override 15 | protected void doInit() throws Exception { 16 | registerUser("name", "pass").andExpect(status().isCreated()); 17 | } 18 | 19 | @Test 20 | public void userRepositoryWithoutTokenIsForbidden() throws Exception { 21 | mockMvc.perform(get("/api/users")).andExpect(status().isForbidden()); 22 | } 23 | 24 | @Test 25 | public void userRepositoryWithTokenIsAllowed() throws Exception { 26 | final String token = extractToken(login("name", "pass").andReturn()); 27 | mockMvc.perform(get("/api/users").header("Authorization", "Bearer " + token)) 28 | .andExpect(status().isOk()); 29 | } 30 | 31 | @Test 32 | public void loginOk() throws Exception { 33 | login("name", "pass") 34 | .andExpect(status().isOk()) 35 | .andExpect(jsonPath("$.token").exists()) 36 | .andExpect(jsonPath("$.user.username", equalTo("name"))) 37 | .andExpect(jsonPath("$.user.password").doesNotExist()) 38 | .andReturn(); 39 | } 40 | 41 | @Test 42 | public void loginNok() throws Exception { 43 | login("name", "wrong").andExpect(status().isForbidden()); 44 | } 45 | 46 | 47 | private ResultActions registerUser(String username, String password) throws Exception { 48 | return mockMvc.perform( 49 | post("/api/users") 50 | .content("{\"username\":\"" + username + "\",\"password\":\"" + password + "\"}")); 51 | } 52 | } 53 | -------------------------------------------------------------------------------- /src/main/java/guru/nidi/jwtspring/config/JwtAuthenticationTokenFilter.java: -------------------------------------------------------------------------------- 1 | package guru.nidi.jwtspring.config; 2 | 3 | import org.springframework.beans.factory.annotation.Autowired; 4 | import org.springframework.beans.factory.annotation.Value; 5 | import org.springframework.security.core.authority.SimpleGrantedAuthority; 6 | import org.springframework.security.core.context.SecurityContext; 7 | import org.springframework.security.core.context.SecurityContextHolder; 8 | import org.springframework.security.web.authentication.WebAuthenticationDetailsSource; 9 | import org.springframework.security.web.authentication.preauth.PreAuthenticatedAuthenticationToken; 10 | import org.springframework.web.filter.GenericFilterBean; 11 | 12 | import javax.servlet.FilterChain; 13 | import javax.servlet.ServletException; 14 | import javax.servlet.ServletRequest; 15 | import javax.servlet.ServletResponse; 16 | import javax.servlet.http.HttpServletRequest; 17 | import java.io.IOException; 18 | import java.util.stream.Collectors; 19 | 20 | public class JwtAuthenticationTokenFilter extends GenericFilterBean { 21 | @Autowired 22 | private JwtTokenCodec jwtTokenCodec; 23 | 24 | @Override 25 | public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain) throws IOException, ServletException { 26 | final HttpServletRequest httpRequest = (HttpServletRequest) request; 27 | final String header = httpRequest.getHeader("Authorization"); 28 | final SecurityContext context = SecurityContextHolder.getContext(); 29 | if (header != null && context.getAuthentication() == null) { 30 | final String tokenStr = header.substring("Bearer ".length()); 31 | final JwtToken token = jwtTokenCodec.decodeToken(tokenStr); 32 | if (!token.isExpired()) { 33 | final PreAuthenticatedAuthenticationToken authentication = new PreAuthenticatedAuthenticationToken(token, "n/a", token.getRoles().stream().map(SimpleGrantedAuthority::new).collect(Collectors.toList())); 34 | authentication.setDetails(new WebAuthenticationDetailsSource().buildDetails(httpRequest)); 35 | context.setAuthentication(authentication); 36 | } 37 | } 38 | chain.doFilter(request, response); 39 | } 40 | } -------------------------------------------------------------------------------- /pom.xml: -------------------------------------------------------------------------------- 1 | 2 | 4 | 4.0.0 5 | 6 | 7 | org.springframework.boot 8 | spring-boot-starter-parent 9 | 1.4.1.RELEASE 10 | 11 | 12 | guru.nidi 13 | jwt-with-spring 14 | 0.0.1-SNAPSHOT 15 | 16 | 17 | 1.8 18 | 19 | 20 | 21 | 22 | org.springframework.boot 23 | spring-boot-starter-data-rest 24 | 25 | 26 | org.springframework.boot 27 | spring-boot-starter-data-mongodb 28 | 29 | 30 | org.springframework.boot 31 | spring-boot-starter-security 32 | 33 | 34 | io.jsonwebtoken 35 | jjwt 36 | 0.6.0 37 | 38 | 39 | 40 | org.springframework.boot 41 | spring-boot-starter-test 42 | test 43 | 44 | 45 | org.springframework.security 46 | spring-security-test 47 | test 48 | 49 | 50 | de.flapdoodle.embed 51 | de.flapdoodle.embed.mongo 52 | 1.50.5 53 | test 54 | 55 | 56 | 57 | 58 | 59 | 60 | org.springframework.boot 61 | spring-boot-maven-plugin 62 | 63 | 64 | 65 | 66 | 67 | -------------------------------------------------------------------------------- /src/test/java/guru/nidi/jwtspring/AbstractMvcTest.java: -------------------------------------------------------------------------------- 1 | package guru.nidi.jwtspring; 2 | 3 | import com.fasterxml.jackson.databind.ObjectMapper; 4 | import com.jayway.jsonpath.JsonPath; 5 | import guru.nidi.jwtspring.controller.AuthenticationRequest; 6 | import org.junit.Before; 7 | import org.junit.Ignore; 8 | import org.junit.runner.RunWith; 9 | import org.springframework.beans.factory.annotation.Autowired; 10 | import org.springframework.boot.test.context.SpringBootTest; 11 | import org.springframework.http.MediaType; 12 | import org.springframework.test.context.TestPropertySource; 13 | import org.springframework.test.context.junit4.SpringRunner; 14 | import org.springframework.test.web.servlet.MockMvc; 15 | import org.springframework.test.web.servlet.MvcResult; 16 | import org.springframework.test.web.servlet.ResultActions; 17 | import org.springframework.web.context.WebApplicationContext; 18 | 19 | import java.io.IOException; 20 | import java.io.UnsupportedEncodingException; 21 | import java.util.HashSet; 22 | import java.util.Set; 23 | 24 | import static org.springframework.security.test.web.servlet.setup.SecurityMockMvcConfigurers.springSecurity; 25 | import static org.springframework.test.web.servlet.request.MockMvcRequestBuilders.post; 26 | import static org.springframework.test.web.servlet.setup.MockMvcBuilders.webAppContextSetup; 27 | 28 | @SpringBootTest 29 | @RunWith(SpringRunner.class) 30 | @TestPropertySource(properties = {"spring.data.mongodb.port=27018"}) 31 | @Ignore 32 | public class AbstractMvcTest { 33 | protected MockMvc mockMvc; 34 | private ObjectMapper mapper = new ObjectMapper(); 35 | private static Set inited = new HashSet<>(); 36 | 37 | @Autowired 38 | private WebApplicationContext webApplicationContext; 39 | 40 | @Before 41 | public void setup() { 42 | mockMvc = webAppContextSetup(webApplicationContext).apply(springSecurity()).build(); 43 | } 44 | 45 | @Before 46 | public void init() throws Exception { 47 | if (!inited.contains(getClass())) { 48 | doInit(); 49 | inited.add(getClass()); 50 | } 51 | } 52 | 53 | protected void doInit() throws Exception { 54 | } 55 | 56 | protected String json(Object o) throws IOException { 57 | return mapper.writeValueAsString(o); 58 | } 59 | 60 | protected ResultActions login(String username, String password) throws Exception { 61 | final AuthenticationRequest auth = new AuthenticationRequest(); 62 | auth.setUsername(username); 63 | auth.setPassword(password); 64 | return mockMvc.perform( 65 | post("/api/public/login") 66 | .content(json(auth)) 67 | .contentType(MediaType.APPLICATION_JSON)); 68 | } 69 | 70 | protected String extractToken(MvcResult result) throws UnsupportedEncodingException { 71 | return JsonPath.read(result.getResponse().getContentAsString(), "$.token"); 72 | } 73 | 74 | } 75 | -------------------------------------------------------------------------------- /src/main/java/guru/nidi/jwtspring/config/SecurityConfig.java: -------------------------------------------------------------------------------- 1 | package guru.nidi.jwtspring.config; 2 | 3 | import org.springframework.beans.factory.annotation.Autowired; 4 | import org.springframework.context.annotation.Bean; 5 | import org.springframework.context.annotation.Configuration; 6 | import org.springframework.http.HttpMethod; 7 | import org.springframework.security.config.annotation.authentication.builders.AuthenticationManagerBuilder; 8 | import org.springframework.security.config.annotation.method.configuration.EnableGlobalMethodSecurity; 9 | import org.springframework.security.config.annotation.web.builders.HttpSecurity; 10 | import org.springframework.security.config.annotation.web.configuration.EnableWebSecurity; 11 | import org.springframework.security.config.annotation.web.configuration.WebSecurityConfigurerAdapter; 12 | import org.springframework.security.config.http.SessionCreationPolicy; 13 | import org.springframework.security.core.userdetails.UserDetailsService; 14 | import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder; 15 | import org.springframework.security.crypto.password.PasswordEncoder; 16 | import org.springframework.security.web.authentication.Http403ForbiddenEntryPoint; 17 | import org.springframework.security.web.authentication.UsernamePasswordAuthenticationFilter; 18 | 19 | import javax.servlet.Filter; 20 | 21 | @Configuration 22 | @EnableWebSecurity 23 | @EnableGlobalMethodSecurity(prePostEnabled = true) 24 | public class SecurityConfig extends WebSecurityConfigurerAdapter { 25 | @Autowired 26 | private UserDetailsService userDetailsService; 27 | 28 | @Autowired 29 | public void configureAuthentication(AuthenticationManagerBuilder authenticationManagerBuilder) throws Exception { 30 | authenticationManagerBuilder 31 | .userDetailsService(this.userDetailsService) 32 | .passwordEncoder(passwordEncoder()); 33 | } 34 | 35 | @Bean 36 | PasswordEncoder passwordEncoder() { 37 | return new BCryptPasswordEncoder(); 38 | } 39 | 40 | @Bean 41 | Filter authenticationFilter() { 42 | return new JwtAuthenticationTokenFilter(); 43 | } 44 | 45 | @Override 46 | protected void configure(HttpSecurity httpSecurity) throws Exception { 47 | httpSecurity 48 | .csrf().disable() 49 | .headers().cacheControl().and().and() 50 | .exceptionHandling().authenticationEntryPoint(new Http403ForbiddenEntryPoint()).and() 51 | .sessionManagement().sessionCreationPolicy(SessionCreationPolicy.STATELESS).and() 52 | .addFilterBefore(authenticationFilter(), UsernamePasswordAuthenticationFilter.class) 53 | .authorizeRequests() 54 | .antMatchers("/favicon.ico", "/**/*.html", "/**/*.css", "/**/*.js", "/**/*.gif").permitAll() 55 | .antMatchers("/api/public/**").permitAll() 56 | .antMatchers(HttpMethod.POST, "/api/users").permitAll() 57 | .anyRequest().authenticated(); 58 | } 59 | } -------------------------------------------------------------------------------- /src/test/java/guru/nidi/jwtspring/AuthorizationTest.java: -------------------------------------------------------------------------------- 1 | package guru.nidi.jwtspring; 2 | 3 | import com.jayway.jsonpath.JsonPath; 4 | import guru.nidi.jwtspring.domain.Company; 5 | import guru.nidi.jwtspring.domain.User; 6 | import guru.nidi.jwtspring.repository.CompanyRepository; 7 | import guru.nidi.jwtspring.repository.UserRepository; 8 | import org.junit.Test; 9 | import org.springframework.beans.factory.annotation.Autowired; 10 | import org.springframework.security.crypto.password.PasswordEncoder; 11 | import org.springframework.test.web.servlet.MvcResult; 12 | 13 | import java.util.Arrays; 14 | 15 | import static org.springframework.test.web.servlet.request.MockMvcRequestBuilders.get; 16 | import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.status; 17 | 18 | public class AuthorizationTest extends AbstractMvcTest { 19 | @Autowired 20 | private UserRepository userRepository; 21 | @Autowired 22 | private CompanyRepository companyRepository; 23 | @Autowired 24 | private PasswordEncoder passwordEncoder; 25 | 26 | private static String companyAid, companyBid; 27 | 28 | public void doInit() throws Exception { 29 | final Company companyA = new Company(); 30 | companyA.setName("a"); 31 | companyAid = companyRepository.save(companyA).getId(); 32 | 33 | final Company companyB = new Company(); 34 | companyB.setName("b"); 35 | companyBid = companyRepository.save(companyB).getId(); 36 | 37 | final User user = new User(); 38 | user.setUsername("user"); 39 | user.setPassword(passwordEncoder.encode("pass")); 40 | user.setRoles(Arrays.asList("ROLE_USER")); 41 | user.setCompany(companyA); 42 | userRepository.save(user); 43 | final User admin = new User(); 44 | admin.setUsername("admin"); 45 | admin.setPassword(passwordEncoder.encode("pass")); 46 | admin.setRoles(Arrays.asList("ROLE_ADMIN")); 47 | admin.setCompany(companyB); 48 | userRepository.save(admin); 49 | } 50 | 51 | @Test 52 | public void userCannotAccessListOfCompanies() throws Exception { 53 | final String token = extractToken(login("user", "pass").andReturn()); 54 | mockMvc.perform(get("/api/companies").header("Authorization", "Bearer " + token)) 55 | .andExpect(status().isForbidden()); 56 | } 57 | 58 | @Test 59 | public void adminCanAccessListOfCompanies() throws Exception { 60 | final String token = extractToken(login("admin", "pass").andReturn()); 61 | mockMvc.perform(get("/api/companies").header("Authorization", "Bearer " + token)) 62 | .andExpect(status().isOk()); 63 | } 64 | 65 | @Test 66 | public void userCanAccessOwnCompany() throws Exception { 67 | final String token = extractToken(login("user", "pass").andReturn()); 68 | mockMvc.perform(get("/api/companies/" + companyAid).header("Authorization", "Bearer " + token)) 69 | .andExpect(status().isOk()); 70 | } 71 | 72 | @Test 73 | public void userCannotAccessForeignCompany() throws Exception { 74 | final String token = extractToken(login("user", "pass").andReturn()); 75 | mockMvc.perform(get("/api/companies/" + companyBid).header("Authorization", "Bearer " + token)) 76 | .andExpect(status().isForbidden()); 77 | } 78 | 79 | @Test 80 | public void userCannotAccessForeignCompanyViaUser() throws Exception { 81 | final String token = extractToken(login("user", "pass").andReturn()); 82 | final MvcResult authorization = mockMvc.perform(get("/api/users/search/findByUsername?username=admin").header("Authorization", "Bearer " + token)).andReturn(); 83 | final String c = JsonPath.read(authorization.getResponse().getContentAsString(), "$._links.company.href"); 84 | 85 | mockMvc.perform(get(c).header("Authorization", "Bearer " + token)) 86 | .andExpect(status().isForbidden()); 87 | } 88 | 89 | @Test 90 | public void adminCanAccessOwnCompany() throws Exception { 91 | final String token = extractToken(login("admin", "pass").andReturn()); 92 | mockMvc.perform(get("/api/companies/" + companyAid).header("Authorization", "Bearer " + token)) 93 | .andExpect(status().isOk()); 94 | } 95 | 96 | @Test 97 | public void adminCanAccessForeignCompany() throws Exception { 98 | final String token = extractToken(login("admin", "pass").andReturn()); 99 | mockMvc.perform(get("/api/companies/" + companyBid).header("Authorization", "Bearer " + token)) 100 | .andExpect(status().isOk()); 101 | } 102 | 103 | } 104 | -------------------------------------------------------------------------------- /LICENSE: -------------------------------------------------------------------------------- 1 | Apache License 2 | Version 2.0, January 2004 3 | http://www.apache.org/licenses/ 4 | 5 | TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION 6 | 7 | 1. Definitions. 8 | 9 | "License" shall mean the terms and conditions for use, reproduction, 10 | and distribution as defined by Sections 1 through 9 of this document. 11 | 12 | "Licensor" shall mean the copyright owner or entity authorized by 13 | the copyright owner that is granting the License. 14 | 15 | "Legal Entity" shall mean the union of the acting entity and all 16 | other entities that control, are controlled by, or are under common 17 | control with that entity. For the purposes of this definition, 18 | "control" means (i) the power, direct or indirect, to cause the 19 | direction or management of such entity, whether by contract or 20 | otherwise, or (ii) ownership of fifty percent (50%) or more of the 21 | outstanding shares, or (iii) beneficial ownership of such entity. 22 | 23 | "You" (or "Your") shall mean an individual or Legal Entity 24 | exercising permissions granted by this License. 25 | 26 | "Source" form shall mean the preferred form for making modifications, 27 | including but not limited to software source code, documentation 28 | source, and configuration files. 29 | 30 | "Object" form shall mean any form resulting from mechanical 31 | transformation or translation of a Source form, including but 32 | not limited to compiled object code, generated documentation, 33 | and conversions to other media types. 34 | 35 | "Work" shall mean the work of authorship, whether in Source or 36 | Object form, made available under the License, as indicated by a 37 | copyright notice that is included in or attached to the work 38 | (an example is provided in the Appendix below). 39 | 40 | "Derivative Works" shall mean any work, whether in Source or Object 41 | form, that is based on (or derived from) the Work and for which the 42 | editorial revisions, annotations, elaborations, or other modifications 43 | represent, as a whole, an original work of authorship. For the purposes 44 | of this License, Derivative Works shall not include works that remain 45 | separable from, or merely link (or bind by name) to the interfaces of, 46 | the Work and Derivative Works thereof. 47 | 48 | "Contribution" shall mean any work of authorship, including 49 | the original version of the Work and any modifications or additions 50 | to that Work or Derivative Works thereof, that is intentionally 51 | submitted to Licensor for inclusion in the Work by the copyright owner 52 | or by an individual or Legal Entity authorized to submit on behalf of 53 | the copyright owner. For the purposes of this definition, "submitted" 54 | means any form of electronic, verbal, or written communication sent 55 | to the Licensor or its representatives, including but not limited to 56 | communication on electronic mailing lists, source code control systems, 57 | and issue tracking systems that are managed by, or on behalf of, the 58 | Licensor for the purpose of discussing and improving the Work, but 59 | excluding communication that is conspicuously marked or otherwise 60 | designated in writing by the copyright owner as "Not a Contribution." 61 | 62 | "Contributor" shall mean Licensor and any individual or Legal Entity 63 | on behalf of whom a Contribution has been received by Licensor and 64 | subsequently incorporated within the Work. 65 | 66 | 2. Grant of Copyright License. Subject to the terms and conditions of 67 | this License, each Contributor hereby grants to You a perpetual, 68 | worldwide, non-exclusive, no-charge, royalty-free, irrevocable 69 | copyright license to reproduce, prepare Derivative Works of, 70 | publicly display, publicly perform, sublicense, and distribute the 71 | Work and such Derivative Works in Source or Object form. 72 | 73 | 3. Grant of Patent License. Subject to the terms and conditions of 74 | this License, each Contributor hereby grants to You a perpetual, 75 | worldwide, non-exclusive, no-charge, royalty-free, irrevocable 76 | (except as stated in this section) patent license to make, have made, 77 | use, offer to sell, sell, import, and otherwise transfer the Work, 78 | where such license applies only to those patent claims licensable 79 | by such Contributor that are necessarily infringed by their 80 | Contribution(s) alone or by combination of their Contribution(s) 81 | with the Work to which such Contribution(s) was submitted. If You 82 | institute patent litigation against any entity (including a 83 | cross-claim or counterclaim in a lawsuit) alleging that the Work 84 | or a Contribution incorporated within the Work constitutes direct 85 | or contributory patent infringement, then any patent licenses 86 | granted to You under this License for that Work shall terminate 87 | as of the date such litigation is filed. 88 | 89 | 4. Redistribution. You may reproduce and distribute copies of the 90 | Work or Derivative Works thereof in any medium, with or without 91 | modifications, and in Source or Object form, provided that You 92 | meet the following conditions: 93 | 94 | (a) You must give any other recipients of the Work or 95 | Derivative Works a copy of this License; and 96 | 97 | (b) You must cause any modified files to carry prominent notices 98 | stating that You changed the files; and 99 | 100 | (c) You must retain, in the Source form of any Derivative Works 101 | that You distribute, all copyright, patent, trademark, and 102 | attribution notices from the Source form of the Work, 103 | excluding those notices that do not pertain to any part of 104 | the Derivative Works; and 105 | 106 | (d) If the Work includes a "NOTICE" text file as part of its 107 | distribution, then any Derivative Works that You distribute must 108 | include a readable copy of the attribution notices contained 109 | within such NOTICE file, excluding those notices that do not 110 | pertain to any part of the Derivative Works, in at least one 111 | of the following places: within a NOTICE text file distributed 112 | as part of the Derivative Works; within the Source form or 113 | documentation, if provided along with the Derivative Works; or, 114 | within a display generated by the Derivative Works, if and 115 | wherever such third-party notices normally appear. The contents 116 | of the NOTICE file are for informational purposes only and 117 | do not modify the License. You may add Your own attribution 118 | notices within Derivative Works that You distribute, alongside 119 | or as an addendum to the NOTICE text from the Work, provided 120 | that such additional attribution notices cannot be construed 121 | as modifying the License. 122 | 123 | You may add Your own copyright statement to Your modifications and 124 | may provide additional or different license terms and conditions 125 | for use, reproduction, or distribution of Your modifications, or 126 | for any such Derivative Works as a whole, provided Your use, 127 | reproduction, and distribution of the Work otherwise complies with 128 | the conditions stated in this License. 129 | 130 | 5. Submission of Contributions. Unless You explicitly state otherwise, 131 | any Contribution intentionally submitted for inclusion in the Work 132 | by You to the Licensor shall be under the terms and conditions of 133 | this License, without any additional terms or conditions. 134 | Notwithstanding the above, nothing herein shall supersede or modify 135 | the terms of any separate license agreement you may have executed 136 | with Licensor regarding such Contributions. 137 | 138 | 6. Trademarks. This License does not grant permission to use the trade 139 | names, trademarks, service marks, or product names of the Licensor, 140 | except as required for reasonable and customary use in describing the 141 | origin of the Work and reproducing the content of the NOTICE file. 142 | 143 | 7. Disclaimer of Warranty. Unless required by applicable law or 144 | agreed to in writing, Licensor provides the Work (and each 145 | Contributor provides its Contributions) on an "AS IS" BASIS, 146 | WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or 147 | implied, including, without limitation, any warranties or conditions 148 | of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A 149 | PARTICULAR PURPOSE. You are solely responsible for determining the 150 | appropriateness of using or redistributing the Work and assume any 151 | risks associated with Your exercise of permissions under this License. 152 | 153 | 8. Limitation of Liability. In no event and under no legal theory, 154 | whether in tort (including negligence), contract, or otherwise, 155 | unless required by applicable law (such as deliberate and grossly 156 | negligent acts) or agreed to in writing, shall any Contributor be 157 | liable to You for damages, including any direct, indirect, special, 158 | incidental, or consequential damages of any character arising as a 159 | result of this License or out of the use or inability to use the 160 | Work (including but not limited to damages for loss of goodwill, 161 | work stoppage, computer failure or malfunction, or any and all 162 | other commercial damages or losses), even if such Contributor 163 | has been advised of the possibility of such damages. 164 | 165 | 9. Accepting Warranty or Additional Liability. While redistributing 166 | the Work or Derivative Works thereof, You may choose to offer, 167 | and charge a fee for, acceptance of support, warranty, indemnity, 168 | or other liability obligations and/or rights consistent with this 169 | License. However, in accepting such obligations, You may act only 170 | on Your own behalf and on Your sole responsibility, not on behalf 171 | of any other Contributor, and only if You agree to indemnify, 172 | defend, and hold each Contributor harmless for any liability 173 | incurred by, or claims asserted against, such Contributor by reason 174 | of your accepting any such warranty or additional liability. 175 | 176 | END OF TERMS AND CONDITIONS 177 | 178 | APPENDIX: How to apply the Apache License to your work. 179 | 180 | To apply the Apache License to your work, attach the following 181 | boilerplate notice, with the fields enclosed by brackets "{}" 182 | replaced with your own identifying information. (Don't include 183 | the brackets!) The text should be enclosed in the appropriate 184 | comment syntax for the file format. We also recommend that a 185 | file or class name and description of purpose be included on the 186 | same "printed page" as the copyright notice for easier 187 | identification within third-party archives. 188 | 189 | Copyright {yyyy} {name of copyright owner} 190 | 191 | Licensed under the Apache License, Version 2.0 (the "License"); 192 | you may not use this file except in compliance with the License. 193 | You may obtain a copy of the License at 194 | 195 | http://www.apache.org/licenses/LICENSE-2.0 196 | 197 | Unless required by applicable law or agreed to in writing, software 198 | distributed under the License is distributed on an "AS IS" BASIS, 199 | WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 200 | See the License for the specific language governing permissions and 201 | limitations under the License. 202 | --------------------------------------------------------------------------------