Skip to content

Commit

Permalink
oauth2 support for backend
Browse files Browse the repository at this point in the history
  • Loading branch information
pbougou committed Feb 20, 2018
1 parent 69e108d commit 6634951
Show file tree
Hide file tree
Showing 23 changed files with 400 additions and 69 deletions.
18 changes: 17 additions & 1 deletion backend/bin/application.properties
Original file line number Diff line number Diff line change
Expand Up @@ -9,13 +9,29 @@ spring.http.encoding.charset=UTF-8
spring.http.encoding.enabled=true
spring.http.encoding.force=true
spring.http.converters.preferred-json-mapper=jackson

# mondoDB
spring.data.mongodb.host=localhost
spring.data.mongodb.port=27017

# https support
server.port = 8443
security.require-ssl=true
server.ssl.key-store-type:PKCS12
server.ssl.key-store=classpath:keystore.p12
server.ssl.key-store-password=softeng
server.ssl.key-alias=tomcat
server.ssl.key-alias=tomcat

#oauth2 and jwt support
security.oauth2.resource.filter-order=3

security.signing-key=MaYzkSjmkzPC57L
security.encoding-strength=256
security.security-realm=Spring Boot JWT Example Realm

security.jwt.client-id=testjwtclientid
security.jwt.client-secret=XY7kmzoNzl100
security.jwt.grant-type=password
security.jwt.scope-read=read
security.jwt.scope-write=write
security.jwt.resource-ids=testjwtresourceid
Binary file not shown.
Binary file not shown.
Binary file not shown.
Binary file modified backend/bin/gr/ntua/ece/softeng/controllers/ParentController.class
Binary file not shown.
Binary file not shown.
Binary file added backend/bin/gr/ntua/ece/softeng/entities/Role.class
Binary file not shown.
Binary file not shown.
Binary file not shown.
Binary file not shown.
5 changes: 5 additions & 0 deletions backend/build.gradle
Original file line number Diff line number Diff line change
Expand Up @@ -36,6 +36,11 @@ dependencies {
compile 'org.springframework.boot:spring-boot-starter-data-jpa'
compile("org.springframework.boot:spring-boot-starter-data-mongodb")

compile('org.springframework.boot:spring-boot-starter-security')
compile('org.springframework.security.oauth:spring-security-oauth2')
compile('org.springframework.boot:spring-boot-starter-actuator')
compile('org.springframework.security:spring-security-jwt')

runtime('mysql:mysql-connector-java')
testCompile('org.springframework.boot:spring-boot-starter-test')
}
Expand Down
Original file line number Diff line number Diff line change
@@ -0,0 +1,68 @@
package gr.ntua.ece.softeng.config;
import java.util.Arrays;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.context.annotation.Configuration;
import org.springframework.security.authentication.AuthenticationManager;
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.TokenEnhancerChain;
import org.springframework.security.oauth2.provider.token.TokenStore;
import org.springframework.security.oauth2.provider.token.store.JwtAccessTokenConverter;

@Configuration
@EnableAuthorizationServer
public class AuthorizationServerConfig extends AuthorizationServerConfigurerAdapter {

@Value("${security.jwt.client-id}")
private String clientId;

@Value("${security.jwt.client-secret}")
private String clientSecret;

@Value("${security.jwt.grant-type}")
private String grantType;

@Value("${security.jwt.scope-read}")
private String scopeRead;

@Value("${security.jwt.scope-write}")
private String scopeWrite = "write";

@Value("${security.jwt.resource-ids}")
private String resourceIds;

@Autowired
private TokenStore tokenStore;

@Autowired
private JwtAccessTokenConverter accessTokenConverter;

@Autowired
private AuthenticationManager authenticationManager;

@Override
public void configure(ClientDetailsServiceConfigurer configurer) throws Exception {
configurer
.inMemory()
.withClient(clientId)
.secret(clientSecret)
.authorizedGrantTypes(grantType)
.scopes(scopeRead, scopeWrite)
.resourceIds(resourceIds);
}

@Override
public void configure(AuthorizationServerEndpointsConfigurer endpoints) throws Exception {
TokenEnhancerChain enhancerChain = new TokenEnhancerChain();
enhancerChain.setTokenEnhancers(Arrays.asList(accessTokenConverter));
endpoints.tokenStore(tokenStore)
.accessTokenConverter(accessTokenConverter)
.tokenEnhancer(enhancerChain)
.authenticationManager(authenticationManager);
}

}
Original file line number Diff line number Diff line change
@@ -0,0 +1,35 @@
package gr.ntua.ece.softeng.config;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
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.token.ResourceServerTokenServices;

@Configuration
@EnableResourceServer
public class ResourceServerConfig extends ResourceServerConfigurerAdapter {
@Autowired
private ResourceServerTokenServices tokenServices;

@Value("${security.jwt.resource-ids}")
private String resourceIds;

@Override
public void configure(ResourceServerSecurityConfigurer resources) throws Exception {
resources.resourceId(resourceIds).tokenServices(tokenServices);
}

@Override
public void configure(HttpSecurity http) throws Exception {
http
.requestMatchers()
.and()
.authorizeRequests()
.antMatchers("/actuator/**", "/api-docs/**").permitAll()
.antMatchers("/private/**" ).authenticated();
}
}
Original file line number Diff line number Diff line change
@@ -0,0 +1,85 @@
package gr.ntua.ece.softeng.config;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.context.annotation.Primary;
import org.springframework.security.authentication.AuthenticationManager;
import org.springframework.security.authentication.encoding.ShaPasswordEncoder;
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.builders.HttpSecurity;
import org.springframework.security.config.annotation.web.configuration.EnableWebSecurity;
import org.springframework.security.config.annotation.web.configuration.WebSecurityConfigurerAdapter;
import org.springframework.security.config.http.SessionCreationPolicy;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.oauth2.provider.token.DefaultTokenServices;
import org.springframework.security.oauth2.provider.token.TokenStore;
import org.springframework.security.oauth2.provider.token.store.JwtAccessTokenConverter;
import org.springframework.security.oauth2.provider.token.store.JwtTokenStore;

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

@Value("${security.signing-key}")
private String signingKey;

@Value("${security.encoding-strength}")
private Integer encodingStrength;

@Value("${security.security-realm}")
private String securityRealm;

@Autowired
private UserDetailsService userDetailsService;

@Bean
@Override
protected AuthenticationManager authenticationManager() throws Exception {
return super.authenticationManager();
}

@Override
protected void configure(AuthenticationManagerBuilder auth) throws Exception {
auth.userDetailsService(userDetailsService)
.passwordEncoder(new ShaPasswordEncoder(encodingStrength));
}

@Override
protected void configure(HttpSecurity http) throws Exception {
http
.sessionManagement()
.sessionCreationPolicy(SessionCreationPolicy.STATELESS)
.and()
.httpBasic()
.realmName(securityRealm)
.and()
.csrf()
.disable();

}

@Bean
public JwtAccessTokenConverter accessTokenConverter() {
JwtAccessTokenConverter converter = new JwtAccessTokenConverter();
converter.setSigningKey(signingKey);
return converter;
}

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

@Bean
@Primary //Making this primary to avoid any accidental duplication with another token service instance of the same name
public DefaultTokenServices tokenServices() {
DefaultTokenServices defaultTokenServices = new DefaultTokenServices();
defaultTokenServices.setTokenStore(tokenStore());
defaultTokenServices.setSupportRefreshToken(true);
return defaultTokenServices;
}
}
Original file line number Diff line number Diff line change
@@ -1,6 +1,6 @@
package gr.ntua.ece.softeng.controllers;

import java.util.HashSet;
import java.util.Arrays;
import java.util.List;
import java.util.Set;

Expand All @@ -11,60 +11,50 @@
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;

import gr.ntua.ece.softeng.entities.Event;
import gr.ntua.ece.softeng.entities.Parent;
import gr.ntua.ece.softeng.entities.Role;
import gr.ntua.ece.softeng.entities.User;
import gr.ntua.ece.softeng.repositories.ParentRepository;
import gr.ntua.ece.softeng.repositories.UserRepository;

@Controller // This means that this class is a Controller
@RequestMapping(path="/parents") // This means URL's start with /demo (after Application path)
@Controller
@RequestMapping(path="/parents")
public class ParentController {
@Autowired

@Autowired
private ParentRepository parentRepository;

@GetMapping(path="/add")
public @ResponseBody String addNewParent (@RequestParam String FirstName
, @RequestParam String LastName, @RequestParam String username, @RequestParam String password,
@RequestParam String email , @RequestParam String PhoneNumber, @RequestParam String DebitCard) {

Parent p = new Parent();
p.setFirstName(FirstName);
p.setLastName(LastName);
p.setUsername(username);
p.setPassword(password);
p.setEmail(email);
p.setPhoneNumber(PhoneNumber);
p.setDebitCard(DebitCard);
//p.setFpoints(null);
p.setEvents(new HashSet<>());
parentRepository.save(p);
return "Saved";
}
/*BUG FIX: POST to path*/

@Autowired
private UserRepository userRepository;

private final static String POST_PARENT_URL = "/addNewParent";

@PostMapping(POST_PARENT_URL)
public @ResponseBody String createParent(@RequestBody Parent parent) {

String username = parent.getUsername();
String password = parent.getPassword();
String sha256hex = org.apache.commons.codec.digest.DigestUtils.sha256Hex(password);

userRepository.save(new User(username, sha256hex, Arrays.asList(new Role("PARENT"))));

parent.setPassword(sha256hex);
parent.setFpoints(0);
System.out.println("Creat Parent: " + parent);
parentRepository.save(parent);
return "ok with post";

return "ok with post from parent";
}



@GetMapping(path="/{parent_username}/events")
public @ResponseBody Set<Event> findEvents (@PathVariable String parent_username) {
return parentRepository.findByUsername(parent_username).getEvents();
}


@GetMapping(path="/all")
public @ResponseBody List<Parent> getAllParents() {
// This returns a JSON or XML with the users
return parentRepository.findAll();
}

Expand Down
Loading

0 comments on commit 6634951

Please sign in to comment.