├── .gitignore ├── .travis.yml ├── src └── main │ ├── webapp │ ├── fonts │ │ ├── glyphicons-halflings-regular.eot │ │ ├── glyphicons-halflings-regular.ttf │ │ ├── glyphicons-halflings-regular.woff │ │ └── glyphicons-halflings-regular.svg │ ├── js │ │ ├── config.js │ │ └── app.js │ ├── css │ │ └── custom.css │ ├── partials │ │ ├── edit.html │ │ ├── create.html │ │ ├── index.html │ │ └── login.html │ ├── WEB-INF │ │ └── web.xml │ └── index.html │ ├── resources │ ├── application.properties │ ├── log4j2.xml │ ├── META-INF │ │ └── persistence.xml │ └── context.xml │ └── java │ └── net │ └── dontdrinkandroot │ └── example │ └── angularrestspringsecurity │ ├── entity │ ├── Entity.java │ ├── Role.java │ ├── BlogPost.java │ ├── AccessToken.java │ └── User.java │ ├── JsonViews.java │ ├── transfer │ ├── TokenTransfer.java │ └── UserTransfer.java │ ├── dao │ ├── Dao.java │ ├── accesstoken │ │ ├── AccessTokenDao.java │ │ └── JpaAccessTokenDao.java │ ├── blogpost │ │ ├── BlogPostDao.java │ │ └── JpaBlogPostDao.java │ ├── user │ │ ├── UserDao.java │ │ └── JpaUserDao.java │ ├── DataBaseInitializer.java │ └── JpaDao.java │ ├── service │ ├── UserService.java │ └── DaoUserService.java │ └── rest │ ├── UnauthorizedEntryPoint.java │ ├── AuthenticationTokenProcessingFilter.java │ └── resources │ ├── UserResource.java │ └── BlogPostResource.java ├── README.md ├── pom.xml └── LICENSE /.gitignore: -------------------------------------------------------------------------------- 1 | *.iml 2 | /.idea/ 3 | /.settings 4 | /target 5 | /.classpath 6 | /.project 7 | -------------------------------------------------------------------------------- /.travis.yml: -------------------------------------------------------------------------------- 1 | language: java 2 | 3 | jdk: 4 | - oraclejdk8 5 | 6 | cache: 7 | directories: 8 | - "$HOME/.m2/repository" 9 | 10 | script: 11 | - mvn clean test 12 | -------------------------------------------------------------------------------- /src/main/webapp/fonts/glyphicons-halflings-regular.eot: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/philipsorst/angular-rest-springsecurity/HEAD/src/main/webapp/fonts/glyphicons-halflings-regular.eot -------------------------------------------------------------------------------- /src/main/webapp/fonts/glyphicons-halflings-regular.ttf: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/philipsorst/angular-rest-springsecurity/HEAD/src/main/webapp/fonts/glyphicons-halflings-regular.ttf -------------------------------------------------------------------------------- /src/main/webapp/fonts/glyphicons-halflings-regular.woff: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/philipsorst/angular-rest-springsecurity/HEAD/src/main/webapp/fonts/glyphicons-halflings-regular.woff -------------------------------------------------------------------------------- /src/main/resources/application.properties: -------------------------------------------------------------------------------- 1 | # Database variables 2 | db.username=sa 3 | db.password= 4 | db.driver=org.hsqldb.jdbcDriver 5 | db.url=jdbc:hsqldb:mem:example 6 | 7 | # Application secret used for salting 8 | app.secret=ThisIsASecretSoChangeMe 9 | -------------------------------------------------------------------------------- /src/main/webapp/js/config.js: -------------------------------------------------------------------------------- 1 | var exampleAppConfig = { 2 | /* When set to false a query parameter is used to pass on the access token. 3 | * This might be desirable if headers don't work correctly in some 4 | * environments and is still secure when using https. */ 5 | useAccessTokenHeader: true, 6 | debug: true 7 | }; -------------------------------------------------------------------------------- /src/main/webapp/css/custom.css: -------------------------------------------------------------------------------- 1 | body { 2 | padding-top: 60px; 3 | } 4 | 5 | .loader { 6 | font-size: 36px; 7 | line-height: 36px; 8 | font-weight: bold; 9 | width: 200px; 10 | height: 92px; 11 | text-align: center; 12 | position: absolute; 13 | top: 0; 14 | bottom: 0; 15 | left: 0; 16 | right: 0; 17 | margin: auto; 18 | } -------------------------------------------------------------------------------- /src/main/java/net/dontdrinkandroot/example/angularrestspringsecurity/entity/Entity.java: -------------------------------------------------------------------------------- 1 | package net.dontdrinkandroot.example.angularrestspringsecurity.entity; 2 | 3 | import java.io.Serializable; 4 | 5 | /** 6 | * @author Philip Washington Sorst 7 | */ 8 | public interface Entity extends Serializable 9 | { 10 | Long getId(); 11 | } 12 | -------------------------------------------------------------------------------- /src/main/java/net/dontdrinkandroot/example/angularrestspringsecurity/JsonViews.java: -------------------------------------------------------------------------------- 1 | package net.dontdrinkandroot.example.angularrestspringsecurity; 2 | 3 | /** 4 | * @author Philip Washington Sorst 5 | */ 6 | public class JsonViews 7 | { 8 | public static class User 9 | { 10 | } 11 | 12 | public static class Admin extends User 13 | { 14 | } 15 | } 16 | -------------------------------------------------------------------------------- /src/main/java/net/dontdrinkandroot/example/angularrestspringsecurity/transfer/TokenTransfer.java: -------------------------------------------------------------------------------- 1 | package net.dontdrinkandroot.example.angularrestspringsecurity.transfer; 2 | 3 | public class TokenTransfer 4 | { 5 | 6 | private final String token; 7 | 8 | 9 | public TokenTransfer(String token) 10 | { 11 | this.token = token; 12 | } 13 | 14 | 15 | public String getToken() 16 | { 17 | return this.token; 18 | } 19 | 20 | } -------------------------------------------------------------------------------- /src/main/resources/log4j2.xml: -------------------------------------------------------------------------------- 1 | 2 | 3 | 4 | 5 | 6 | 7 | 8 | 9 | 10 | 11 | 12 | 13 | 14 | -------------------------------------------------------------------------------- /src/main/java/net/dontdrinkandroot/example/angularrestspringsecurity/dao/Dao.java: -------------------------------------------------------------------------------- 1 | package net.dontdrinkandroot.example.angularrestspringsecurity.dao; 2 | 3 | import net.dontdrinkandroot.example.angularrestspringsecurity.entity.Entity; 4 | 5 | import java.util.List; 6 | 7 | public interface Dao 8 | { 9 | List findAll(); 10 | 11 | T find(I id); 12 | 13 | T save(T entity); 14 | 15 | void delete(I id); 16 | 17 | void delete(T entity); 18 | } 19 | -------------------------------------------------------------------------------- /src/main/java/net/dontdrinkandroot/example/angularrestspringsecurity/dao/accesstoken/AccessTokenDao.java: -------------------------------------------------------------------------------- 1 | package net.dontdrinkandroot.example.angularrestspringsecurity.dao.accesstoken; 2 | 3 | import net.dontdrinkandroot.example.angularrestspringsecurity.dao.Dao; 4 | import net.dontdrinkandroot.example.angularrestspringsecurity.entity.AccessToken; 5 | 6 | /** 7 | * @author Philip Washington Sorst 8 | */ 9 | public interface AccessTokenDao extends Dao 10 | { 11 | AccessToken findByToken(String accessTokenString); 12 | } 13 | -------------------------------------------------------------------------------- /src/main/java/net/dontdrinkandroot/example/angularrestspringsecurity/dao/blogpost/BlogPostDao.java: -------------------------------------------------------------------------------- 1 | package net.dontdrinkandroot.example.angularrestspringsecurity.dao.blogpost; 2 | 3 | import net.dontdrinkandroot.example.angularrestspringsecurity.dao.Dao; 4 | import net.dontdrinkandroot.example.angularrestspringsecurity.entity.BlogPost; 5 | 6 | /** 7 | * Definition of a Data Access Object that can perform CRUD Operations for {@link BlogPost}s. 8 | * 9 | * @author Philip Washington Sorst 10 | */ 11 | public interface BlogPostDao extends Dao 12 | { 13 | } 14 | -------------------------------------------------------------------------------- /src/main/java/net/dontdrinkandroot/example/angularrestspringsecurity/dao/user/UserDao.java: -------------------------------------------------------------------------------- 1 | package net.dontdrinkandroot.example.angularrestspringsecurity.dao.user; 2 | 3 | import net.dontdrinkandroot.example.angularrestspringsecurity.dao.Dao; 4 | import net.dontdrinkandroot.example.angularrestspringsecurity.entity.User; 5 | import org.springframework.security.core.userdetails.UsernameNotFoundException; 6 | 7 | public interface UserDao extends Dao 8 | { 9 | User loadUserByUsername(String username) throws UsernameNotFoundException; 10 | 11 | User findByName(String name); 12 | } 13 | -------------------------------------------------------------------------------- /src/main/java/net/dontdrinkandroot/example/angularrestspringsecurity/entity/Role.java: -------------------------------------------------------------------------------- 1 | package net.dontdrinkandroot.example.angularrestspringsecurity.entity; 2 | 3 | import org.springframework.security.core.GrantedAuthority; 4 | 5 | public enum Role implements GrantedAuthority 6 | { 7 | USER("ROLE_USER"), 8 | ADMIN("ROLE_ADMIN"); 9 | 10 | private String authority; 11 | 12 | Role(String authority) 13 | { 14 | this.authority = authority; 15 | } 16 | 17 | @Override 18 | public String getAuthority() 19 | { 20 | return this.authority; 21 | } 22 | } 23 | -------------------------------------------------------------------------------- /src/main/webapp/partials/edit.html: -------------------------------------------------------------------------------- 1 | 4 | 5 |
6 |
7 | 8 |
9 | 11 |
12 |
13 |
14 |
15 | 16 |
17 |
18 |
-------------------------------------------------------------------------------- /src/main/webapp/partials/create.html: -------------------------------------------------------------------------------- 1 | 4 | 5 |
6 |
7 | 8 |
9 | 11 |
12 |
13 |
14 |
15 | 16 |
17 |
18 |
-------------------------------------------------------------------------------- /src/main/java/net/dontdrinkandroot/example/angularrestspringsecurity/service/UserService.java: -------------------------------------------------------------------------------- 1 | package net.dontdrinkandroot.example.angularrestspringsecurity.service; 2 | 3 | import net.dontdrinkandroot.example.angularrestspringsecurity.entity.AccessToken; 4 | import net.dontdrinkandroot.example.angularrestspringsecurity.entity.User; 5 | import org.springframework.security.core.userdetails.UserDetailsService; 6 | 7 | /** 8 | * @author Philip Washington Sorst 9 | */ 10 | public interface UserService extends UserDetailsService 11 | { 12 | User findUserByAccessToken(String accessToken); 13 | 14 | AccessToken createAccessToken(User user); 15 | } 16 | -------------------------------------------------------------------------------- /src/main/java/net/dontdrinkandroot/example/angularrestspringsecurity/transfer/UserTransfer.java: -------------------------------------------------------------------------------- 1 | package net.dontdrinkandroot.example.angularrestspringsecurity.transfer; 2 | 3 | import java.util.Map; 4 | 5 | 6 | public class UserTransfer 7 | { 8 | 9 | private final String name; 10 | 11 | private final Map roles; 12 | 13 | 14 | public UserTransfer(String userName, Map roles) 15 | { 16 | this.name = userName; 17 | this.roles = roles; 18 | } 19 | 20 | 21 | public String getName() 22 | { 23 | return this.name; 24 | } 25 | 26 | 27 | public Map getRoles() 28 | { 29 | return this.roles; 30 | } 31 | 32 | } -------------------------------------------------------------------------------- /src/main/resources/META-INF/persistence.xml: -------------------------------------------------------------------------------- 1 | 2 | 7 | 8 | net.dontdrinkandroot.example.angularrestspringsecurity.entity.AccessToken 9 | net.dontdrinkandroot.example.angularrestspringsecurity.entity.BlogPost 10 | net.dontdrinkandroot.example.angularrestspringsecurity.entity.User 11 | 12 | 13 | -------------------------------------------------------------------------------- /src/main/webapp/partials/index.html: -------------------------------------------------------------------------------- 1 |
2 | 3 |
4 | 7 | 8 |
9 |
10 |
11 | 13 | 15 |
16 |

{{blogPost.date | date}}

17 |

{{blogPost.content}}

18 |
19 |
20 | -------------------------------------------------------------------------------- /src/main/java/net/dontdrinkandroot/example/angularrestspringsecurity/rest/UnauthorizedEntryPoint.java: -------------------------------------------------------------------------------- 1 | package net.dontdrinkandroot.example.angularrestspringsecurity.rest; 2 | 3 | import org.springframework.security.core.AuthenticationException; 4 | import org.springframework.security.web.AuthenticationEntryPoint; 5 | 6 | import javax.servlet.ServletException; 7 | import javax.servlet.http.HttpServletRequest; 8 | import javax.servlet.http.HttpServletResponse; 9 | import java.io.IOException; 10 | 11 | /** 12 | * {@link AuthenticationEntryPoint} that rejects all requests with an unauthorized error message. 13 | * 14 | * @author Philip W. Sorst 15 | */ 16 | public class UnauthorizedEntryPoint implements AuthenticationEntryPoint 17 | { 18 | @Override 19 | public void commence( 20 | HttpServletRequest request, 21 | HttpServletResponse response, 22 | AuthenticationException authException 23 | ) throws IOException, ServletException 24 | { 25 | response.sendError( 26 | HttpServletResponse.SC_UNAUTHORIZED, 27 | "Unauthorized: Authentication token was either missing or invalid." 28 | ); 29 | } 30 | } 31 | -------------------------------------------------------------------------------- /src/main/webapp/partials/login.html: -------------------------------------------------------------------------------- 1 | 4 | 5 |
6 | 7 |
8 |
9 |
10 | 11 |
12 | 13 |
14 |
15 |
16 | 17 |
18 | 19 |
20 |
21 |
22 |
23 |
24 | 27 |
28 |
29 |
30 |
31 |
32 | 33 |
34 |
35 |
36 |
37 | 38 |
39 |

Login with either user:user to read entries or with admin:admin to read and edit entries.

40 |
41 | 42 |
-------------------------------------------------------------------------------- /src/main/java/net/dontdrinkandroot/example/angularrestspringsecurity/dao/blogpost/JpaBlogPostDao.java: -------------------------------------------------------------------------------- 1 | package net.dontdrinkandroot.example.angularrestspringsecurity.dao.blogpost; 2 | 3 | import net.dontdrinkandroot.example.angularrestspringsecurity.dao.JpaDao; 4 | import net.dontdrinkandroot.example.angularrestspringsecurity.entity.BlogPost; 5 | import org.springframework.transaction.annotation.Transactional; 6 | 7 | import javax.persistence.TypedQuery; 8 | import javax.persistence.criteria.CriteriaBuilder; 9 | import javax.persistence.criteria.CriteriaQuery; 10 | import javax.persistence.criteria.Root; 11 | import java.util.List; 12 | 13 | /** 14 | * JPA Implementation of a {@link BlogPostDao}. 15 | * 16 | * @author Philip Washington Sorst 17 | */ 18 | public class JpaBlogPostDao extends JpaDao implements BlogPostDao 19 | { 20 | public JpaBlogPostDao() 21 | { 22 | super(BlogPost.class); 23 | } 24 | 25 | @Override 26 | @Transactional(readOnly = true) 27 | public List findAll() 28 | { 29 | final CriteriaBuilder builder = this.getEntityManager().getCriteriaBuilder(); 30 | final CriteriaQuery criteriaQuery = builder.createQuery(BlogPost.class); 31 | 32 | Root root = criteriaQuery.from(BlogPost.class); 33 | criteriaQuery.orderBy(builder.desc(root.get("date"))); 34 | 35 | TypedQuery typedQuery = this.getEntityManager().createQuery(criteriaQuery); 36 | return typedQuery.getResultList(); 37 | } 38 | } 39 | -------------------------------------------------------------------------------- /src/main/java/net/dontdrinkandroot/example/angularrestspringsecurity/dao/accesstoken/JpaAccessTokenDao.java: -------------------------------------------------------------------------------- 1 | package net.dontdrinkandroot.example.angularrestspringsecurity.dao.accesstoken; 2 | 3 | import net.dontdrinkandroot.example.angularrestspringsecurity.dao.JpaDao; 4 | import net.dontdrinkandroot.example.angularrestspringsecurity.entity.AccessToken; 5 | import org.springframework.transaction.annotation.Transactional; 6 | 7 | import javax.persistence.NoResultException; 8 | import javax.persistence.criteria.CriteriaBuilder; 9 | import javax.persistence.criteria.CriteriaQuery; 10 | import javax.persistence.criteria.Root; 11 | 12 | /** 13 | * @author Philip Washington Sorst 14 | */ 15 | public class JpaAccessTokenDao extends JpaDao implements AccessTokenDao 16 | { 17 | public JpaAccessTokenDao() 18 | { 19 | super(AccessToken.class); 20 | } 21 | 22 | @Override 23 | @Transactional(readOnly = true, noRollbackFor = NoResultException.class) 24 | public AccessToken findByToken(String accessTokenString) 25 | { 26 | CriteriaBuilder builder = this.getEntityManager().getCriteriaBuilder(); 27 | CriteriaQuery query = builder.createQuery(this.entityClass); 28 | Root root = query.from(this.entityClass); 29 | query.where(builder.equal(root.get("token"), accessTokenString)); 30 | 31 | try { 32 | return this.getEntityManager().createQuery(query).getSingleResult(); 33 | } catch (NoResultException e) { 34 | return null; 35 | } 36 | } 37 | } 38 | -------------------------------------------------------------------------------- /src/main/java/net/dontdrinkandroot/example/angularrestspringsecurity/entity/BlogPost.java: -------------------------------------------------------------------------------- 1 | package net.dontdrinkandroot.example.angularrestspringsecurity.entity; 2 | 3 | import com.fasterxml.jackson.annotation.JsonView; 4 | import net.dontdrinkandroot.example.angularrestspringsecurity.JsonViews; 5 | 6 | import javax.persistence.Column; 7 | import javax.persistence.GeneratedValue; 8 | import javax.persistence.Id; 9 | import java.util.Date; 10 | 11 | /** 12 | * JPA Annotated Pojo that represents a blog post. 13 | * 14 | * @author Philip Washington Sorst 15 | */ 16 | @javax.persistence.Entity 17 | public class BlogPost implements Entity 18 | { 19 | @Id 20 | @GeneratedValue 21 | private Long id; 22 | 23 | @Column 24 | private Date date; 25 | 26 | @Column 27 | private String content; 28 | 29 | public BlogPost() 30 | { 31 | this.date = new Date(); 32 | } 33 | 34 | @JsonView(JsonViews.Admin.class) 35 | public Long getId() 36 | { 37 | return this.id; 38 | } 39 | 40 | @JsonView(JsonViews.User.class) 41 | public Date getDate() 42 | { 43 | return this.date; 44 | } 45 | 46 | public void setDate(Date date) 47 | { 48 | this.date = date; 49 | } 50 | 51 | @JsonView(JsonViews.User.class) 52 | public String getContent() 53 | { 54 | return this.content; 55 | } 56 | 57 | public void setContent(String content) 58 | { 59 | this.content = content; 60 | } 61 | 62 | @Override 63 | public String toString() 64 | { 65 | return String.format("BlogPost[%d, %s]", this.id, this.content); 66 | } 67 | } 68 | -------------------------------------------------------------------------------- /src/main/java/net/dontdrinkandroot/example/angularrestspringsecurity/entity/AccessToken.java: -------------------------------------------------------------------------------- 1 | package net.dontdrinkandroot.example.angularrestspringsecurity.entity; 2 | 3 | import javax.persistence.Column; 4 | import javax.persistence.GeneratedValue; 5 | import javax.persistence.Id; 6 | import javax.persistence.ManyToOne; 7 | import java.util.Date; 8 | 9 | /** 10 | * @author Philip Washington Sorst 11 | */ 12 | @javax.persistence.Entity 13 | public class AccessToken implements Entity 14 | { 15 | @Id 16 | @GeneratedValue 17 | private Long id; 18 | 19 | @Column(nullable = false) 20 | private String token; 21 | 22 | @ManyToOne 23 | private User user; 24 | 25 | @Column 26 | private Date expiry; 27 | 28 | protected AccessToken() 29 | { 30 | /* Reflection instantiation */ 31 | } 32 | 33 | public AccessToken(User user, String token) 34 | { 35 | this.user = user; 36 | this.token = token; 37 | } 38 | 39 | public AccessToken(User user, String token, Date expiry) 40 | { 41 | this(user, token); 42 | this.expiry = expiry; 43 | } 44 | 45 | @Override 46 | public Long getId() 47 | { 48 | return this.id; 49 | } 50 | 51 | public String getToken() 52 | { 53 | return this.token; 54 | } 55 | 56 | public User getUser() 57 | { 58 | return this.user; 59 | } 60 | 61 | public Date getExpiry() 62 | { 63 | return this.expiry; 64 | } 65 | 66 | public boolean isExpired() 67 | { 68 | if (null == this.expiry) { 69 | return false; 70 | } 71 | 72 | return this.expiry.getTime() > System.currentTimeMillis(); 73 | } 74 | } 75 | -------------------------------------------------------------------------------- /src/main/webapp/WEB-INF/web.xml: -------------------------------------------------------------------------------- 1 | 2 | 6 | 7 | angular-rest-springsecurity 8 | 9 | 12 | 13 | contextConfigLocation 14 | 15 | classpath:/context.xml 16 | 17 | 18 | 19 | org.springframework.web.context.ContextLoaderListener 20 | 21 | 22 | 25 | 26 | RestService 27 | org.glassfish.jersey.servlet.ServletContainer 28 | 29 | jersey.config.server.provider.packages 30 | net.dontdrinkandroot.example.angularrestspringsecurity.rest 31 | 32 | 1 33 | 34 | 35 | RestService 36 | /rest/* 37 | 38 | 39 | 42 | 43 | springSecurityFilterChain 44 | org.springframework.web.filter.DelegatingFilterProxy 45 | 46 | 47 | springSecurityFilterChain 48 | /* 49 | 50 | 51 | -------------------------------------------------------------------------------- /README.md: -------------------------------------------------------------------------------- 1 | angular-rest-springsecurity 2 | =========================== 3 | 4 | [![Build Status](https://travis-ci.org/philipsorst/angular-rest-springsecurity.svg?branch=master)](https://travis-ci.org/philipsorst/angular-rest-springsecurity) 5 | [![Donate](https://img.shields.io/badge/Donate-PayPal-green.svg)](https://www.paypal.com/cgi-bin/webscr?cmd=_donations&business=W9NAXW8YAZ4D6&item_name=Angular+REST+SpringSecurity+Example+Donation¤cy_code=EUR) 6 | 7 | An example AngularJS Application that uses a Spring Security protected Jersey REST backend based on Hibernate/JPA. 8 | 9 | About 10 | ----- 11 | 12 | The projects aim is to demonstrate the Java implementation of a simple REST interface which is used by an AngularJS application. The following topics are covered: 13 | 14 | * A relational database that holds blog posts and users. 15 | * A REST service that exposes the data in the database. 16 | * Authentication and authorization against the REST service. 17 | * A Simple AngularJS application that allows users to view or edit news entries depending on their role. 18 | * A responsive design. 19 | 20 | This project is just meant to be a demonstration, therefore it is neither well documented nor well tested. Use it to learn about the technologies used, but do not use it for productive applications. 21 | 22 | Any feedback is welcome, and I will incorporate useful pull requests. 23 | 24 | Technologies 25 | ------------ 26 | 27 | * [AngularJS](http://angularjs.org/) 28 | * [Bootstrap](http://getbootstrap.com/) 29 | * [Jersey](https://jersey.java.net/) 30 | * [Spring Security](http://projects.spring.io/spring-security/) 31 | * [Hibernate](http://hibernate.org/) 32 | 33 | Running 34 | ------- 35 | 36 | Make sure Java >= 8 and [Maven](http://maven.apache.org/) >= 3.0 is installed on your system. Go into the project dir and type `mvn jetty:run`, then point your browser to `http://localhost:8080`. 37 | 38 | License 39 | ------- 40 | 41 | [The Apache Software License, Version 2.0](http://www.apache.org/licenses/LICENSE-2.0.txt) -------------------------------------------------------------------------------- /src/main/java/net/dontdrinkandroot/example/angularrestspringsecurity/dao/user/JpaUserDao.java: -------------------------------------------------------------------------------- 1 | package net.dontdrinkandroot.example.angularrestspringsecurity.dao.user; 2 | 3 | import net.dontdrinkandroot.example.angularrestspringsecurity.dao.JpaDao; 4 | import net.dontdrinkandroot.example.angularrestspringsecurity.entity.User; 5 | import org.springframework.security.core.userdetails.UsernameNotFoundException; 6 | import org.springframework.transaction.annotation.Transactional; 7 | 8 | import javax.persistence.TypedQuery; 9 | import javax.persistence.criteria.CriteriaBuilder; 10 | import javax.persistence.criteria.CriteriaQuery; 11 | import javax.persistence.criteria.Path; 12 | import javax.persistence.criteria.Root; 13 | import java.util.List; 14 | 15 | /** 16 | * @author Philip Washington Sorst 17 | */ 18 | public class JpaUserDao extends JpaDao implements UserDao 19 | { 20 | public JpaUserDao() 21 | { 22 | super(User.class); 23 | } 24 | 25 | @Override 26 | @Transactional(readOnly = true) 27 | public User loadUserByUsername(String username) throws UsernameNotFoundException 28 | { 29 | User user = this.findByName(username); 30 | if (null == user) { 31 | throw new UsernameNotFoundException("The user with name " + username + " was not found"); 32 | } 33 | 34 | return user; 35 | } 36 | 37 | @Override 38 | @Transactional(readOnly = true) 39 | public User findByName(String name) 40 | { 41 | final CriteriaBuilder builder = this.getEntityManager().getCriteriaBuilder(); 42 | final CriteriaQuery criteriaQuery = builder.createQuery(this.entityClass); 43 | 44 | Root root = criteriaQuery.from(this.entityClass); 45 | Path namePath = root.get("name"); 46 | criteriaQuery.where(builder.equal(namePath, name)); 47 | 48 | TypedQuery typedQuery = this.getEntityManager().createQuery(criteriaQuery); 49 | List users = typedQuery.getResultList(); 50 | 51 | if (users.isEmpty()) { 52 | return null; 53 | } 54 | 55 | return users.iterator().next(); 56 | } 57 | } 58 | -------------------------------------------------------------------------------- /src/main/java/net/dontdrinkandroot/example/angularrestspringsecurity/dao/DataBaseInitializer.java: -------------------------------------------------------------------------------- 1 | package net.dontdrinkandroot.example.angularrestspringsecurity.dao; 2 | 3 | import net.dontdrinkandroot.example.angularrestspringsecurity.dao.blogpost.BlogPostDao; 4 | import net.dontdrinkandroot.example.angularrestspringsecurity.dao.user.UserDao; 5 | import net.dontdrinkandroot.example.angularrestspringsecurity.entity.BlogPost; 6 | import net.dontdrinkandroot.example.angularrestspringsecurity.entity.Role; 7 | import net.dontdrinkandroot.example.angularrestspringsecurity.entity.User; 8 | import org.springframework.security.crypto.password.PasswordEncoder; 9 | 10 | import java.util.Date; 11 | 12 | /** 13 | * Initialize the database with some test entries. 14 | * 15 | * @author Philip Washington Sorst 16 | */ 17 | public class DataBaseInitializer 18 | { 19 | private BlogPostDao blogPostDao; 20 | 21 | private UserDao userDao; 22 | 23 | private PasswordEncoder passwordEncoder; 24 | 25 | protected DataBaseInitializer() 26 | { 27 | /* Default constructor for reflection instantiation */ 28 | } 29 | 30 | public DataBaseInitializer(UserDao userDao, BlogPostDao blogPostDao, PasswordEncoder passwordEncoder) 31 | { 32 | this.userDao = userDao; 33 | this.blogPostDao = blogPostDao; 34 | this.passwordEncoder = passwordEncoder; 35 | } 36 | 37 | public void initDataBase() 38 | { 39 | User userUser = new User("user", this.passwordEncoder.encode("user")); 40 | userUser.addRole(Role.USER); 41 | this.userDao.save(userUser); 42 | 43 | User adminUser = new User("admin", this.passwordEncoder.encode("admin")); 44 | adminUser.addRole(Role.USER); 45 | adminUser.addRole(Role.ADMIN); 46 | this.userDao.save(adminUser); 47 | 48 | long timestamp = System.currentTimeMillis() - (1000 * 60 * 60 * 24); 49 | for (int i = 0; i < 10; i++) { 50 | BlogPost blogPost = new BlogPost(); 51 | blogPost.setContent("This is example content " + i); 52 | blogPost.setDate(new Date(timestamp)); 53 | this.blogPostDao.save(blogPost); 54 | timestamp += 1000 * 60 * 60; 55 | } 56 | } 57 | } 58 | -------------------------------------------------------------------------------- /src/main/java/net/dontdrinkandroot/example/angularrestspringsecurity/service/DaoUserService.java: -------------------------------------------------------------------------------- 1 | package net.dontdrinkandroot.example.angularrestspringsecurity.service; 2 | 3 | import net.dontdrinkandroot.example.angularrestspringsecurity.dao.accesstoken.AccessTokenDao; 4 | import net.dontdrinkandroot.example.angularrestspringsecurity.dao.user.UserDao; 5 | import net.dontdrinkandroot.example.angularrestspringsecurity.entity.AccessToken; 6 | import net.dontdrinkandroot.example.angularrestspringsecurity.entity.User; 7 | import org.springframework.security.core.userdetails.UserDetails; 8 | import org.springframework.security.core.userdetails.UsernameNotFoundException; 9 | import org.springframework.transaction.annotation.Transactional; 10 | 11 | import java.util.UUID; 12 | 13 | /** 14 | * @author Philip Washington Sorst 15 | */ 16 | public class DaoUserService implements UserService 17 | { 18 | private UserDao userDao; 19 | 20 | private AccessTokenDao accessTokenDao; 21 | 22 | protected DaoUserService() 23 | { 24 | /* Reflection instantiation */ 25 | } 26 | 27 | public DaoUserService(UserDao userDao, AccessTokenDao accessTokenDao) 28 | { 29 | this.userDao = userDao; 30 | this.accessTokenDao = accessTokenDao; 31 | } 32 | 33 | @Override 34 | @Transactional(readOnly = true) 35 | public UserDetails loadUserByUsername(String username) throws UsernameNotFoundException 36 | { 37 | return this.userDao.loadUserByUsername(username); 38 | } 39 | 40 | @Override 41 | @Transactional 42 | public User findUserByAccessToken(String accessTokenString) 43 | { 44 | AccessToken accessToken = this.accessTokenDao.findByToken(accessTokenString); 45 | 46 | if (null == accessToken) { 47 | return null; 48 | } 49 | 50 | if (accessToken.isExpired()) { 51 | this.accessTokenDao.delete(accessToken); 52 | return null; 53 | } 54 | 55 | return accessToken.getUser(); 56 | } 57 | 58 | @Override 59 | @Transactional 60 | public AccessToken createAccessToken(User user) 61 | { 62 | AccessToken accessToken = new AccessToken(user, UUID.randomUUID().toString()); 63 | return this.accessTokenDao.save(accessToken); 64 | } 65 | } 66 | -------------------------------------------------------------------------------- /src/main/java/net/dontdrinkandroot/example/angularrestspringsecurity/dao/JpaDao.java: -------------------------------------------------------------------------------- 1 | package net.dontdrinkandroot.example.angularrestspringsecurity.dao; 2 | 3 | import net.dontdrinkandroot.example.angularrestspringsecurity.entity.Entity; 4 | import org.springframework.transaction.annotation.Transactional; 5 | 6 | import javax.persistence.EntityManager; 7 | import javax.persistence.PersistenceContext; 8 | import javax.persistence.TypedQuery; 9 | import javax.persistence.criteria.CriteriaBuilder; 10 | import javax.persistence.criteria.CriteriaQuery; 11 | import java.util.List; 12 | 13 | /** 14 | * @param Type of the Entity. 15 | * @param Type of the Primary Key. 16 | * @author Philip Washington Sorst 17 | */ 18 | public class JpaDao implements Dao 19 | { 20 | private EntityManager entityManager; 21 | 22 | protected Class entityClass; 23 | 24 | public JpaDao(Class entityClass) 25 | { 26 | this.entityClass = entityClass; 27 | } 28 | 29 | public EntityManager getEntityManager() 30 | { 31 | return this.entityManager; 32 | } 33 | 34 | @PersistenceContext 35 | public void setEntityManager(final EntityManager entityManager) 36 | { 37 | this.entityManager = entityManager; 38 | } 39 | 40 | @Override 41 | @Transactional(readOnly = true) 42 | public List findAll() 43 | { 44 | final CriteriaBuilder builder = this.getEntityManager().getCriteriaBuilder(); 45 | final CriteriaQuery criteriaQuery = builder.createQuery(this.entityClass); 46 | 47 | criteriaQuery.from(this.entityClass); 48 | 49 | TypedQuery typedQuery = this.getEntityManager().createQuery(criteriaQuery); 50 | return typedQuery.getResultList(); 51 | } 52 | 53 | @Override 54 | @Transactional(readOnly = true) 55 | public T find(I id) 56 | { 57 | return this.getEntityManager().find(this.entityClass, id); 58 | } 59 | 60 | @Override 61 | @Transactional 62 | public T save(T entity) 63 | { 64 | return this.getEntityManager().merge(entity); 65 | } 66 | 67 | @Override 68 | @Transactional 69 | public void delete(I id) 70 | { 71 | if (id == null) { 72 | return; 73 | } 74 | 75 | T entity = this.find(id); 76 | if (entity == null) { 77 | return; 78 | } 79 | 80 | this.getEntityManager().remove(entity); 81 | } 82 | 83 | @Override 84 | @Transactional 85 | public void delete(T entity) 86 | { 87 | this.getEntityManager().remove(entity); 88 | } 89 | } 90 | -------------------------------------------------------------------------------- /src/main/java/net/dontdrinkandroot/example/angularrestspringsecurity/rest/AuthenticationTokenProcessingFilter.java: -------------------------------------------------------------------------------- 1 | package net.dontdrinkandroot.example.angularrestspringsecurity.rest; 2 | 3 | import net.dontdrinkandroot.example.angularrestspringsecurity.entity.User; 4 | import net.dontdrinkandroot.example.angularrestspringsecurity.service.UserService; 5 | import org.springframework.security.authentication.UsernamePasswordAuthenticationToken; 6 | import org.springframework.security.core.context.SecurityContextHolder; 7 | import org.springframework.web.filter.GenericFilterBean; 8 | 9 | import javax.servlet.FilterChain; 10 | import javax.servlet.ServletException; 11 | import javax.servlet.ServletRequest; 12 | import javax.servlet.ServletResponse; 13 | import javax.servlet.http.HttpServletRequest; 14 | import java.io.IOException; 15 | 16 | /** 17 | * @author Philip Washington Sorst 18 | */ 19 | public class AuthenticationTokenProcessingFilter extends GenericFilterBean 20 | { 21 | private final UserService userService; 22 | 23 | public AuthenticationTokenProcessingFilter(UserService userService) 24 | { 25 | this.userService = userService; 26 | } 27 | 28 | @Override 29 | public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain) 30 | throws IOException, ServletException 31 | { 32 | HttpServletRequest httpRequest = this.getAsHttpRequest(request); 33 | 34 | String accessToken = this.extractAccessTokenFromRequest(httpRequest); 35 | if (null != accessToken) { 36 | User user = this.userService.findUserByAccessToken(accessToken); 37 | if (null != user) { 38 | UsernamePasswordAuthenticationToken authentication = 39 | new UsernamePasswordAuthenticationToken(user, null, user.getAuthorities()); 40 | SecurityContextHolder.getContext().setAuthentication(authentication); 41 | } 42 | } 43 | 44 | chain.doFilter(request, response); 45 | } 46 | 47 | private HttpServletRequest getAsHttpRequest(ServletRequest request) 48 | { 49 | if (!(request instanceof HttpServletRequest)) { 50 | throw new RuntimeException("Expecting an HTTP request"); 51 | } 52 | 53 | return (HttpServletRequest) request; 54 | } 55 | 56 | private String extractAccessTokenFromRequest(HttpServletRequest httpRequest) 57 | { 58 | /* Get token from header */ 59 | String authToken = httpRequest.getHeader("X-Access-Token"); 60 | 61 | /* If token not found get it from request parameter */ 62 | if (authToken == null) { 63 | authToken = httpRequest.getParameter("token"); 64 | } 65 | 66 | return authToken; 67 | } 68 | } 69 | -------------------------------------------------------------------------------- /src/main/java/net/dontdrinkandroot/example/angularrestspringsecurity/entity/User.java: -------------------------------------------------------------------------------- 1 | package net.dontdrinkandroot.example.angularrestspringsecurity.entity; 2 | 3 | import org.springframework.security.core.GrantedAuthority; 4 | import org.springframework.security.core.userdetails.UserDetails; 5 | 6 | import javax.persistence.*; 7 | import java.util.Collection; 8 | import java.util.HashSet; 9 | import java.util.Set; 10 | 11 | /** 12 | * @author Philip Washington Sorst 13 | */ 14 | @javax.persistence.Entity 15 | public class User implements Entity, UserDetails 16 | { 17 | @Id 18 | @GeneratedValue 19 | private Long id; 20 | 21 | @Column(unique = true, length = 16, nullable = false) 22 | private String name; 23 | 24 | @Column(length = 80, nullable = false) 25 | private String password; 26 | 27 | @ElementCollection(fetch = FetchType.EAGER) 28 | private Set roles = new HashSet(); 29 | 30 | protected User() 31 | { 32 | /* Reflection instantiation */ 33 | } 34 | 35 | public User(String name, String passwordHash) 36 | { 37 | this.name = name; 38 | this.password = passwordHash; 39 | } 40 | 41 | public Long getId() 42 | { 43 | return this.id; 44 | } 45 | 46 | public void setId(Long id) 47 | { 48 | this.id = id; 49 | } 50 | 51 | public String getName() 52 | { 53 | return this.name; 54 | } 55 | 56 | public void setName(String name) 57 | { 58 | this.name = name; 59 | } 60 | 61 | public Set getRoles() 62 | { 63 | return this.roles; 64 | } 65 | 66 | public void setRoles(Set roles) 67 | { 68 | this.roles = roles; 69 | } 70 | 71 | public void addRole(Role role) 72 | { 73 | this.roles.add(role); 74 | } 75 | 76 | @Override 77 | public String getPassword() 78 | { 79 | return this.password; 80 | } 81 | 82 | public void setPassword(String password) 83 | { 84 | this.password = password; 85 | } 86 | 87 | @Override 88 | public Collection getAuthorities() 89 | { 90 | return this.getRoles(); 91 | } 92 | 93 | @Override 94 | public String getUsername() 95 | { 96 | return this.name; 97 | } 98 | 99 | @Override 100 | public boolean isAccountNonExpired() 101 | { 102 | return true; 103 | } 104 | 105 | @Override 106 | public boolean isAccountNonLocked() 107 | { 108 | return true; 109 | } 110 | 111 | @Override 112 | public boolean isCredentialsNonExpired() 113 | { 114 | return true; 115 | } 116 | 117 | @Override 118 | public boolean isEnabled() 119 | { 120 | return true; 121 | } 122 | } 123 | -------------------------------------------------------------------------------- /src/main/java/net/dontdrinkandroot/example/angularrestspringsecurity/rest/resources/UserResource.java: -------------------------------------------------------------------------------- 1 | package net.dontdrinkandroot.example.angularrestspringsecurity.rest.resources; 2 | 3 | import net.dontdrinkandroot.example.angularrestspringsecurity.entity.AccessToken; 4 | import net.dontdrinkandroot.example.angularrestspringsecurity.entity.User; 5 | import net.dontdrinkandroot.example.angularrestspringsecurity.service.UserService; 6 | import net.dontdrinkandroot.example.angularrestspringsecurity.transfer.UserTransfer; 7 | import org.springframework.beans.factory.annotation.Autowired; 8 | import org.springframework.beans.factory.annotation.Qualifier; 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.GrantedAuthority; 13 | import org.springframework.security.core.context.SecurityContextHolder; 14 | import org.springframework.security.core.userdetails.UserDetails; 15 | import org.springframework.stereotype.Component; 16 | 17 | import javax.ws.rs.*; 18 | import javax.ws.rs.core.MediaType; 19 | import javax.ws.rs.core.Response; 20 | import java.util.HashMap; 21 | import java.util.Map; 22 | 23 | /** 24 | * @author Philip Washington Sorst 25 | */ 26 | @Component 27 | @Path("/user") 28 | public class UserResource 29 | { 30 | @Autowired 31 | private UserService userService; 32 | 33 | @Autowired 34 | @Qualifier("authenticationManager") 35 | private AuthenticationManager authManager; 36 | 37 | /** 38 | * Retrieves the currently logged in user. 39 | * 40 | * @return A transfer containing the username and the roles. 41 | */ 42 | @GET 43 | @Produces(MediaType.APPLICATION_JSON) 44 | public UserTransfer getUser() 45 | { 46 | Authentication authentication = SecurityContextHolder.getContext().getAuthentication(); 47 | Object principal = authentication.getPrincipal(); 48 | if (!(principal instanceof UserDetails)) { 49 | throw new WebApplicationException(Response.Status.UNAUTHORIZED); 50 | } 51 | UserDetails userDetails = (UserDetails) principal; 52 | 53 | return new UserTransfer(userDetails.getUsername(), this.createRoleMap(userDetails)); 54 | } 55 | 56 | /** 57 | * Authenticates a user and creates an access token. 58 | * 59 | * @param username The name of the user. 60 | * @param password The password of the user. 61 | * @return The generated access token. 62 | */ 63 | @Path("authenticate") 64 | @POST 65 | @Produces(MediaType.APPLICATION_JSON) 66 | public AccessToken authenticate(@FormParam("username") String username, @FormParam("password") String password) 67 | { 68 | UsernamePasswordAuthenticationToken authenticationToken = 69 | new UsernamePasswordAuthenticationToken(username, password); 70 | Authentication authentication = this.authManager.authenticate(authenticationToken); 71 | SecurityContextHolder.getContext().setAuthentication(authentication); 72 | 73 | Object principal = authentication.getPrincipal(); 74 | if (!(principal instanceof User)) { 75 | throw new WebApplicationException(Response.Status.UNAUTHORIZED); 76 | } 77 | 78 | return this.userService.createAccessToken((User) principal); 79 | } 80 | 81 | private Map createRoleMap(UserDetails userDetails) 82 | { 83 | Map roles = new HashMap<>(); 84 | for (GrantedAuthority authority : userDetails.getAuthorities()) { 85 | roles.put(authority.getAuthority(), Boolean.TRUE); 86 | } 87 | 88 | return roles; 89 | } 90 | } 91 | -------------------------------------------------------------------------------- /src/main/webapp/index.html: -------------------------------------------------------------------------------- 1 | 2 | 3 | 4 | 5 | 6 | 7 | Angular Rest SpringSecurity Example 8 | 10 | 12 | 13 | 18 | 19 | 20 | 21 |
22 |

Loading

23 |

24 |
25 | 26 | 60 | 61 |
62 |
{{error}}
63 |
64 |
65 | 66 | 67 | 70 | 71 | 73 | 75 | 77 | 78 | 79 | 80 | -------------------------------------------------------------------------------- /src/main/java/net/dontdrinkandroot/example/angularrestspringsecurity/rest/resources/BlogPostResource.java: -------------------------------------------------------------------------------- 1 | package net.dontdrinkandroot.example.angularrestspringsecurity.rest.resources; 2 | 3 | import com.fasterxml.jackson.databind.ObjectMapper; 4 | import com.fasterxml.jackson.databind.ObjectWriter; 5 | import net.dontdrinkandroot.example.angularrestspringsecurity.JsonViews; 6 | import net.dontdrinkandroot.example.angularrestspringsecurity.dao.blogpost.BlogPostDao; 7 | import net.dontdrinkandroot.example.angularrestspringsecurity.entity.BlogPost; 8 | import net.dontdrinkandroot.example.angularrestspringsecurity.entity.Role; 9 | import org.slf4j.Logger; 10 | import org.slf4j.LoggerFactory; 11 | import org.springframework.beans.factory.annotation.Autowired; 12 | import org.springframework.security.core.Authentication; 13 | import org.springframework.security.core.context.SecurityContextHolder; 14 | import org.springframework.security.core.userdetails.UserDetails; 15 | import org.springframework.stereotype.Component; 16 | 17 | import javax.ws.rs.*; 18 | import javax.ws.rs.core.MediaType; 19 | import javax.ws.rs.core.Response; 20 | import java.io.IOException; 21 | import java.util.List; 22 | 23 | /** 24 | * @author Philip Washington Sorst 25 | */ 26 | @Component 27 | @Path("/blogposts") 28 | public class BlogPostResource 29 | { 30 | private final Logger logger = LoggerFactory.getLogger(this.getClass()); 31 | 32 | @Autowired 33 | private BlogPostDao blogPostDao; 34 | 35 | @Autowired 36 | private ObjectMapper mapper; 37 | 38 | @GET 39 | @Produces(MediaType.APPLICATION_JSON) 40 | public String list() throws IOException 41 | { 42 | this.logger.info("list()"); 43 | 44 | ObjectWriter viewWriter; 45 | if (this.isAdmin()) { 46 | viewWriter = this.mapper.writerWithView(JsonViews.Admin.class); 47 | } else { 48 | viewWriter = this.mapper.writerWithView(JsonViews.User.class); 49 | } 50 | List allEntries = this.blogPostDao.findAll(); 51 | 52 | return viewWriter.writeValueAsString(allEntries); 53 | } 54 | 55 | @GET 56 | @Produces(MediaType.APPLICATION_JSON) 57 | @Path("{id}") 58 | public BlogPost read(@PathParam("id") Long id) 59 | { 60 | this.logger.info("read(id)"); 61 | 62 | BlogPost blogPost = this.blogPostDao.find(id); 63 | if (blogPost == null) { 64 | throw new WebApplicationException(Response.Status.NOT_FOUND); 65 | } 66 | 67 | return blogPost; 68 | } 69 | 70 | @POST 71 | @Produces(MediaType.APPLICATION_JSON) 72 | @Consumes(MediaType.APPLICATION_JSON) 73 | public BlogPost create(BlogPost blogPost) 74 | { 75 | this.logger.info("create(): " + blogPost); 76 | 77 | return this.blogPostDao.save(blogPost); 78 | } 79 | 80 | @POST 81 | @Produces(MediaType.APPLICATION_JSON) 82 | @Consumes(MediaType.APPLICATION_JSON) 83 | @Path("{id}") 84 | public BlogPost update(@PathParam("id") Long id, BlogPost blogPost) 85 | { 86 | this.logger.info("update(): " + blogPost); 87 | 88 | return this.blogPostDao.save(blogPost); 89 | } 90 | 91 | @DELETE 92 | @Produces(MediaType.APPLICATION_JSON) 93 | @Path("{id}") 94 | public void delete(@PathParam("id") Long id) 95 | { 96 | this.logger.info("delete(id)"); 97 | 98 | this.blogPostDao.delete(id); 99 | } 100 | 101 | private boolean isAdmin() 102 | { 103 | Authentication authentication = SecurityContextHolder.getContext().getAuthentication(); 104 | Object principal = authentication.getPrincipal(); 105 | 106 | if (!(principal instanceof UserDetails)) { 107 | return false; 108 | } 109 | 110 | UserDetails userDetails = (UserDetails) principal; 111 | 112 | return userDetails.getAuthorities().contains(Role.ADMIN); 113 | } 114 | } 115 | -------------------------------------------------------------------------------- /src/main/resources/context.xml: -------------------------------------------------------------------------------- 1 | 2 | 11 | 12 | 15 | 16 | 17 | 18 | 19 | 20 | 21 | 22 | 23 | 24 | 25 | 26 | 27 | 28 | 31 | 32 | 33 | 34 | 35 | 36 | 37 | 38 | 39 | 41 | 42 | 43 | 44 | 45 | 46 | 47 | 48 | 49 | 50 | 51 | 52 | 53 | 54 | 55 | 56 | 57 | 58 | 59 | 60 | 61 | 63 | 64 | 65 | 66 | 67 | 68 | 69 | 70 | 73 | 74 | 75 | 76 | 77 | 78 | 81 | 82 | 83 | 84 | 87 | 88 | 89 | 90 | 91 | 92 | 93 | 94 | 95 | 96 | 97 | 98 | 102 | 103 | 104 | 105 | 106 | 107 | 108 | 109 | 110 | 111 | 113 | 114 | 116 | 117 | 118 | 119 | 120 | -------------------------------------------------------------------------------- /pom.xml: -------------------------------------------------------------------------------- 1 | 3 | 4.0.0 4 | net.dontdrinkandroot.example 5 | angular-rest-springsecurity 6 | 0.4.0-SNAPSHOT 7 | war 8 | 9 | 10 | UTF-8 11 | 4.2.3.RELEASE 12 | 4.3.9.RELEASE 13 | 1.19.4 14 | 2.26-b07 15 | 5.2.10.Final 16 | 2.8.2 17 | 3.1.0 18 | 2.4.0 19 | 2.1.1 20 | 4.12 21 | 22 | 3.6.1 23 | 9.4.6.v20170531 24 | 25 | 26 | 27 | 28 | Philip Washington Sorst 29 | https://sorst.net 30 | 31 | 32 | 33 | 34 | 35 | The Apache Software License, Version 2.0 36 | http://www.apache.org/licenses/LICENSE-2.0.txt 37 | repo 38 | 39 | 40 | 41 | 42 | 3.0 43 | 44 | 45 | 46 | 47 | 48 | org.apache.maven.plugins 49 | maven-compiler-plugin 50 | ${version.maven-compiler-plugin} 51 | 52 | 1.8 53 | 1.8 54 | 55 | 56 | 57 | org.eclipse.jetty 58 | jetty-maven-plugin 59 | ${version.org.eclipse.jetty.jetty-maven-plugin} 60 | 61 | 62 | / 63 | .*/^(asm-all-repackaged)[^/]*\.jar$ 64 | 65 | 66 | 67 | 68 | 69 | 70 | 71 | scm:git:https://github.com/philipsorst/angular-rest-springsecurity.git 72 | 73 | HEAD 74 | 75 | 76 | 77 | 78 | 79 | org.springframework 80 | spring-orm 81 | ${version.org.springframework} 82 | 83 | 84 | 85 | org.springframework 86 | spring-tx 87 | ${version.org.springframework} 88 | 89 | 90 | 91 | org.glassfish.jersey.ext 92 | jersey-spring4 93 | ${version.org.glassfish.jersey} 94 | 95 | 96 | 97 | org.glassfish.jersey.media 98 | jersey-media-json-jackson 99 | ${version.org.glassfish.jersey} 100 | 101 | 102 | 103 | org.hsqldb 104 | hsqldb 105 | ${version.org.hsqldb} 106 | 107 | 108 | 109 | org.apache.commons 110 | commons-dbcp2 111 | ${version.org.apache.commons.dbcp2} 112 | 113 | 114 | 115 | org.hibernate 116 | hibernate-entitymanager 117 | ${version.org.hibernate} 118 | 119 | 120 | 121 | org.apache.logging.log4j 122 | log4j-core 123 | ${version.org.apache.logging.log4j} 124 | 125 | 126 | 127 | org.apache.logging.log4j 128 | log4j-slf4j-impl 129 | ${version.org.apache.logging.log4j} 130 | 131 | 132 | 133 | org.springframework.security 134 | spring-security-web 135 | ${version.org.springframework.security} 136 | 137 | 138 | 139 | org.springframework.security 140 | spring-security-config 141 | ${version.org.springframework.security} 142 | 143 | 144 | 145 | javax.servlet 146 | javax.servlet-api 147 | ${version.javax.servlet-api} 148 | provided 149 | 150 | 151 | 152 | org.springframework 153 | spring-test 154 | ${version.org.springframework} 155 | test 156 | 157 | 158 | 159 | junit 160 | junit 161 | ${version.junit} 162 | test 163 | 164 | 165 | 166 | 167 | -------------------------------------------------------------------------------- /src/main/webapp/js/app.js: -------------------------------------------------------------------------------- 1 | angular.module('exampleApp', ['ngRoute', 'ngCookies', 'exampleApp.services']) 2 | .config( 3 | ['$routeProvider', '$locationProvider', '$httpProvider', function ($routeProvider, $locationProvider, $httpProvider) { 4 | 5 | $routeProvider.when('/create', { 6 | templateUrl: 'partials/create.html', 7 | controller: CreateController 8 | }); 9 | 10 | $routeProvider.when('/edit/:id', { 11 | templateUrl: 'partials/edit.html', 12 | controller: EditController 13 | }); 14 | 15 | $routeProvider.when('/login', { 16 | templateUrl: 'partials/login.html', 17 | controller: LoginController 18 | }); 19 | 20 | $routeProvider.otherwise({ 21 | templateUrl: 'partials/index.html', 22 | controller: IndexController 23 | }); 24 | 25 | $locationProvider.hashPrefix('!'); 26 | 27 | /* Register error provider that shows message on failed requests or redirects to login page on 28 | * unauthenticated requests */ 29 | $httpProvider.interceptors.push(function ($q, $rootScope, $location) { 30 | return { 31 | 'responseError': function (rejection) { 32 | var status = rejection.status; 33 | var config = rejection.config; 34 | var method = config.method; 35 | var url = config.url; 36 | 37 | if (status == 401) { 38 | $location.path("/login"); 39 | } else { 40 | $rootScope.error = method + " on " + url + " failed with status " + status; 41 | } 42 | 43 | return $q.reject(rejection); 44 | } 45 | }; 46 | } 47 | ); 48 | 49 | /* Registers auth token interceptor, auth token is either passed by header or by query parameter 50 | * as soon as there is an authenticated user */ 51 | $httpProvider.interceptors.push(function ($q, $rootScope, $location) { 52 | return { 53 | 'request': function (config) { 54 | var isRestCall = config.url.indexOf('rest') == 0; 55 | if (isRestCall && angular.isDefined($rootScope.accessToken)) { 56 | var accessToken = $rootScope.accessToken; 57 | if (exampleAppConfig.useAccessTokenHeader) { 58 | config.headers['X-Access-Token'] = accessToken; 59 | } else { 60 | config.url = config.url + "?token=" + accessToken; 61 | } 62 | } 63 | return config || $q.when(config); 64 | } 65 | }; 66 | } 67 | ); 68 | 69 | }] 70 | ).run(function ($rootScope, $location, $cookieStore, UserService) { 71 | 72 | /* Reset error when a new view is loaded */ 73 | $rootScope.$on('$viewContentLoaded', function () { 74 | delete $rootScope.error; 75 | }); 76 | 77 | $rootScope.hasRole = function (role) { 78 | 79 | if ($rootScope.user === undefined) { 80 | return false; 81 | } 82 | 83 | if ($rootScope.user.roles[role] === undefined) { 84 | return false; 85 | } 86 | 87 | return $rootScope.user.roles[role]; 88 | }; 89 | 90 | $rootScope.logout = function () { 91 | delete $rootScope.user; 92 | delete $rootScope.accessToken; 93 | $cookieStore.remove('accessToken'); 94 | $location.path("/login"); 95 | }; 96 | 97 | /* Try getting valid user from cookie or go to login page */ 98 | var originalPath = $location.path(); 99 | $location.path("/login"); 100 | var accessToken = $cookieStore.get('accessToken'); 101 | if (accessToken !== undefined) { 102 | $rootScope.accessToken = accessToken; 103 | UserService.get(function (user) { 104 | $rootScope.user = user; 105 | $location.path(originalPath); 106 | }); 107 | } 108 | 109 | $rootScope.initialized = true; 110 | }); 111 | 112 | function IndexController($scope, BlogPostService) { 113 | 114 | $scope.blogPosts = BlogPostService.query(); 115 | 116 | $scope.deletePost = function (blogPost) { 117 | blogPost.$remove(function () { 118 | $scope.blogPosts = BlogPostService.query(); 119 | }); 120 | }; 121 | } 122 | 123 | function EditController($scope, $routeParams, $location, BlogPostService) { 124 | 125 | $scope.blogPost = BlogPostService.get({id: $routeParams.id}); 126 | 127 | $scope.save = function () { 128 | $scope.blogPost.$save(function () { 129 | $location.path('/'); 130 | }); 131 | }; 132 | } 133 | 134 | function CreateController($scope, $location, BlogPostService) { 135 | 136 | $scope.blogPost = new BlogPostService(); 137 | 138 | $scope.save = function () { 139 | $scope.blogPost.$save(function () { 140 | $location.path('/'); 141 | }); 142 | }; 143 | } 144 | 145 | function LoginController($scope, $rootScope, $location, $cookieStore, UserService) { 146 | 147 | $scope.rememberMe = false; 148 | 149 | $scope.login = function () { 150 | UserService.authenticate($.param({ 151 | username: $scope.username, 152 | password: $scope.password 153 | }), function (authenticationResult) { 154 | var accessToken = authenticationResult.token; 155 | $rootScope.accessToken = accessToken; 156 | if ($scope.rememberMe) { 157 | $cookieStore.put('accessToken', accessToken); 158 | } 159 | UserService.get(function (user) { 160 | $rootScope.user = user; 161 | $location.path("/"); 162 | }); 163 | }); 164 | }; 165 | } 166 | 167 | var services = angular.module('exampleApp.services', ['ngResource']); 168 | 169 | services.factory('UserService', function ($resource) { 170 | 171 | return $resource('rest/user/:action', {}, 172 | { 173 | authenticate: { 174 | method: 'POST', 175 | params: {'action': 'authenticate'}, 176 | headers: {'Content-Type': 'application/x-www-form-urlencoded'} 177 | } 178 | } 179 | ); 180 | }); 181 | 182 | services.factory('BlogPostService', function ($resource) { 183 | 184 | return $resource('rest/blogposts/:id', {id: '@id'}); 185 | }); 186 | -------------------------------------------------------------------------------- /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, and 10 | distribution as defined by Sections 1 through 9 of this document. 11 | 12 | "Licensor" shall mean the copyright owner or entity authorized by the copyright 13 | owner that is granting the License. 14 | 15 | "Legal Entity" shall mean the union of the acting entity and all other entities 16 | that control, are controlled by, or are under common control with that entity. 17 | For the purposes of this definition, "control" means (i) the power, direct or 18 | indirect, to cause the direction or management of such entity, whether by 19 | contract or otherwise, or (ii) ownership of fifty percent (50%) or more of the 20 | outstanding shares, or (iii) beneficial ownership of such entity. 21 | 22 | "You" (or "Your") shall mean an individual or Legal Entity exercising 23 | permissions granted by this License. 24 | 25 | "Source" form shall mean the preferred form for making modifications, including 26 | but not limited to software source code, documentation source, and configuration 27 | files. 28 | 29 | "Object" form shall mean any form resulting from mechanical transformation or 30 | translation of a Source form, including but not limited to compiled object code, 31 | generated documentation, and conversions to other media types. 32 | 33 | "Work" shall mean the work of authorship, whether in Source or Object form, made 34 | available under the License, as indicated by a copyright notice that is included 35 | in or attached to the work (an example is provided in the Appendix below). 36 | 37 | "Derivative Works" shall mean any work, whether in Source or Object form, that 38 | is based on (or derived from) the Work and for which the editorial revisions, 39 | annotations, elaborations, or other modifications represent, as a whole, an 40 | original work of authorship. For the purposes of this License, Derivative Works 41 | shall not include works that remain separable from, or merely link (or bind by 42 | name) to the interfaces of, the Work and Derivative Works thereof. 43 | 44 | "Contribution" shall mean any work of authorship, including the original version 45 | of the Work and any modifications or additions to that Work or Derivative Works 46 | thereof, that is intentionally submitted to Licensor for inclusion in the Work 47 | by the copyright owner or by an individual or Legal Entity authorized to submit 48 | on behalf of the copyright owner. For the purposes of this definition, 49 | "submitted" means any form of electronic, verbal, or written communication sent 50 | to the Licensor or its representatives, including but not limited to 51 | communication on electronic mailing lists, source code control systems, and 52 | issue tracking systems that are managed by, or on behalf of, the Licensor for 53 | the purpose of discussing and improving the Work, but excluding communication 54 | that is conspicuously marked or otherwise designated in writing by the copyright 55 | owner as "Not a Contribution." 56 | 57 | "Contributor" shall mean Licensor and any individual or Legal Entity on behalf 58 | of whom a Contribution has been received by Licensor and subsequently 59 | incorporated within the Work. 60 | 61 | 2. Grant of Copyright License. 62 | 63 | Subject to the terms and conditions of this License, each Contributor hereby 64 | grants to You a perpetual, worldwide, non-exclusive, no-charge, royalty-free, 65 | irrevocable copyright license to reproduce, prepare Derivative Works of, 66 | publicly display, publicly perform, sublicense, and distribute the Work and such 67 | Derivative Works in Source or Object form. 68 | 69 | 3. Grant of Patent License. 70 | 71 | Subject to the terms and conditions of this License, each Contributor hereby 72 | grants to You a perpetual, worldwide, non-exclusive, no-charge, royalty-free, 73 | irrevocable (except as stated in this section) patent license to make, have 74 | made, use, offer to sell, sell, import, and otherwise transfer the Work, where 75 | such license applies only to those patent claims licensable by such Contributor 76 | that are necessarily infringed by their Contribution(s) alone or by combination 77 | of their Contribution(s) with the Work to which such Contribution(s) was 78 | submitted. If You institute patent litigation against any entity (including a 79 | cross-claim or counterclaim in a lawsuit) alleging that the Work or a 80 | Contribution incorporated within the Work constitutes direct or contributory 81 | patent infringement, then any patent licenses granted to You under this License 82 | for that Work shall terminate as of the date such litigation is filed. 83 | 84 | 4. Redistribution. 85 | 86 | You may reproduce and distribute copies of the Work or Derivative Works thereof 87 | in any medium, with or without modifications, and in Source or Object form, 88 | provided that You meet the following conditions: 89 | 90 | You must give any other recipients of the Work or Derivative Works a copy of 91 | this License; and 92 | You must cause any modified files to carry prominent notices stating that You 93 | changed the files; and 94 | You must retain, in the Source form of any Derivative Works that You distribute, 95 | all copyright, patent, trademark, and attribution notices from the Source form 96 | of the Work, excluding those notices that do not pertain to any part of the 97 | Derivative Works; and 98 | If the Work includes a "NOTICE" text file as part of its distribution, then any 99 | Derivative Works that You distribute must include a readable copy of the 100 | attribution notices contained within such NOTICE file, excluding those notices 101 | that do not pertain to any part of the Derivative Works, in at least one of the 102 | following places: within a NOTICE text file distributed as part of the 103 | Derivative Works; within the Source form or documentation, if provided along 104 | with the Derivative Works; or, within a display generated by the Derivative 105 | Works, if and wherever such third-party notices normally appear. The contents of 106 | the NOTICE file are for informational purposes only and do not modify the 107 | License. You may add Your own attribution notices within Derivative Works that 108 | You distribute, alongside or as an addendum to the NOTICE text from the Work, 109 | provided that such additional attribution notices cannot be construed as 110 | modifying the License. 111 | You may add Your own copyright statement to Your modifications and may provide 112 | additional or different license terms and conditions for use, reproduction, or 113 | distribution of Your modifications, or for any such Derivative Works as a whole, 114 | provided Your use, reproduction, and distribution of the Work otherwise complies 115 | with the conditions stated in this License. 116 | 117 | 5. Submission of Contributions. 118 | 119 | Unless You explicitly state otherwise, any Contribution intentionally submitted 120 | for inclusion in the Work by You to the Licensor shall be under the terms and 121 | conditions of this License, without any additional terms or conditions. 122 | Notwithstanding the above, nothing herein shall supersede or modify the terms of 123 | any separate license agreement you may have executed with Licensor regarding 124 | such Contributions. 125 | 126 | 6. Trademarks. 127 | 128 | This License does not grant permission to use the trade names, trademarks, 129 | service marks, or product names of the Licensor, except as required for 130 | reasonable and customary use in describing the origin of the Work and 131 | reproducing the content of the NOTICE file. 132 | 133 | 7. Disclaimer of Warranty. 134 | 135 | Unless required by applicable law or agreed to in writing, Licensor provides the 136 | Work (and each Contributor provides its Contributions) on an "AS IS" BASIS, 137 | WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied, 138 | including, without limitation, any warranties or conditions of TITLE, 139 | NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A PARTICULAR PURPOSE. You are 140 | solely responsible for determining the appropriateness of using or 141 | redistributing the Work and assume any risks associated with Your exercise of 142 | permissions under this License. 143 | 144 | 8. Limitation of Liability. 145 | 146 | In no event and under no legal theory, whether in tort (including negligence), 147 | contract, or otherwise, unless required by applicable law (such as deliberate 148 | and grossly negligent acts) or agreed to in writing, shall any Contributor be 149 | liable to You for damages, including any direct, indirect, special, incidental, 150 | or consequential damages of any character arising as a result of this License or 151 | out of the use or inability to use the Work (including but not limited to 152 | damages for loss of goodwill, work stoppage, computer failure or malfunction, or 153 | any and all other commercial damages or losses), even if such Contributor has 154 | been advised of the possibility of such damages. 155 | 156 | 9. Accepting Warranty or Additional Liability. 157 | 158 | While redistributing the Work or Derivative Works thereof, You may choose to 159 | offer, and charge a fee for, acceptance of support, warranty, indemnity, or 160 | other liability obligations and/or rights consistent with this License. However, 161 | in accepting such obligations, You may act only on Your own behalf and on Your 162 | sole responsibility, not on behalf of any other Contributor, and only if You 163 | agree to indemnify, defend, and hold each Contributor harmless for any liability 164 | incurred by, or claims asserted against, such Contributor by reason of your 165 | accepting any such warranty or additional liability. 166 | 167 | END OF TERMS AND CONDITIONS 168 | 169 | APPENDIX: How to apply the Apache License to your work 170 | 171 | To apply the Apache License to your work, attach the following boilerplate 172 | notice, with the fields enclosed by brackets "[]" replaced with your own 173 | identifying information. (Don't include the brackets!) The text should be 174 | enclosed in the appropriate comment syntax for the file format. We also 175 | recommend that a file or class name and description of purpose be included on 176 | the same "printed page" as the copyright notice for easier identification within 177 | third-party archives. 178 | 179 | Copyright [yyyy] [name of copyright owner] 180 | 181 | Licensed under the Apache License, Version 2.0 (the "License"); 182 | you may not use this file except in compliance with the License. 183 | You may obtain a copy of the License at 184 | 185 | http://www.apache.org/licenses/LICENSE-2.0 186 | 187 | Unless required by applicable law or agreed to in writing, software 188 | distributed under the License is distributed on an "AS IS" BASIS, 189 | WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 190 | See the License for the specific language governing permissions and 191 | limitations under the License. 192 | -------------------------------------------------------------------------------- /src/main/webapp/fonts/glyphicons-halflings-regular.svg: -------------------------------------------------------------------------------- 1 | 2 | 3 | 4 | 5 | 6 | 7 | 8 | 9 | 10 | 11 | 12 | 13 | 14 | 15 | 16 | 17 | 18 | 19 | 20 | 21 | 22 | 23 | 24 | 25 | 26 | 27 | 28 | 29 | 30 | 31 | 32 | 33 | 34 | 35 | 36 | 37 | 38 | 39 | 40 | 41 | 42 | 43 | 44 | 45 | 46 | 47 | 48 | 49 | 50 | 51 | 52 | 53 | 54 | 55 | 56 | 57 | 58 | 59 | 60 | 61 | 62 | 63 | 64 | 65 | 66 | 67 | 68 | 69 | 70 | 71 | 72 | 73 | 74 | 75 | 76 | 77 | 78 | 79 | 80 | 81 | 82 | 83 | 84 | 85 | 86 | 87 | 88 | 89 | 90 | 91 | 92 | 93 | 94 | 95 | 96 | 97 | 98 | 99 | 100 | 101 | 102 | 103 | 104 | 105 | 106 | 107 | 108 | 109 | 110 | 111 | 112 | 113 | 114 | 115 | 116 | 117 | 118 | 119 | 120 | 121 | 122 | 123 | 124 | 125 | 126 | 127 | 128 | 129 | 130 | 131 | 132 | 133 | 134 | 135 | 136 | 137 | 138 | 139 | 140 | 141 | 142 | 143 | 144 | 145 | 146 | 147 | 148 | 149 | 150 | 151 | 152 | 153 | 154 | 155 | 156 | 157 | 158 | 159 | 160 | 161 | 162 | 163 | 164 | 165 | 166 | 167 | 168 | 169 | 170 | 171 | 172 | 173 | 174 | 175 | 176 | 177 | 178 | 179 | 180 | 181 | 182 | 183 | 184 | 185 | 186 | 187 | 188 | 189 | 190 | 191 | 192 | 193 | 194 | 195 | 196 | 197 | 198 | 199 | 200 | 201 | 202 | 203 | 204 | 205 | 206 | 207 | 208 | 209 | 210 | 211 | 212 | 213 | 214 | 215 | 216 | 217 | 218 | 219 | 220 | 221 | 222 | 223 | 224 | 225 | 226 | 227 | 228 | 229 | --------------------------------------------------------------------------------