Compare commits

...

3 Commits

Author SHA1 Message Date
e775a3cd6d Final changes 2019-01-16 15:32:18 +01:00
c778570c50 Product Controller "/customProduct" 2019-01-15 23:39:47 +01:00
3db194ea21 Added JWTAuthorizationFilter 2019-01-14 02:40:48 +01:00
7 changed files with 162 additions and 23 deletions

14
pom.xml
View File

@@ -36,6 +36,20 @@
<artifactId>spring-boot-starter-web</artifactId>
</dependency>
<!-- JAVA-JWT Auth0-->
<dependency>
<groupId>com.auth0</groupId>
<artifactId>java-jwt</artifactId>
<version>3.5.0</version>
</dependency>
<!-- https://mvnrepository.com/artifact/commons-codec/commons-codec -->
<dependency>
<groupId>commons-codec</groupId>
<artifactId>commons-codec</artifactId>
<version>1.11</version>
</dependency>
<dependency>
<groupId>org.projectlombok</groupId>
<artifactId>lombok</artifactId>

View File

@@ -1,19 +0,0 @@
package me.aski.catalogueservice.sec;
import org.springframework.web.filter.OncePerRequestFilter;
import javax.servlet.FilterChain;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
public class JWTAuthorizationFilter extends OncePerRequestFilter {
@Override
protected void doFilterInternal(HttpServletRequest httpServletRequest, HttpServletResponse httpServletResponse, FilterChain filterChain) throws ServletException, IOException {
System.out.println("**********");
String jwt = httpServletRequest.getHeader("Authorization");
if (jwt == null) throw new RuntimeException("Not Authorized");
filterChain.doFilter(httpServletRequest, httpServletResponse);
}
}

View File

@@ -0,0 +1,58 @@
package me.aski.catalogueservice.security;
import com.auth0.jwt.JWT;
import com.auth0.jwt.JWTVerifier;
import com.auth0.jwt.algorithms.Algorithm;
import com.auth0.jwt.interfaces.DecodedJWT;
import org.springframework.security.authentication.UsernamePasswordAuthenticationToken;
import org.springframework.security.core.GrantedAuthority;
import org.springframework.security.core.authority.SimpleGrantedAuthority;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.web.filter.OncePerRequestFilter;
import javax.servlet.FilterChain;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.util.Collection;
import java.util.List;
import java.util.stream.Collectors;
public class JWTAuthorizationFilter extends OncePerRequestFilter {
@Override
protected void doFilterInternal(HttpServletRequest request, HttpServletResponse response, FilterChain filterChain) throws ServletException, IOException {
response.setHeader("Access-Control-Allow-Origin", "*");
response.setHeader("Access-Control-Allow-Methods", "POST, GET, OPTIONS, DELETE, PUT, PATCH");
String allHeaders = "No-Auth, Accept, Accept-CH, Accept-Charset, Accept-Datetime, Accept-Encoding, Accept-Ext, Accept-Features, Accept-Language, Accept-Params, Accept-Ranges, Access-Control-Allow-Credentials, Access-Control-Allow-Headers, Access-Control-Allow-Methods, Access-Control-Allow-Origin, Access-Control-Expose-Headers, Access-Control-Max-Age, Access-Control-Request-Headers, Access-Control-Request-Method, Age, Allow, Alternates, Authentication-Info, Authorization, C-Ext, C-Man, C-Opt, C-PEP, C-PEP-Info, CONNECT, Cache-Control, Compliance, Connection, Content-Base, Content-Disposition, Content-Encoding, Content-ID, Content-Language, Content-Length, Content-Location, Content-MD5, Content-Range, Content-Script-Type, Content-Security-Policy, Content-Style-Type, Content-Transfer-Encoding, Content-Type, Content-Version, Cookie, Cost, DAV, DELETE, DNT, DPR, Date, Default-Style, Delta-Base, Depth, Derived-From, Destination, Differential-ID, Digest, ETag, Expect, Expires, Ext, From, GET, GetProfile, HEAD, HTTP-date, Host, IM, If, If-Match, If-Modified-Since, If-None-Match, If-Range, If-Unmodified-Since, Keep-Alive, Label, Last-Event-ID, Last-Modified, Link, Location, Lock-Token, MIME-Version, Man, Max-Forwards, Media-Range, Message-ID, Meter, Negotiate, Non-Compliance, OPTION, OPTIONS, OWS, Opt, Optional, Ordering-Type, Origin, Overwrite, P3P, PEP, PICS-Label, POST, PUT, Pep-Info, Permanent, Position, Pragma, ProfileObject, Protocol, Protocol-Query, Protocol-Request, Proxy-Authenticate, Proxy-Authentication-Info, Proxy-Authorization, Proxy-Features, Proxy-Instruction, Public, RWS, Range, Referer, Refresh, Resolution-Hint, Resolver-Location, Retry-After, Safe, Sec-Websocket-Extensions, Sec-Websocket-Key, Sec-Websocket-Origin, Sec-Websocket-Protocol, Sec-Websocket-Version, Security-Scheme, Server, Set-Cookie, Set-Cookie2, SetProfile, SoapAction, Status, Status-URI, Strict-Transport-Security, SubOK, Subst, Surrogate-Capability, Surrogate-Control, TCN, TE, TRACE, Timeout, Title, Trailer, Transfer-Encoding, UA-Color, UA-Media, UA-Pixels, UA-Resolution, UA-Windowpixels, URI, Upgrade, User-Agent, Variant-Vary, Vary, Version, Via, Viewport-Width, WWW-Authenticate, Want-Digest, Warning, Width, X-Content-Duration, X-Content-Security-Policy, X-Content-Type-Options, X-CustomHeader, X-DNSPrefetch-Control, X-Forwarded-For, X-Forwarded-Port, X-Forwarded-Proto, X-Frame-Options, X-Modified, X-OTHER, X-PING, X-PINGOTHER, X-Powered-By, X-Requested-With";
response.setHeader("Access-Control-Allow-Headers", allHeaders);
response.setHeader("Access-Control-Expose-Headers", allHeaders);
response.setHeader("Access-Control-Allow-Credentials", "true");
if ("OPTIONS".equalsIgnoreCase(request.getMethod())) {
response.setStatus(HttpServletResponse.SC_OK);
} else {
String jwtToken = request.getHeader(SecurityParams.HEADER_NAME);
if (jwtToken == null || !jwtToken.startsWith(SecurityParams.PREFIX)) {
//throw new RuntimeException("Not Authorized");
filterChain.doFilter(request, response);
return;
}
String jwt = jwtToken.substring(SecurityParams.PREFIX.length());
JWTVerifier verifier = JWT.require(Algorithm.HMAC256(SecurityParams.SECRET))
.build();
DecodedJWT decodedJWT = verifier.verify(jwt);
String username = decodedJWT.getSubject();
List<String> roles = decodedJWT.getClaims().get("roles").asList(String.class);
Collection<GrantedAuthority> authorities = roles.stream().map(SimpleGrantedAuthority::new).collect(Collectors.toList());
UsernamePasswordAuthenticationToken user = new UsernamePasswordAuthenticationToken(username, null, authorities);
SecurityContextHolder.getContext().setAuthentication(user);
filterChain.doFilter(request, response);
}
}
}

View File

@@ -1,8 +1,8 @@
package me.aski.catalogueservice.sec;
package me.aski.catalogueservice.security;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.security.config.annotation.authentication.builders.AuthenticationManagerBuilder;
import org.springframework.http.HttpMethod;
import org.springframework.security.config.annotation.web.builders.HttpSecurity;
import org.springframework.security.config.annotation.web.configuration.EnableWebSecurity;
import org.springframework.security.config.annotation.web.configuration.WebSecurityConfigurerAdapter;
@@ -14,19 +14,21 @@ import org.springframework.security.web.authentication.UsernamePasswordAuthentic
@EnableWebSecurity
public class SecurityConfig extends WebSecurityConfigurerAdapter {
@Override
/*@Override
protected void configure(AuthenticationManagerBuilder auth) throws Exception {
auth.inMemoryAuthentication().
withUser("admin").password(passwordEncoder().encode("1234")).roles("ADMIN", "USER")
.and().
withUser("user").password(passwordEncoder().encode("1234")).roles("USER");
}
}*/
@Override
protected void configure(HttpSecurity http) throws Exception {
//super.configure(http);
http.csrf().disable();
http.sessionManagement().sessionCreationPolicy(SessionCreationPolicy.STATELESS);
http.authorizeRequests().antMatchers(HttpMethod.GET, "/categories/**").permitAll();
http.authorizeRequests().antMatchers(HttpMethod.GET, "/products/**").permitAll();
http.authorizeRequests().antMatchers("/categories/**").hasAuthority("ADMIN");
http.authorizeRequests().antMatchers("/products/**").hasAuthority("USER");
http.authorizeRequests().anyRequest().authenticated();

View File

@@ -0,0 +1,8 @@
package me.aski.catalogueservice.security;
public interface SecurityParams {
String HEADER_NAME = "Authorization";
String SECRET = "abdellah@aski.me";
long EXPIRATION = 10 * 24 * 3600;
String PREFIX = "Bearer ";
}

View File

@@ -0,0 +1,75 @@
package me.aski.catalogueservice.web;
import lombok.Data;
import lombok.ToString;
import me.aski.catalogueservice.dao.CategoryRepository;
import me.aski.catalogueservice.dao.ProductRepository;
import me.aski.catalogueservice.entities.Category;
import me.aski.catalogueservice.entities.Product;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.PutMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RestController;
@RestController
public class ProductController {
@Autowired
private CategoryRepository categoryRepository;
@Autowired
private ProductRepository productRepository;
@PostMapping("/customProducts")
public ResponseEntity<?> postProduct(@RequestBody ProductForm form) {
form.setCategory(form.getCategory().split("/")[form.getCategory().split("/").length - 1]);
Category c = categoryRepository.findById(form.getCategory()).get();
Product p = productRepository.save(new Product(null, form.getName(), form.getPrice(), c));
c.getProducts().add(p);
categoryRepository.save(c);
return new ResponseEntity<>(HttpStatus.OK);
}
@PutMapping("/customProducts")
public ResponseEntity<?> putProduct(@RequestBody ProductForm form) {
form.setCategory(form.getCategory().split("/")[form.getCategory().split("/").length - 1]);
form.setId(form.getId().split("/")[form.getId().split("/").length - 1]);
Product product = productRepository.findById(form.getId()).get();
Category oldCategory = product.getCategory();
oldCategory.getProducts().remove(product);
categoryRepository.save(oldCategory);
Category newCategory = categoryRepository.findById(form.getCategory()).get();
product.setName(form.getName());
product.setCategory(newCategory);
product.setPrice(form.getPrice());
productRepository.save(product);
newCategory.getProducts().add(product);
categoryRepository.save(newCategory);
return new ResponseEntity<>(HttpStatus.OK);
}
}
@Data
@ToString
class ProductForm {
private String id;
private String name;
private double price;
private String category;
}

View File

@@ -1 +1,2 @@
server.port=8081
spring.data.mongodb.uri=mongodb://localhost:27017/CatalogueService