Skip to content

mv #5

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

Open
wants to merge 1 commit into
base: master
Choose a base branch
from
Open

mv #5

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
44 changes: 43 additions & 1 deletion shoppingcart/pom.xml
Original file line number Diff line number Diff line change
Expand Up @@ -5,7 +5,7 @@
<parent>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-parent</artifactId>
<version>2.2.8.RELEASE</version>
<version>2.2.9.RELEASE</version>
<relativePath/> <!-- lookup parent from repository -->
</parent>
<groupId>com.lambdaschool</groupId>
Expand Down Expand Up @@ -63,7 +63,49 @@
<artifactId>javafaker</artifactId>
<version>1.0.1</version>
</dependency>
<dependency>
<groupId>org.springframework.security.oauth</groupId>
<artifactId>spring-security-oauth2</artifactId>
<version>2.3.6.RELEASE</version>
</dependency>
<dependency>
<groupId>io.springfox</groupId>
<artifactId>springfox-bean-validators</artifactId>
<version>2.9.2</version>
</dependency>
<dependency>
<groupId>io.springfox</groupId>
<artifactId>springfox-core</artifactId>
<version>2.9.2</version>
</dependency>
<dependency>
<groupId>io.springfox</groupId>
<artifactId>springfox-spring-web</artifactId>
<version>2.9.2</version>
</dependency>
<dependency>
<groupId>io.springfox</groupId>
<artifactId>springfox-swagger2</artifactId>
<version>2.9.2</version>
</dependency>
</dependencies>
<!--SECURITY DEPENDENCIES-->
<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>

<build>
<plugins>
Expand Down
Original file line number Diff line number Diff line change
@@ -0,0 +1,51 @@
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{

//user pass
static final String CLIENT_ID = "lambda-id";
static final String CLIENT_SECRET = "lambda-secret";
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 encoder;

@Override
public void configure(ClientDetailsServiceConfigurer clients) throws Exception {

clients.inMemory().withClient(CLIENT_ID).secret(encoder.encode(CLIENT_SECRET)).authorizedGrantTypes(GRANT_TYPE_PASSWORD,AUTHORIZATION_CODE)
.scopes(SCOPE_READ,SCOPE_WRITE,SCOPE_TRUST)
.accessTokenValiditySeconds(ACCESS_TOKEN_VALIDITY_SECONDS);
}

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

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

import com.zaxxer.hikari.HikariConfig;
import com.zaxxer.hikari.HikariDataSource;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.boot.jdbc.DataSourceBuilder;
import org.springframework.context.ApplicationContext;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.core.env.Environment;

import javax.sql.DataSource;

@Configuration
public class DataSourceConfig
{
@Autowired
private ApplicationContext appContext;

@Autowired
private Environment env;

@Value("${spring.data.source.url}")
private String dbUrl;

@Bean
public DataSource dataSource()
{
String dbValue = env.getProperty("local.run.db");

if (dbValue.equalsIgnoreCase("POSTGRESQL"))
{
HikariConfig config = new HikariConfig();
config.setJdbcUrl(dbUrl);
return new HikariDataSource(config);
} else
{
return DataSourceBuilder.create()
.username("sa")
.password("")
.url("jdbc:h2:mem:testdb")
.driverClassName("org.h2.Driver")
.build();
}

}
}
Original file line number Diff line number Diff line change
@@ -0,0 +1,40 @@
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){

resources.resourceId(RESOURCE_ID).stateless(false);
}

@Override
public void configure(HttpSecurity http) throws Exception{
http.csrf().disable();
//for h2 console to work
http.headers().frameOptions().disable();
http.logout().disable();

//** means everything after that
http.authorizeRequests().antMatchers("/","/h2-console/**","/swagger" +
"-resources/**","/swagger-resource/**","/swagger-ui.html",
"/v2/api-docs","/webjars/**","/createnewuser","/user").permitAll()
.antMatchers("/logout").authenticated()
.antMatchers("/users/**").hasAnyRole("ADMIN","USER")
.antMatchers("/roles/**").hasAnyRole("ADMIN")
.and()
.exceptionHandling()
.accessDeniedHandler(new OAuth2AccessDeniedHandler());
}
}
Original file line number Diff line number Diff line change
@@ -0,0 +1,50 @@
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;

import javax.annotation.Resource;

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

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

@Resource(name = "securityUserService")
private UserDetailsService userDetailsService;

@Autowired
public void globalUserDetails(AuthenticationManagerBuilder auth) throws Exception{
// ties authentication to userdetails service
auth.userDetailsService(userDetailsService).passwordEncoder(encoder());
}

@Bean
public PasswordEncoder encoder(){

return new BCryptPasswordEncoder();
}

@Bean
public TokenStore tokenStore(){
return new InMemoryTokenStore();
}

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

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

import javax.servlet.FilterChain;
import javax.servlet.ServletException;
import javax.servlet.ServletRequest;
import javax.servlet.ServletResponse;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.util.logging.Filter;
import java.util.logging.LogRecord;

@Component
@Order(Ordered.HIGHEST_PRECEDENCE)
public class SimpleCorsFilter implements Filter {
@Override
public boolean isLoggable(LogRecord record) {
return true;
}

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
@@ -0,0 +1,55 @@
package com.lambdaschool.shoppingcart.config;

import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.context.annotation.Import;
import springfox.bean.validators.configuration.BeanValidatorPluginsConfiguration;
import springfox.documentation.builders.ApiInfoBuilder;
import springfox.documentation.builders.PathSelectors;
import springfox.documentation.builders.RequestHandlerSelectors;
import springfox.documentation.service.ApiInfo;
import springfox.documentation.service.Contact;
import springfox.documentation.spi.DocumentationType;
import springfox.documentation.spring.web.plugins.Docket;
import springfox.documentation.swagger2.annotations.EnableSwagger2;

@Configuration
@EnableSwagger2
@Import(BeanValidatorPluginsConfiguration.class)
public class Swagger2Config
{
/**
* Configures what to document using Swagger
*
* @return A Docket which is the primary interface for Swagger configuration
*/
@Bean
public Docket api()
{
return new Docket(DocumentationType.SWAGGER_2)
.select()
.apis(RequestHandlerSelectors
.basePackage("com.lambdaschool.usermodel"))
.paths(PathSelectors.regex("/.*"))
.build()
.apiInfo(apiEndPointsInfo());
}

/**
* Configures some information related to the Application for Swagger
*
* @return ApiInfo a Swagger object containing identification information for this application
*/
private ApiInfo apiEndPointsInfo()
{
return new ApiInfoBuilder().title("User Model Example")
.description("User Model Example")
.contact(new Contact("John Mitchell",
"http://www.lambdaschool.com",
"[email protected]"))
.license("MIT")
.licenseUrl("https://github.com/LambdaSchool/java-usermodel/blob/master/LICENSE")
.version("1.0.0")
.build();
}
}
Loading