Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

George hatzigeorgio #20

Open
wants to merge 4 commits into
base: master
Choose a base branch
from
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
14 changes: 14 additions & 0 deletions shoppingcart/pom.xml
Original file line number Diff line number Diff line change
Expand Up @@ -35,6 +35,20 @@
<scope>runtime</scope>
<optional>true</optional>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-security</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.security</groupId>
<artifactId>spring-security-test</artifactId>
<scope>test</scope>
</dependency>
<dependency>
<groupId>org.springframework.security.oauth</groupId>
<artifactId>spring-security-oauth2</artifactId>
<version>2.3.6.RELEASE</version>
</dependency>

<dependency>
<groupId>com.h2database</groupId>
Expand Down
Original file line number Diff line number Diff line change
@@ -0,0 +1,56 @@
package com.lambdaschool.shoppingcart.config;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Configuration;
import org.springframework.security.authentication.AuthenticationManager;
import org.springframework.security.crypto.password.PasswordEncoder;
import org.springframework.security.oauth2.config.annotation.configurers.ClientDetailsServiceConfigurer;
import org.springframework.security.oauth2.config.annotation.web.configuration.AuthorizationServerConfigurerAdapter;
import org.springframework.security.oauth2.config.annotation.web.configuration.EnableAuthorizationServer;
import org.springframework.security.oauth2.config.annotation.web.configurers.AuthorizationServerEndpointsConfigurer;
import org.springframework.security.oauth2.provider.token.TokenStore;

@Configuration
@EnableAuthorizationServer
public class AuthorizationServerConfig extends AuthorizationServerConfigurerAdapter {

private static final String CLIENT_ID = System.getenv("OAUTHCLIENTID");
private static final String CLIENT_SECRET= System.getenv("OAUTHCLIENTSECRET");

static final String GRANT_TYPE_PASSWORD = "password";
static final String AUTHORIZATION_CODE = "authorization_code";

static final String SCOPE_READ = "read";
static final String SCOPE_WRITE = "write";
static final String SCOPE_TRUST = "trust";

static final int ACCESS_TOKEN_VALIDITY_SECONDS = -1;

@Autowired
private TokenStore tokenStore;

@Autowired
private AuthenticationManager authenticationManager;

@Autowired
private PasswordEncoder passwordEncoder;

@Override
public void configure(AuthorizationServerEndpointsConfigurer endpoints) throws Exception {
endpoints.tokenStore(tokenStore)
.authenticationManager(authenticationManager);
endpoints.pathMapping("/oauth/token","/login");
}

@Override
public void configure(ClientDetailsServiceConfigurer clients) throws Exception {
clients.inMemory()
.withClient(CLIENT_ID)
.secret(passwordEncoder.encode(CLIENT_SECRET))
.authorizedGrantTypes(GRANT_TYPE_PASSWORD,AUTHORIZATION_CODE)
.scopes(SCOPE_READ,SCOPE_TRUST,SCOPE_WRITE)
.accessTokenValiditySeconds(ACCESS_TOKEN_VALIDITY_SECONDS);


}
}
Original file line number Diff line number Diff line change
@@ -0,0 +1,45 @@
package com.lambdaschool.shoppingcart.config;

import org.springframework.context.annotation.Configuration;
import org.springframework.security.config.annotation.web.builders.HttpSecurity;
import org.springframework.security.oauth2.config.annotation.web.configuration.EnableResourceServer;
import org.springframework.security.oauth2.config.annotation.web.configuration.ResourceServerConfigurerAdapter;
import org.springframework.security.oauth2.config.annotation.web.configurers.ResourceServerSecurityConfigurer;
import org.springframework.security.oauth2.provider.error.OAuth2AccessDeniedHandler;

@Configuration
@EnableResourceServer
public class ResourceServerConfig extends ResourceServerConfigurerAdapter {
private static final String RESOURCE_ID ="resource_id";

@Override
public void configure(ResourceServerSecurityConfigurer resources) throws Exception {
resources.resourceId(RESOURCE_ID)
.stateless(false);
}

@Override
public void configure(HttpSecurity http) throws Exception {
http.authorizeRequests()
.antMatchers("/", "/h2-console/**",
"/swagger-resources/**",
"/swagger-resource/**",
"/swagger-ui.html",
"/v2/api-docs",
"/webjars/**",
"/createnewuser")
.permitAll()
.antMatchers("/roles/**","/products/**","/users/**")
.hasAnyRole("ADMIN")
.antMatchers("/carts/**")
.authenticated()
.and()
.exceptionHandling()
.accessDeniedHandler(new OAuth2AccessDeniedHandler());

http.csrf().disable();
http.headers().frameOptions().disable();
http.logout().disable();

}
}
Original file line number Diff line number Diff line change
@@ -0,0 +1,46 @@
package com.lambdaschool.shoppingcart.config;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.security.authentication.AuthenticationManager;
import org.springframework.security.config.annotation.authentication.builders.AuthenticationManagerBuilder;
import org.springframework.security.config.annotation.method.configuration.EnableGlobalMethodSecurity;
import org.springframework.security.config.annotation.web.configuration.EnableWebSecurity;
import org.springframework.security.config.annotation.web.configuration.WebSecurityConfigurerAdapter;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder;
import org.springframework.security.crypto.password.PasswordEncoder;
import org.springframework.security.oauth2.provider.token.TokenStore;
import org.springframework.security.oauth2.provider.token.store.InMemoryTokenStore;


@Configuration
@EnableWebSecurity
@EnableGlobalMethodSecurity(prePostEnabled = true)
public class SecurityServiceConfig extends WebSecurityConfigurerAdapter {

@Override
@Bean
public AuthenticationManager authenticationManagerBean()throws Exception{
return super.authenticationManagerBean();
}
@Bean
public TokenStore tokenStore(){
return new InMemoryTokenStore();
}

@Bean
public PasswordEncoder passwordEncoder(){
return new BCryptPasswordEncoder();
}
@Autowired
private UserDetailsService securityUserDetails;


@Autowired
public void globalUserDetails(AuthenticationManagerBuilder auth) throws Exception {
auth.userDetailsService(securityUserDetails)
.passwordEncoder(passwordEncoder());
}
}
Original file line number Diff line number Diff line change
@@ -0,0 +1,52 @@
package com.lambdaschool.shoppingcart.config;

import org.springframework.core.Ordered;
import org.springframework.core.annotation.Order;
import org.springframework.http.HttpMethod;

import javax.servlet.*;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
@Order(Ordered.HIGHEST_PRECEDENCE)
public class SimpleCorsFilter implements Filter {
@Override
public void doFilter(
ServletRequest servletRequest,
ServletResponse servletResponse,
FilterChain filterChain)
throws
IOException,
ServletException
{
// Convert our request and response to Http ones. If they are not Http ones, an exception would be thrown
// that would handled by our exception handler!
HttpServletResponse response = (HttpServletResponse) servletResponse;
HttpServletRequest request = (HttpServletRequest) servletRequest;
// white list domains that can access this API. * says let everyone access it. To restrict access use something like
// response.setHeader("Access-Control-Allow-Origin",
// "https://lambdaschool.com/");
response.setHeader("Access-Control-Allow-Origin",
"*");
// white list http methods that can be used with this API. * says lets them all work! To restrict access use something like
// response.setHeader("Access-Control-Allow-Methods", "POST, PUT, GET, OPTIONS, DELETE");
response.setHeader("Access-Control-Allow-Methods",
"*");
// while list access headers that can be used with this API. * says lets them all work! To restrict access use something like
// response.setHeader("Access-Control-Allow-Headers", "x-requested-with, authorization, content-type, access_token");
response.setHeader("Access-Control-Allow-Headers",
"*");
// maximum seconds results can be cached
response.setHeader("Access-Control-Max-Age",
"3600");
if (HttpMethod.OPTIONS.name()
.equalsIgnoreCase(request.getMethod()))
{
response.setStatus(HttpServletResponse.SC_OK);
} else
{
filterChain.doFilter(servletRequest,
servletResponse);
}
}
}
Original file line number Diff line number Diff line change
Expand Up @@ -5,8 +5,11 @@
import com.lambdaschool.shoppingcart.services.CartItemService;
import com.lambdaschool.shoppingcart.services.UserService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.web.bind.annotation.*;

@RestController
Expand All @@ -16,21 +19,24 @@ public class CartController
@Autowired
private CartItemService cartItemService;


@Autowired
private UserService userService;

@GetMapping(value = "/user/{userid}",
@GetMapping(value = "/user/products",
produces = {"application/json"})
public ResponseEntity<?> listCartItemsByUserId(
@PathVariable
long userid)
public ResponseEntity<?> listCartItemsByUserId()
{
User u = userService.findUserById(userid);
return new ResponseEntity<>(u,
String uname = SecurityContextHolder.getContext().getAuthentication().getName();

User user = userService.findByName(uname);


return new ResponseEntity<>(user,
HttpStatus.OK);
}

@PutMapping(value = "/add/user/{userid}/product/{productid}",
@PutMapping(value = "/add/user/product/{productid}",
produces = {"application/json"})
public ResponseEntity<?> addToCart(
@PathVariable
Expand All @@ -45,7 +51,7 @@ public ResponseEntity<?> addToCart(
HttpStatus.OK);
}

@DeleteMapping(value = "/remove/user/{userid}/product/{productid}",
@DeleteMapping(value = "/remove/user/product/{productid}",
produces = {"application/json"})
public ResponseEntity<?> removeFromCart(
@PathVariable
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -6,6 +6,7 @@
import org.springframework.http.HttpHeaders;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.servlet.support.ServletUriComponentsBuilder;

Expand Down Expand Up @@ -51,13 +52,13 @@ public ResponseEntity<?> listAllUsers()
* @return JSON object of the user you seek
* @see UserService#findUserById(long) UserService.findUserById(long)
*/
@GetMapping(value = "/user/{userId}",
@GetMapping(value = "/user"
produces = "application/json")
public ResponseEntity<?> getUserById(
@PathVariable
Long userId)
public ResponseEntity<?> getUserById()
{
User u = userService.findUserById(userId);
String uname = SecurityContextHolder.getContext().getAuthentication().getName();

User u = userService.findByName(uname);
return new ResponseEntity<>(u,
HttpStatus.OK);
}
Expand Down Expand Up @@ -148,7 +149,7 @@ public ResponseEntity<?> addNewUser(
* @return status of OK
* @see UserService#save(User) UserService.save(User)
*/
@PutMapping(value = "/user/{userid}",
@PutMapping(value = "/user",
consumes = "application/json")
public ResponseEntity<?> updateFullUser(
@Valid
Expand Down
Original file line number Diff line number Diff line change
@@ -1,12 +1,14 @@
package com.lambdaschool.shoppingcart.models;

import com.fasterxml.jackson.annotation.JsonIgnore;
import com.fasterxml.jackson.annotation.JsonIgnoreProperties;
import com.fasterxml.jackson.annotation.JsonProperty;
import org.springframework.security.core.authority.SimpleGrantedAuthority;
import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder;

import javax.persistence.*;
import javax.validation.constraints.Email;
import java.util.HashSet;
import java.util.Set;
import java.util.*;

/**
* The entity allowing interaction with the users table
Expand Down Expand Up @@ -122,12 +124,17 @@ public String getUsername()
{
return username;
}
public void setPassword(String password)
{
BCryptPasswordEncoder passwordEncoder = new BCryptPasswordEncoder();
this.password = passwordEncoder.encode(password);
}

public void setPasswordNoEncrypt(String password)
{
this.password = password;
}

/**
* setter for username
*
* @param username the new username (String) converted to lowercase
*/
public void setUsername(String username)
{
this.username = username.toLowerCase();
Expand Down Expand Up @@ -168,10 +175,6 @@ public String getPassword()
*
* @param password the new password (String) for the user
*/
public void setPassword(String password)
{
this.password = password;
}

/**
* Getter for user role combinations
Expand Down Expand Up @@ -212,4 +215,14 @@ public void setCarts(Set<CartItem> carts)
{
this.carts = carts;
}

@JsonIgnore
public List<SimpleGrantedAuthority> getAuthority(){
List<SimpleGrantedAuthority> rtnList = new ArrayList<>();
for (UserRoles ur: this.roles){
String myRole = "ROLE_" + ur.getRole().getName().toUpperCase();
rtnList.add(new SimpleGrantedAuthority(myRole));
}
return rtnList;
}
}
Loading