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

Cerberus #1

Open
wants to merge 5 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
8 changes: 3 additions & 5 deletions build.gradle
Original file line number Diff line number Diff line change
Expand Up @@ -52,11 +52,9 @@ repositories {

dependencies {
compile('org.springframework.boot:spring-boot-starter-actuator')

//compile('org.springframework.boot:spring-boot-starter-security')
//compile("org.springframework.security.oauth:spring-security-oauth2:2.0.6.RELEASE")
//compile("org.springframework.cloud:spring-cloud-starter-security:1.0.0.RELEASE")

compile('org.springframework.boot:spring-boot-starter-security')
compile('org.springframework.mobile:spring-mobile-device')
compile('io.jsonwebtoken:jjwt:0.6.0')
compile('org.springframework.cloud:spring-cloud-starter-eureka')
compile('org.springframework.boot:spring-boot-starter-amqp')
compile('org.springframework.boot:spring-boot-starter-data-rest')
Expand Down
32 changes: 0 additions & 32 deletions src/main/java/company/tothepoint/BeheerApplication.java
Original file line number Diff line number Diff line change
Expand Up @@ -43,29 +43,6 @@ Queue queue() {
return new Queue(BEHEER_QUEUE, true, false, false);
}

// @EnableAuthorizationServer
// protected static class OAuth2Config extends AuthorizationServerConfigurerAdapter {
// @Autowired
// private AuthenticationManager authenticationManager;
//
// @Override
// public void configure(AuthorizationServerEndpointsConfigurer endpoints) throws Exception {
// endpoints.authenticationManager(authenticationManager);
// }
//
// @Override
// public void configure(ClientDetailsServiceConfigurer clients)
// throws Exception {
// clients.inMemory()
// .withClient("acme")
// .secret("acmesecret")
// .authorizedGrantTypes("authorization_code","implicit",
// "refresh_token", "password").scopes("openid");
//
// }
// }



@Bean
Jackson2JsonMessageConverter jackson2JsonMessageConverter(ObjectMapper objectMapper) {
Expand All @@ -79,15 +56,6 @@ TopicExchange beheerTopicExchange() {
return new TopicExchange(BEHEER_EXCHANGE, true, false);
}

// @Bean
// TopicExchange businessUnitTopicExchange() {
// return new TopicExchange(BUSINESSUNIT_EXCHANGE, true, false);
// }

// @Bean
// Binding businessUnitBinding(Queue queue, TopicExchange businessUnitTopicExchange) {
// return BindingBuilder.bind(queue).to(businessUnitTopicExchange).with(BUSINESSUNIT_ROUTING);
// }
@Bean
Binding beheerBinding(Queue queue, TopicExchange beheerTopicExchange) {
return BindingBuilder.bind(queue).to(beheerTopicExchange).with(BEHEER_ROUTING);
Expand Down
23 changes: 23 additions & 0 deletions src/main/java/company/tothepoint/configuration/CORSFilter.java
Original file line number Diff line number Diff line change
@@ -0,0 +1,23 @@
package company.tothepoint.configuration;

import org.springframework.stereotype.Component;

import javax.servlet.*;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;

@Component
public class CORSFilter implements Filter {
public void doFilter(ServletRequest req, ServletResponse res, FilterChain chain) throws IOException, ServletException {
HttpServletResponse response = (HttpServletResponse) res;
response.setHeader("Access-Control-Allow-Origin", "*");
response.setHeader("Access-Control-Allow-Methods", "POST, GET, PUT, OPTIONS, DELETE");
response.setHeader("Access-Control-Max-Age", "3600");
response.setHeader("Access-Control-Allow-Headers", "Origin, X-Requested-With, Content-Type, Accept, Authorization");
chain.doFilter(req, res);
}

public voi init(FilterConfig filterConfig) {}

public void destroy() {}
}
Original file line number Diff line number Diff line change
@@ -0,0 +1,92 @@
package company.tothepoint.configuration;

import company.tothepoint.security.AuthenticationTokenFilter;
import company.tothepoint.security.EntryPointUnauthorizedHandler;
import company.tothepoint.service.SecurityService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.ComponentScan;
import org.springframework.context.annotation.Configuration;
import org.springframework.http.HttpMethod;
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.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.crypto.bcrypt.BCryptPasswordEncoder;
import org.springframework.security.crypto.password.PasswordEncoder;

import org.springframework.security.web.authentication.UsernamePasswordAuthenticationFilter;

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


@Autowired
private EntryPointUnauthorizedHandler unauthorizedHandler;


@Autowired
private UserDetailsService userDetailsService;

@Autowired
private SecurityService securityService;


@Autowired
public void configureAuthentication(AuthenticationManagerBuilder authenticationManagerBuilder) throws Exception {
authenticationManagerBuilder
.userDetailsService(this.userDetailsService)
.passwordEncoder(passwordEncoder());
}

@Bean
public PasswordEncoder passwordEncoder() {
return new BCryptPasswordEncoder();
}

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

@Bean
public AuthenticationTokenFilter authenticationTokenFilterBean() throws Exception {
AuthenticationTokenFilter authenticationTokenFilter = new AuthenticationTokenFilter();
authenticationTokenFilter.setAuthenticationManager(authenticationManagerBean());
return authenticationTokenFilter;
}

@Bean
public SecurityService securityService() {
return this.securityService;
}

@Override
protected void configure(HttpSecurity httpSecurity) throws Exception {
httpSecurity
.csrf()
.disable()
.exceptionHandling()
.authenticationEntryPoint(this.unauthorizedHandler)
.and()
.sessionManagement()
.sessionCreationPolicy(SessionCreationPolicy.STATELESS)
.and()
.authorizeRequests()
.antMatchers(HttpMethod.OPTIONS, "/**").permitAll()
.antMatchers("/auth/**").permitAll()
.anyRequest().authenticated();

// Custom JWT based authentication
httpSecurity
.addFilterBefore(authenticationTokenFilterBean(), UsernamePasswordAuthenticationFilter.class);
}
}
Original file line number Diff line number Diff line change
@@ -0,0 +1,74 @@
package company.tothepoint.controller;
import org.springframework.mobile.device.Device;
import company.tothepoint.model.AuthenticationRequest;
import company.tothepoint.model.AuthenticationResponse;
import company.tothepoint.model.CerberusUser;
import company.tothepoint.security.TokenUtils;
import org.apache.log4j.Logger;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.http.ResponseEntity;
import org.springframework.security.authentication.AuthenticationManager;
import org.springframework.security.authentication.UsernamePasswordAuthenticationToken;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.AuthenticationException;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RestController;

import javax.servlet.http.HttpServletRequest;

@RestController
@RequestMapping("/auth")
public class AuthenticationController {

private final Logger logger = Logger.getLogger(AuthenticationController.class);

@Value("${beheerder-service.token.header}")
private String tokenHeader;

@Autowired
private AuthenticationManager authenticationManager;

@Autowired
private TokenUtils tokenUtils;

@Autowired
private UserDetailsService userDetailsService;

@RequestMapping(method = RequestMethod.POST)
public ResponseEntity<?> authenticationRequest(@RequestBody AuthenticationRequest authenticationRequest, Device device) throws AuthenticationException {
logger.error("In POST REQUEST");
logger.error(authenticationRequest.getUsername());
logger.error(authenticationRequest.getPassword());
Authentication authentication = this.authenticationManager.authenticate(
new UsernamePasswordAuthenticationToken(
authenticationRequest.getUsername(),
authenticationRequest.getPassword()
)
);

SecurityContextHolder.getContext().setAuthentication(authentication);
// Reload password post-authentication so we can generate token
UserDetails userDetails = this.userDetailsService.loadUserByUsername(authenticationRequest.getUsername());
String token = this.tokenUtils.generateToken(userDetails, device);
return ResponseEntity.ok(new AuthenticationResponse(token));
}

@RequestMapping(value = "/refresh", method = RequestMethod.GET)
public ResponseEntity<?> authenticationRequest(HttpServletRequest request) {
String token = request.getHeader(this.tokenHeader);
String username = this.tokenUtils.getUsernameFromToken(token);
CerberusUser user = (CerberusUser) this.userDetailsService.loadUserByUsername(username);
if (this.tokenUtils.canTokenBeRefreshed(token, user.getLastPasswordReset())) {
String refreshedToken = this.tokenUtils.refreshToken(token);
return ResponseEntity.ok(new AuthenticationResponse(refreshedToken));
} else {
return ResponseEntity.badRequest().body(null);
}
}
}
Original file line number Diff line number Diff line change
Expand Up @@ -12,8 +12,6 @@
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.*;

//import java.security.Principal;
import java.security.Principal;
import java.util.List;
import java.util.Optional;

Expand Down
Original file line number Diff line number Diff line change
@@ -0,0 +1,29 @@
package company.tothepoint.controller;

import org.springframework.http.ResponseEntity;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RestController;

/**
* Created by butrint on 9/05/16.
*/
@RestController
@RequestMapping("/protected")
public class ProtectedController {

/**
This is an example of some different kinds of granular restriction for endpoints. You can use the built-in SPEL expressions
in @PreAuthorize such as 'hasRole()' to determine if a user has access. However, if you require logic beyond the methods
Spring provides then you can encapsulate it in a service and register it as a bean to use it within the annotation as
demonstrated below with 'securityService'.
**/
@RequestMapping(method = RequestMethod.GET)
//@PreAuthorize("hasRole('ADMIN')")
@PreAuthorize("@securityService.hasProtectedAccess()")
public ResponseEntity<?> getDaHoney() {
return ResponseEntity.ok(":O");
}

}
41 changes: 41 additions & 0 deletions src/main/java/company/tothepoint/controller/UserController.java
Original file line number Diff line number Diff line change
@@ -0,0 +1,41 @@
package company.tothepoint.controller;

import company.tothepoint.domain.User;
import company.tothepoint.repository.UserRepository;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.actuate.autoconfigure.ShellProperties;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RestController;

import java.util.List;

/**
* Created by butrint on 11/05/16.
*/
@RestController
@RequestMapping("/users")
public class UserController {
private static final Logger LOG = LoggerFactory.getLogger(UserController.class);

@Autowired
private UserRepository userRepository;
@RequestMapping(method = RequestMethod.GET)
public ResponseEntity<List<User>> getAllUsers() {
return new ResponseEntity<>(userRepository.findAll(), HttpStatus.OK);
}

@RequestMapping(method = RequestMethod.POST)
public ResponseEntity<User> createBeheerder(@RequestBody User user) {
LOG.debug("POST /users createUsers(..) called!");
User createdUser = userRepository.save(user);
return new ResponseEntity<>(createdUser, HttpStatus.CREATED);
}

}
15 changes: 15 additions & 0 deletions src/main/java/company/tothepoint/domain/DomainBase.java
Original file line number Diff line number Diff line change
@@ -0,0 +1,15 @@
package company.tothepoint.domain;

import org.apache.commons.lang.builder.ReflectionToStringBuilder;

import java.io.Serializable;

/**
* Created by butrint on 10/05/16.
*/
public class DomainBase implements Serializable {
@Override
public String toString() {
return ReflectionToStringBuilder.toString(this);
}
}
Loading