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 #17

Open
wants to merge 3 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
15 changes: 14 additions & 1 deletion shoppingcart/pom.xml
Original file line number Diff line number Diff line change
Expand Up @@ -41,7 +41,20 @@
<artifactId>h2</artifactId>
<!-- <scope>runtime</scope>-->
</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>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-test</artifactId>
Expand Down
Original file line number Diff line number Diff line change
@@ -0,0 +1,59 @@
package com.lambdaschool.shoppingcart.config;

import com.sun.xml.bind.v2.model.core.ID;
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.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.AuthorizationServerEndpointsConfiguration;
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 {

@Autowired
private TokenStore tokenStore;
@Autowired
private AuthenticationManager authenticationManager;

@Autowired

private PasswordEncoder encoder;


private String CLIENT_ID = System.getenv("OAUTHCLIENTID");

private String CLIENT_SECRET = System.getenv("OAUTHCLIENTSECRET");


private String GRANT_TYPE_PASSWORD = "password";
private String AUTHORIZATION_CODE = "authorization_code";
private String SCOPE_READ = "read";
private String SCOPE_WRITE = "write";
private String SCOPE_TRUST = "trust";

private final int ACCESS_TOKEN_VALIDILITY_SECONDS = -1;


@Override
public void configure(ClientDetailsServiceConfigurer configurer) throws Exception{
configurer.inMemory().secret(encoder.encode(CLIENT_SECRET))
.authroizedGrantTypes(GRANT_TYPE_PASSWORD,AUTHORIZATION_CODE)
.scopes(SCOPE_READ,SCOPE_TRUST, SCOPE_WRITE)
.accessTodenValiditySeconds(ACCESS_TOKEN_VALIDILITY_SECONDS);
}
@Override
public void configure (AuthorizationServerEndpointsConfigurer endpoints)
{
endpoints.tokenStore(tokenStore)
.authenticationManager(authenticationManager);
endpoints.pathMapping("/oauth/token", "/login");
}

}
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 ResourceConfiguration 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("/carts/**").permitAll()
.antMatchers("/roles/**").hasAnyRole("Admin")
.antMatchers("/products/**").hasAnyRole("Admin")
.and()
.exceptionHandling()
.accessDeniedHandler(new OAuth2AccessDeniedHandler());

http.csrf().disable();

http.headers().frameOptions().disable();
}
}
Original file line number Diff line number Diff line change
@@ -0,0 +1,48 @@
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.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;

@Configuration
@EnableWebSecurity
@EnableGlobalMethodSecurity(prePostEnabled = true)
public class SecurityConfig extends WebSecurityConfigurerAdapter {
@Override
@Bean
AuthenticationManager authenticationManager() throws Exception
{
return super.authenticationManagerBean();
}

@Autowired
private UserDetailsService securityUserService;

@Autowired
public void globalUserDetails(AuthenticationManagerBuilder auth) throws Exception
throws
exception
{
auth.UserDetailsService(securityUserService)
} .passwordEncoder(encoder());

@Bean
public TokenStore tokenStore()
{
return new inMemoryTokenStore();


}
@Bean
{ public PasswordEncoder encoder()
return new BcryptPasswordEncoder();

}



Original file line number Diff line number Diff line change
@@ -0,0 +1,29 @@
package com.lambdaschool.shoppingcart.controllers;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.security.oauth2.common.OAuth2AccessToken;
import org.springframework.security.oauth2.provider.token.TokenStore;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RestController;

import javax.servlet.http.HttpServletRequest;

@RestController
public class LogoutController {
@Autowired
private TokenStore tokenStore;

@GetMapping(value = {"/oath/revoke-token", "logout",}, produces = "application/json")
public ResponseEntity<?> logoutSelf(HttpServletRequest request)
{
String authHeader = request.getHeader("Authorization");
if (authHeader != null)
{
String TokenValue = authHeader.replace("Bearer", "").trim();
}
OAuth2AccessToken accessToken = TokenStore.readAccessToken(tokenValue)
tokenStore.removeAccessToken(accessToken);
} return new ResponseEntity <> (HttpStatus.OK)
}
Original file line number Diff line number Diff line change
Expand Up @@ -2,10 +2,14 @@

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.ArrayList;
import java.util.HashSet;
import java.util.List;
import java.util.Set;

/**
Expand Down Expand Up @@ -160,7 +164,8 @@ public void setPrimaryemail(String primaryemail)
*/
public String getPassword()
{
return password;
BCryptPasswordEncoder passwordEncoder = new BCryptPasswordEncoder();
this.password = passwordEncoder.ecode(password)
}

/**
Expand Down Expand Up @@ -212,4 +217,17 @@ public void setCarts(Set<CartItem> carts)
{
this.carts = carts;
}

public List <SimpleGrantedAuthority> getAuthority()
{
List<SimpleGrantedAuthority> rtnlist = new ArrayList<>();

for UserRoles r : this.roles)


{
String myRole ="ROLE" + r.getRole().getName().toUpperCase();
rtnlist.add(new SimpleGrantedAuthority(myrole));
}
}
}
Original file line number Diff line number Diff line change
@@ -0,0 +1,27 @@
package com.lambdaschool.shoppingcart.services;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.core.userdetails.UsernameNotFoundException;
import org.springframework.stereotype.Service;

import java.util.Locale;

@Service(value = "securityUserService")
public class SecurityUserServiceImp implements UserDetailsService {

@Autowired
private UserRepository userRepos;
@Override
public UserDetails loadUserByUsername(String s) throws ResourceNotFoundException {

user user = userRepos.findByUsername(s.toLowerCase();
if (user == null){

throw new ResourceNotFoundException("invalid username or password")
}
return org.springframework.security.core.userdetails.User(user.getUsername()
user.getPassword(), user.getAuthority());
}
}
Original file line number Diff line number Diff line change
@@ -1,6 +1,8 @@
package com.lambdaschool.shoppingcart.services;

import org.springframework.data.domain.AuditorAware;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.stereotype.Component;

import java.util.Optional;
Expand All @@ -22,7 +24,12 @@ public class UserAuditing
public Optional<String> getCurrentAuditor()
{
String uname;
uname = "SYSTEM";
return Optional.of(uname);
Authentication authentication = SecurityContextHolder.getContext().getAuthentication();
if (authentication != null){
uname=authentication.getName();
else
} uname = "SYSTEM";

} return Optional.of(uname);
}
}
Original file line number Diff line number Diff line change
Expand Up @@ -79,4 +79,7 @@ User update(
* Deletes all record and their associated records from the database
*/
public void deleteAll();



}
Loading