Skip to content

Commit a0cbc0e

Browse files
committed
Merge branch 'user/authorization'
2 parents 5b4f7f9 + 628226a commit a0cbc0e

22 files changed

+888
-3
lines changed

build.gradle

-3
Original file line numberDiff line numberDiff line change
@@ -30,8 +30,5 @@ dependencies {
3030
compile('org.springframework.boot:spring-boot-starter-data-jpa')
3131
compile('org.springframework.boot:spring-boot-starter-web')
3232
compile('org.springframework.boot:spring-boot-starter-security')
33-
compile('org.springframework.session:spring-session')
34-
35-
testCompile('org.springframework.boot:spring-boot-starter-test')
3633
runtime('mysql:mysql-connector-java:5.1.13')
3734
}
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,15 @@
1+
package org.basic.spring.security.rest;
2+
3+
4+
import org.springframework.boot.SpringApplication;
5+
import org.springframework.boot.autoconfigure.SpringBootApplication;
6+
7+
@SpringBootApplication
8+
public class Application {
9+
10+
11+
public static void main(String[] args) {
12+
SpringApplication.run(Application.class, args);
13+
14+
}
15+
}
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,55 @@
1+
package org.basic.spring.security.rest.config;
2+
3+
import org.basic.spring.security.rest.enums.Authoritiy;
4+
import org.springframework.beans.factory.annotation.Autowired;
5+
import org.springframework.context.annotation.Configuration;
6+
import org.springframework.security.config.annotation.authentication.builders.AuthenticationManagerBuilder;
7+
import org.springframework.security.config.annotation.method.configuration.EnableGlobalMethodSecurity;
8+
import org.springframework.security.config.annotation.web.builders.HttpSecurity;
9+
import org.springframework.security.config.annotation.web.configuration.EnableWebSecurity;
10+
import org.springframework.security.config.annotation.web.configuration.WebSecurityConfigurerAdapter;
11+
import org.springframework.security.core.userdetails.UserDetailsService;
12+
import org.springframework.security.web.access.AccessDeniedHandler;
13+
import org.springframework.security.web.authentication.www.BasicAuthenticationEntryPoint;
14+
15+
/**
16+
* This application is secured at both the URL level for some parts, and the
17+
* method level for other parts. The URL security is shown inside this code,
18+
* while method-level annotations are enabled at by
19+
* {@link EnableGlobalMethodSecurity}.
20+
*
21+
* @author Bijoy Paul
22+
*/
23+
@Configuration
24+
@EnableWebSecurity
25+
public class ApiSecurityConfig extends WebSecurityConfigurerAdapter {
26+
27+
@Autowired
28+
private BasicAuthenticationEntryPoint entryPoint;
29+
30+
@Autowired
31+
private AccessDeniedHandler handler;
32+
33+
@Autowired
34+
private UserDetailsService userDetailsService;
35+
36+
@Autowired
37+
public void configureGlobalSecurity(AuthenticationManagerBuilder auth)
38+
throws Exception {
39+
auth.userDetailsService(userDetailsService);
40+
}
41+
42+
@Override
43+
protected void configure(HttpSecurity http) throws Exception {
44+
45+
http.csrf().disable()
46+
.authorizeRequests()
47+
.antMatchers("/user/count").permitAll()
48+
.antMatchers("/user/profile").hasRole(Authoritiy.USER.toString())
49+
.antMatchers("/user/**").hasRole(Authoritiy.ADMIN.toString())
50+
.and()
51+
.httpBasic().authenticationEntryPoint(entryPoint)
52+
.and()
53+
.exceptionHandling().accessDeniedHandler(handler);
54+
}
55+
}
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,118 @@
1+
package org.basic.spring.security.rest.controller;
2+
3+
import java.security.Principal;
4+
5+
import org.basic.spring.security.rest.dto.entity.user.AuthenticationDto;
6+
import org.basic.spring.security.rest.dto.entity.user.UserDto;
7+
import org.basic.spring.security.rest.dto.entity.user.UserList;
8+
import org.basic.spring.security.rest.dto.response.AbstractResponseDto;
9+
import org.basic.spring.security.rest.service.UserManagedService;
10+
import org.basic.spring.security.rest.util.ResponseUtil;
11+
import org.springframework.beans.factory.annotation.Autowired;
12+
import org.springframework.http.HttpEntity;
13+
import org.springframework.http.HttpStatus;
14+
import org.springframework.http.ResponseEntity;
15+
import org.springframework.web.bind.annotation.PathVariable;
16+
import org.springframework.web.bind.annotation.RequestBody;
17+
import org.springframework.web.bind.annotation.RequestMapping;
18+
import org.springframework.web.bind.annotation.RequestMethod;
19+
import org.springframework.web.bind.annotation.RestController;
20+
21+
@RestController
22+
public class UserController {
23+
24+
@Autowired
25+
UserManagedService userService; //Service which will do all data retrieval/manipulation work
26+
27+
//-------------------User Profile Detail--------------------------------------------------------
28+
29+
@RequestMapping(value = "/user/profile", method = RequestMethod.GET)
30+
public HttpEntity<AbstractResponseDto> profileDetail(Principal principal) {
31+
UserDto user = userService.findByUsername(principal.getName());
32+
return ResponseUtil.success().body(user).send(HttpStatus.OK);
33+
}
34+
35+
//-------------------Count user--------------------------------------------------------
36+
37+
@RequestMapping(value = "/user/count", method = RequestMethod.GET)
38+
public HttpEntity<AbstractResponseDto> userCout() {
39+
40+
return ResponseUtil.success().body(userService.count()).send(HttpStatus.OK);
41+
}
42+
43+
//-------------------Retrieve All Users--------------------------------------------------------
44+
45+
@RequestMapping(value = "/user/", method = RequestMethod.GET)
46+
public HttpEntity<AbstractResponseDto> listAllUsers() {
47+
UserList users = userService.findAllUsers();
48+
if(users.getUserList().isEmpty()){
49+
return ResponseUtil.error().message("No data found").send(HttpStatus.NOT_FOUND);
50+
}
51+
return ResponseUtil.success().body(users).message("User list fetched successfully !!!").send(HttpStatus.OK);
52+
}
53+
54+
55+
//-------------------Retrieve Single User--------------------------------------------------------
56+
57+
@RequestMapping(value = "/user/{id}", method = RequestMethod.GET)
58+
public ResponseEntity<AbstractResponseDto> getUser(@PathVariable("id") long id) {
59+
UserDto user = userService.findById(id);
60+
if (user == null) {
61+
return ResponseUtil.error().message("No data found").send(HttpStatus.NOT_FOUND);
62+
}
63+
return ResponseUtil.success().body(user).message("User fetched successfully !!!").send(HttpStatus.OK);
64+
}
65+
66+
67+
68+
//-------------------Create a User--------------------------------------------------------
69+
70+
@RequestMapping(value = "/user/", method = RequestMethod.POST)
71+
public ResponseEntity<AbstractResponseDto> createUser(@RequestBody AuthenticationDto user) {
72+
73+
userService.saveUser(user);
74+
75+
return ResponseUtil.success().body(user.detail()).message("User created successfully !!!").send(HttpStatus.CREATED);
76+
}
77+
78+
79+
//------------------- Update a User --------------------------------------------------------
80+
81+
@RequestMapping(value = "/user/{id}", method = RequestMethod.PUT)
82+
public ResponseEntity<AbstractResponseDto> updateUser(@PathVariable("id") long id, @RequestBody UserDto user) {
83+
84+
UserDto currentUser = userService.findById(id);
85+
86+
if (currentUser==null) {
87+
return ResponseUtil.error().message("User with id " + id + " not found").send(HttpStatus.NOT_FOUND);
88+
}
89+
90+
userService.updateUser(currentUser, user);
91+
return ResponseUtil.success().body(currentUser).message("User updated successfully !!!").send(HttpStatus.OK);
92+
}
93+
94+
//------------------- Delete a User --------------------------------------------------------
95+
96+
@RequestMapping(value = "/user/{id}", method = RequestMethod.DELETE)
97+
public ResponseEntity<AbstractResponseDto> deleteUser(@PathVariable("id") long id) {
98+
99+
UserDto user = userService.findById(id);
100+
if (user == null) {
101+
System.out.println("Unable to delete. User with id " + id + " not found");
102+
return ResponseUtil.error().message("Unable to delete. User with id " + id + " not found").send(HttpStatus.NOT_FOUND);
103+
}
104+
105+
userService.deleteUserById(id);
106+
return ResponseUtil.success().body(user).message("User deleted successfully !!!").send(HttpStatus.OK);
107+
}
108+
109+
110+
//------------------- Delete All Users --------------------------------------------------------
111+
112+
@RequestMapping(value = "/user/", method = RequestMethod.DELETE)
113+
public ResponseEntity<AbstractResponseDto> deleteAllUsers() {
114+
115+
userService.deleteAllUsers();
116+
return ResponseUtil.success().body(new UserList()).message("All User deleted successfully !!!").send(HttpStatus.OK);
117+
}
118+
}
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,78 @@
1+
package org.basic.spring.security.rest.domain;
2+
3+
import java.util.HashSet;
4+
import java.util.Set;
5+
6+
import javax.persistence.CascadeType;
7+
import javax.persistence.Entity;
8+
import javax.persistence.FetchType;
9+
import javax.persistence.Id;
10+
import javax.persistence.JoinColumn;
11+
import javax.persistence.JoinTable;
12+
import javax.persistence.ManyToMany;
13+
14+
@Entity
15+
public class Authentication {
16+
17+
@Id
18+
private String username;
19+
private String password;
20+
@ManyToMany(fetch = FetchType.EAGER, cascade = CascadeType.ALL)
21+
@JoinTable(
22+
joinColumns = @JoinColumn(name = "user_id"), inverseJoinColumns = @JoinColumn(name = "role_id")
23+
)
24+
private Set<Role> roles;
25+
public Authentication(){}
26+
27+
public Authentication(String username, String password, Set<Role> roles){
28+
this.username = username;
29+
this.password = password;
30+
this.roles = roles;
31+
}
32+
33+
34+
public String getUsername() {
35+
return username;
36+
}
37+
public void setUsername(String username) {
38+
this.username = username;
39+
}
40+
public String getPassword() {
41+
return password;
42+
}
43+
public void setPassword(String password) {
44+
this.password = password;
45+
}
46+
47+
public Set<Role> getRoles() {
48+
return roles;
49+
}
50+
51+
public void setRoles(Set<Role> roles) {
52+
this.roles = roles;
53+
}
54+
55+
public void addRole(Role role) {
56+
Set<Role> roles = this.getRoles();
57+
if (roles == null) {
58+
roles = new HashSet<Role>();
59+
this.setRoles(roles);
60+
}
61+
roles.add(role);
62+
63+
Set<Authentication> users = role.getUsers();
64+
if (users == null) {
65+
users = new HashSet<Authentication>();
66+
role.setUsers(users);
67+
}
68+
users.add(this);
69+
70+
}
71+
72+
@Override
73+
public String toString() {
74+
return "User [username=" + username + ", password=" + password + "]";
75+
}
76+
77+
78+
}
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,57 @@
1+
package org.basic.spring.security.rest.domain;
2+
3+
import java.util.HashSet;
4+
import java.util.Set;
5+
6+
import javax.persistence.*;
7+
8+
@Entity
9+
public class Role {
10+
11+
@Id
12+
@GeneratedValue(strategy = GenerationType.AUTO)
13+
private Long id;
14+
15+
@Column(unique= true)
16+
private String authority;
17+
18+
@ManyToMany(mappedBy = "roles", fetch = FetchType.LAZY)
19+
private Set<Authentication> users;
20+
21+
public Role(){}
22+
23+
public Role(String authority){
24+
this.authority = authority;
25+
}
26+
27+
public Long getId() {
28+
return id;
29+
}
30+
31+
public String getAuthority() {
32+
return authority;
33+
}
34+
public void setAuthority(String authority) {
35+
this.authority = authority;
36+
}
37+
public Set<Authentication> getUsers() {
38+
return users;
39+
}
40+
public void setUsers(Set<Authentication> users) {
41+
this.users = users;
42+
}
43+
public void addUser(Authentication user){
44+
Set<Role> roles = user.getRoles();
45+
if(roles == null){
46+
roles = new HashSet<Role>();
47+
user.setRoles(roles);
48+
}
49+
roles.add(this);
50+
Set<Authentication> users = this.getUsers();
51+
if(users == null){
52+
users = new HashSet<Authentication>();
53+
this.setUsers(users);
54+
}
55+
users.add(user);
56+
}
57+
}

0 commit comments

Comments
 (0)