Skip to content

Commit

Permalink
Final Project Base version 2.0.0
Browse files Browse the repository at this point in the history
  • Loading branch information
mupezzuol committed Oct 8, 2019
1 parent fee0c10 commit 05514c3
Show file tree
Hide file tree
Showing 12 changed files with 80 additions and 107 deletions.
27 changes: 12 additions & 15 deletions pom.xml
Original file line number Diff line number Diff line change
Expand Up @@ -7,22 +7,23 @@
<parent>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-parent</artifactId>
<version>2.1.7.RELEASE</version>
<version>2.1.9.RELEASE</version>
<relativePath/> <!-- lookup parent from repository -->
</parent>


<!-- PROJECT -->
<groupId>com.oauth2</groupId>
<artifactId>project-example-springboot-oauth2-rbac</artifactId>
<version>1.0.0</version>
<version>2.0.0</version>
<name>project-example-springboot-oauth2-rbac</name>
<description>Project Example with Spring Boot and OAuth2 and RBAC.</description>


<!-- PROPERTIES -->
<properties>
<java.version>1.8</java.version>
<spring.oauth2.autoconfigure.version>2.1.9.RELEASE</spring.oauth2.autoconfigure.version>
</properties>


Expand All @@ -45,38 +46,34 @@
<dependency>
<groupId>org.springframework.security.oauth.boot</groupId>
<artifactId>spring-security-oauth2-autoconfigure</artifactId>
<version>2.1.7.RELEASE</version>
<version>${spring.oauth2.autoconfigure.version}</version>
</dependency>


<!-- Spring Data + JPA -->
<!-- Spring Data + JPA + BD -->
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-data-jpa</artifactId>
</dependency>

<!-- PostgreSQL -->
<dependency>
<groupId>org.postgresql</groupId>
<artifactId>postgresql</artifactId>
</dependency>



<!-- Spring Actuator - API monitoring -->
<!-- Spring Actuator + Swagger -->
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-actuator</artifactId>
</dependency>

<!-- Swagger/SpringFox - API documentation using Swagger -->
<dependency>
<groupId>io.springfox</groupId>
<artifactId>springfox-swagger2</artifactId>
<version>2.9.2</version>
</dependency>

<!-- Swagger/SpringFox - DashBoard ->> /swagger-ui.html -->
<dependency>
<groupId>io.springfox</groupId>
<artifactId>springfox-swagger-ui</artifactId>
Expand All @@ -99,17 +96,17 @@
<scope>runtime</scope>
</dependency>

<!-- Spring - Test - H2 - Database -->

<!-- Spring - Test + H2 -->
<dependency>
<groupId>com.h2database</groupId>
<artifactId>h2</artifactId>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-test</artifactId>
<scope>test</scope>
</dependency>

<!-- Spring - Test -->
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-test</artifactId>
<groupId>com.h2database</groupId>
<artifactId>h2</artifactId>
<scope>test</scope>
</dependency>

Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -23,7 +23,6 @@ public class WebSecurityConfig extends WebSecurityConfigurerAdapter {
"/**.html",
"/configuration/**"};


@Bean
@Override
public AuthenticationManager authenticationManagerBean() throws Exception {
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -24,10 +24,7 @@ public class CustomPermissionEvaluator implements PermissionEvaluator {

@Autowired
private IUserService userService;


//OR -> @PreAuthorize("hasPermission(returnObject, {'user_create', 'user_update', 'abcd_create', 'abcd_read', 'user_read'})")
//AND -> @PreAuthorize("hasPermission(returnObject, {'user_read'}) AND hasPermission(returnObject, {'user_update'})")
@Override
public boolean hasPermission(Authentication auth, Object targetDomainObject, Object permission) {

Expand All @@ -46,21 +43,17 @@ public boolean hasPermission(Authentication auth, Object targetDomainObject, Obj
log.info("Permission Invalid for this method");
return false;
}

} catch (Exception e) {
log.error("Error in method hasPermission in class CustomPermissionEvaluator: " + e.getMessage());
return false;
}
}


//@PreAuthorize("hasPermission(#id, 'Foo', 'read')")
@Override
public boolean hasPermission(Authentication auth, Serializable targetId, String targetType, Object permission) {
return true;
}


private List<String> validPermissions(Authentication auth, Object permission) {
log.info("Begin - validating user permission in method validPermissions in class CustomPermissionEvaluator");

Expand Down Expand Up @@ -91,3 +84,10 @@ private List<String> validPermissions(Authentication auth, Object permission) {
}

}

/*
Exemplos:
OR -> @PreAuthorize("hasPermission(returnObject, {'user_create', 'user_update', 'abcd_create', 'abcd_read', 'user_read'})")
AND -> @PreAuthorize("hasPermission(returnObject, {'user_read'}) AND hasPermission(returnObject, {'user_update'})")
@PreAuthorize("hasPermission(#id, 'Foo', 'read')")
*/
2 changes: 1 addition & 1 deletion src/main/java/com/oauth2/config/errors/ApiError.java
Original file line number Diff line number Diff line change
Expand Up @@ -23,7 +23,6 @@ class ApiError {
private String debugMessage;
private String customMessage;


private ApiError() {
this.timestamp = LocalDateTime.now();
}
Expand Down Expand Up @@ -73,4 +72,5 @@ public String idFromValueAndType(Object value, Class<?> suggestedType) {
public JsonTypeInfo.Id getMechanism() {
return JsonTypeInfo.Id.CUSTOM;
}

}
Original file line number Diff line number Diff line change
Expand Up @@ -42,7 +42,6 @@ public Docket forumApi() {
.apiInfo(apiInfo());
}


private ApiInfo apiInfo() {
return new ApiInfoBuilder()
.title("Project Example OAuth2 RBAC - API")
Expand All @@ -54,13 +53,12 @@ private ApiInfo apiInfo() {
.build();
}


//Method that returns templates that will be hidden in the API documentation
@SuppressWarnings("rawtypes")
private Class[] disableTemplateClassesModels(){
ArrayList<Class> classForDisable = new ArrayList<Class>();

//Entities - Models - DTO and others....
//Entities - Models - DTO and others...
classForDisable.add(User.class);

return classForDisable.toArray(new Class[classForDisable.size()]);
Expand Down
58 changes: 58 additions & 0 deletions src/main/java/com/oauth2/controllers/AuthController.java
Original file line number Diff line number Diff line change
@@ -0,0 +1,58 @@
package com.oauth2.controllers;

import java.util.UUID;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.MediaType;
import org.springframework.http.ResponseEntity;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.security.core.userdetails.UsernameNotFoundException;
import org.springframework.web.bind.annotation.DeleteMapping;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import com.oauth2.entities.User;
import com.oauth2.models.dto.auth.AuthUserRoleAndAuthoritiesDTO;
import com.oauth2.services.IUserService;

import io.swagger.annotations.Api;
import lombok.extern.slf4j.Slf4j;

@RequestMapping("/auth")
@Api(tags="Authorities", description="This is about Authentication")
@RestController
@Slf4j
public class AuthController {

@Autowired
private IUserService userService;

@GetMapping(value = "/authorities/{uuid}", produces = MediaType.APPLICATION_JSON_VALUE)
public ResponseEntity<AuthUserRoleAndAuthoritiesDTO> getAuthorities(@PathVariable String uuid){
try {
UUID uuid_user = UUID.fromString(uuid.toString());

User user = userService.findByUuid(uuid_user)
.orElseThrow(() -> new UsernameNotFoundException("Error -> hasPermission for UUID: " + uuid_user));

return ResponseEntity.ok(new AuthUserRoleAndAuthoritiesDTO(user));
} catch (IllegalArgumentException ie) {
log.error("Error method getAuthorities in class AuthController: "+ie.getMessage());
return ResponseEntity.badRequest().build();//400
}
catch (Exception ex) {
log.error("Error method getAuthorities in class AuthController: "+ex.getMessage());
return ResponseEntity.badRequest().build();//400
}
}

@PreAuthorize("hasPermission(returnObject, {'user_create', 'user_update', 'abcd_create', 'abcd_read', 'user_read'})")
@DeleteMapping("/test")
public ResponseEntity<String> testAuthorities(){
System.out.print("I'm in the method!");
return ResponseEntity.ok(new String("OK -> Permission OK"));
}

}
46 changes: 1 addition & 45 deletions src/main/java/com/oauth2/controllers/HomeController.java
Original file line number Diff line number Diff line change
@@ -1,65 +1,21 @@
package com.oauth2.controllers;

import java.util.UUID;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.MediaType;
import org.springframework.http.ResponseEntity;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.security.core.userdetails.UsernameNotFoundException;
import org.springframework.web.bind.annotation.DeleteMapping;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.bind.annotation.RestController;

import com.oauth2.entities.User;
import com.oauth2.models.dto.auth.AuthUserRoleAndAuthoritiesDTO;
import com.oauth2.services.IUserService;

import io.swagger.annotations.Api;

@RequestMapping("/")
@Api(tags="Home - Test", description="Test Request")
@Api(tags="Home - Test", description="Unrestricted request testing")
@RestController
public class HomeController {

@Autowired
private IUserService userService;

@GetMapping()
@ResponseBody
public String home() {
return "Hello World - Welcome API REST";
}

@GetMapping(value = "authorities/{uuid}", produces = MediaType.APPLICATION_JSON_VALUE)
public ResponseEntity<AuthUserRoleAndAuthoritiesDTO> getAuthorities(@PathVariable String uuid){

try {
UUID uuid_user = UUID.fromString(uuid.toString());

User user = userService.findByUuid(uuid_user)
.orElseThrow(() -> new UsernameNotFoundException("Error -> hasPermission for UUID: " + uuid_user));

AuthUserRoleAndAuthoritiesDTO dto = new AuthUserRoleAndAuthoritiesDTO(user);

return ResponseEntity.ok(dto);
} catch (Exception e) {
return null;
}


}


@PreAuthorize("hasPermission(returnObject, {'user_create', 'user_update', 'abcd_create', 'abcd_read', 'user_read'})")
@DeleteMapping("/user")
public ResponseEntity<String> update(){
System.out.print("I'm in the method!");
return ResponseEntity.ok(new String("OK -> Permission OK"));
}


}
1 change: 0 additions & 1 deletion src/main/java/com/oauth2/entities/Permission.java
Original file line number Diff line number Diff line change
Expand Up @@ -32,7 +32,6 @@ public class Permission {
@ManyToMany(mappedBy = "permissions", cascade = CascadeType.PERSIST, fetch = FetchType.EAGER)
private Set<Role> roles;


@Override
public int hashCode() {
if (permissionId != null) {
Expand Down
3 changes: 0 additions & 3 deletions src/main/java/com/oauth2/entities/Role.java
Original file line number Diff line number Diff line change
Expand Up @@ -44,11 +44,9 @@ public class Role implements GrantedAuthority{
name = "permission_id", referencedColumnName = "permissionId"))
private Set<Permission> permissions;


@ManyToMany(mappedBy = "roles")
@Fetch(org.hibernate.annotations.FetchMode.SUBSELECT)
private List<User> users;


@Override
public String getAuthority() {
Expand All @@ -57,7 +55,6 @@ public String getAuthority() {
.collect(Collectors.joining(","));
}


@Override
public int hashCode() {
if (roleId != null) {
Expand Down
1 change: 0 additions & 1 deletion src/main/java/com/oauth2/models/dto/auth/AuthRolesDTO.java
Original file line number Diff line number Diff line change
Expand Up @@ -25,6 +25,5 @@ public AuthRolesDTO(Role role) {
.map(AuthPermissionsDTO::new)
.collect(Collectors.toList()));
}


}
17 changes: 0 additions & 17 deletions src/main/java/com/oauth2/repositories/IPermissionRepository.java

This file was deleted.

13 changes: 0 additions & 13 deletions src/main/java/com/oauth2/repositories/IRoleRepository.java

This file was deleted.

0 comments on commit 05514c3

Please sign in to comment.