Skip to content

Commit c1e3568

Browse files
rahulrahul
authored andcommitted
first commit
1 parent aece59f commit c1e3568

22 files changed

+1061
-1
lines changed

pom.xml

Lines changed: 17 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -29,6 +29,23 @@
2929
<groupId>org.springframework.boot</groupId>
3030
<artifactId>spring-boot-starter-web</artifactId>
3131
</dependency>
32+
33+
<dependency>
34+
<groupId>org.springframework.boot</groupId>
35+
<artifactId>spring-boot-starter-data-jpa</artifactId>
36+
</dependency>
37+
38+
<dependency>
39+
<groupId>org.springframework.boot</groupId>
40+
<artifactId>spring-boot-starter-security</artifactId>
41+
</dependency>
42+
43+
<dependency>
44+
<groupId>io.jsonwebtoken</groupId>
45+
<artifactId>jjwt</artifactId>
46+
<version>0.2</version>
47+
</dependency>
48+
3249
</dependencies>
3350

3451
<build>
Lines changed: 96 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -1,7 +1,102 @@
11
package com.baghaniya.springsecurity.config;
22

3+
import com.baghaniya.springsecurity.security.JwtAuthenticationEntryPoint;
4+
import com.baghaniya.springsecurity.security.JwtAuthenticationFilter;
5+
import com.baghaniya.springsecurity.security.UserDetailsServiceImpl;
6+
import org.springframework.beans.factory.annotation.Autowired;
7+
import org.springframework.context.annotation.Bean;
8+
import org.springframework.context.annotation.Configuration;
9+
import org.springframework.http.HttpMethod;
10+
import org.springframework.security.authentication.AuthenticationManager;
11+
import org.springframework.security.config.BeanIds;
12+
import org.springframework.security.config.annotation.authentication.builders.AuthenticationManagerBuilder;
13+
import org.springframework.security.config.annotation.method.configuration.EnableGlobalMethodSecurity;
14+
import org.springframework.security.config.annotation.web.builders.HttpSecurity;
15+
import org.springframework.security.config.annotation.web.configuration.EnableWebSecurity;
16+
import org.springframework.security.config.annotation.web.configuration.WebSecurityConfigurerAdapter;
17+
import org.springframework.security.config.http.SessionCreationPolicy;
18+
import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder;
19+
import org.springframework.security.crypto.password.PasswordEncoder;
20+
import org.springframework.security.web.authentication.UsernamePasswordAuthenticationFilter;
21+
322
/**
423
* Created by RAHUL on Jul, 2018
524
*/
6-
public class SecurityConfig {
25+
26+
@Configuration
27+
@EnableWebSecurity
28+
@EnableGlobalMethodSecurity(
29+
securedEnabled = true,
30+
prePostEnabled = true
31+
)
32+
public class SecurityConfig extends WebSecurityConfigurerAdapter {
33+
34+
@Autowired
35+
UserDetailsServiceImpl userDetailsService;
36+
37+
@Autowired
38+
private JwtAuthenticationEntryPoint unauthorizedHandler;
39+
40+
@Bean
41+
public JwtAuthenticationFilter jwtAuthenticationFilter() {
42+
return new JwtAuthenticationFilter();
43+
}
44+
45+
@Override
46+
public void configure(AuthenticationManagerBuilder authenticationManagerBuilder) throws Exception {
47+
authenticationManagerBuilder
48+
.userDetailsService(userDetailsService)
49+
.passwordEncoder(passwordEncoder());
50+
}
51+
52+
@Bean(BeanIds.AUTHENTICATION_MANAGER)
53+
@Override
54+
public AuthenticationManager authenticationManagerBean() throws Exception {
55+
return super.authenticationManagerBean();
56+
}
57+
58+
@Bean
59+
public PasswordEncoder passwordEncoder() {
60+
return new BCryptPasswordEncoder();
61+
}
62+
63+
@Override
64+
protected void configure(HttpSecurity http) throws Exception {
65+
http
66+
.cors()
67+
.and()
68+
.csrf()
69+
.disable()
70+
.exceptionHandling()
71+
.authenticationEntryPoint(unauthorizedHandler)
72+
.and()
73+
.sessionManagement()
74+
.sessionCreationPolicy(SessionCreationPolicy.STATELESS)
75+
.and()
76+
.authorizeRequests()
77+
.antMatchers("/",
78+
"/favicon.ico",
79+
"/**/*.png",
80+
"/**/*.gif",
81+
"/**/*.svg",
82+
"/**/*.jpg",
83+
"/**/*.html",
84+
"/**/*.css",
85+
"/**/*.js")
86+
.permitAll()
87+
.antMatchers("/api/auth/**")
88+
.permitAll()
89+
.antMatchers("/api/user/checkUsernameAvailability", "/api/user/checkEmailAvailability")
90+
.permitAll()
91+
.antMatchers(HttpMethod.GET, "/api/polls/**", "/api/users/**")
92+
.permitAll()
93+
.antMatchers("/h2/**")
94+
.permitAll()
95+
.anyRequest()
96+
.authenticated();
97+
98+
// Add our custom JWT security filter
99+
http.addFilterBefore(jwtAuthenticationFilter(), UsernamePasswordAuthenticationFilter.class);
100+
101+
}
7102
}
Lines changed: 15 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,15 @@
1+
package com.baghaniya.springsecurity.config;
2+
3+
import org.springframework.web.servlet.config.annotation.CorsRegistry;
4+
import org.springframework.web.servlet.config.annotation.WebMvcConfigurer;
5+
6+
/**
7+
* Created by RAHUL on Jul, 2018
8+
*/
9+
public class WebMvcConfig implements WebMvcConfigurer {
10+
11+
@Override
12+
public void addCorsMappings(CorsRegistry registry) {
13+
registry.addMapping("/**");
14+
}
15+
}
Lines changed: 101 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,101 @@
1+
package com.baghaniya.springsecurity.controller;
2+
3+
import com.baghaniya.springsecurity.exception.AppException;
4+
import com.baghaniya.springsecurity.model.Role;
5+
import com.baghaniya.springsecurity.model.RoleName;
6+
import com.baghaniya.springsecurity.model.User;
7+
import com.baghaniya.springsecurity.payload.ApiResponse;
8+
import com.baghaniya.springsecurity.payload.JwtAuthenticationResponse;
9+
import com.baghaniya.springsecurity.payload.LoginRequest;
10+
import com.baghaniya.springsecurity.payload.SignUpRequest;
11+
import com.baghaniya.springsecurity.repository.RoleRepository;
12+
import com.baghaniya.springsecurity.repository.UserRepository;
13+
import com.baghaniya.springsecurity.security.JwtTokenProvider;
14+
import org.springframework.beans.factory.annotation.Autowired;
15+
import org.springframework.http.HttpStatus;
16+
import org.springframework.http.ResponseEntity;
17+
import org.springframework.security.authentication.AuthenticationManager;
18+
import org.springframework.security.authentication.UsernamePasswordAuthenticationToken;
19+
import org.springframework.security.core.Authentication;
20+
import org.springframework.security.core.context.SecurityContextHolder;
21+
import org.springframework.security.crypto.password.PasswordEncoder;
22+
import org.springframework.web.bind.annotation.PostMapping;
23+
import org.springframework.web.bind.annotation.RequestBody;
24+
import org.springframework.web.bind.annotation.RequestMapping;
25+
import org.springframework.web.bind.annotation.RestController;
26+
import org.springframework.web.servlet.support.ServletUriComponentsBuilder;
27+
28+
import javax.validation.Valid;
29+
import java.net.URI;
30+
import java.util.Collections;
31+
32+
/**
33+
* Created by RAHUL on Jul, 2018
34+
*/
35+
@RestController
36+
@RequestMapping("/api/auth")
37+
public class AuthController {
38+
39+
@Autowired
40+
AuthenticationManager authenticationManager;
41+
42+
@Autowired
43+
UserRepository userRepository;
44+
45+
@Autowired
46+
RoleRepository roleRepository;
47+
48+
@Autowired
49+
PasswordEncoder passwordEncoder;
50+
51+
@Autowired
52+
JwtTokenProvider tokenProvider;
53+
54+
@PostMapping("/signin")
55+
public ResponseEntity<?> authenticateUser(@Valid @RequestBody LoginRequest loginRequest) {
56+
57+
Authentication authentication = authenticationManager.authenticate(
58+
new UsernamePasswordAuthenticationToken(
59+
loginRequest.getUsernameOrEmail(),
60+
loginRequest.getPassword()
61+
)
62+
);
63+
64+
SecurityContextHolder.getContext().setAuthentication(authentication);
65+
66+
String jwt = tokenProvider.generateToken(authentication);
67+
return ResponseEntity.ok(new JwtAuthenticationResponse(jwt));
68+
}
69+
70+
@PostMapping("/signup")
71+
public ResponseEntity<?> registerUser(@Valid @RequestBody SignUpRequest signUpRequest) {
72+
if(userRepository.existsByUsername(signUpRequest.getUsername())) {
73+
return new ResponseEntity(new ApiResponse(false, "Username is already taken!"),
74+
HttpStatus.BAD_REQUEST);
75+
}
76+
77+
if(userRepository.existsByEmail(signUpRequest.getEmail())) {
78+
return new ResponseEntity(new ApiResponse(false, "Email Address already in use!"),
79+
HttpStatus.BAD_REQUEST);
80+
}
81+
82+
// Creating user's account
83+
User user = new User(signUpRequest.getName(), signUpRequest.getUsername(),
84+
signUpRequest.getEmail(), signUpRequest.getPassword());
85+
86+
user.setPassword(passwordEncoder.encode(user.getPassword()));
87+
88+
Role userRole = roleRepository.findByName(RoleName.ROLE_USER)
89+
.orElseThrow(() -> new AppException("User Role not set."));
90+
91+
user.setRoles(Collections.singleton(userRole));
92+
93+
User result = userRepository.save(user);
94+
95+
URI location = ServletUriComponentsBuilder
96+
.fromCurrentContextPath().path("/users/{username}")
97+
.buildAndExpand(result.getUsername()).toUri();
98+
99+
return ResponseEntity.created(location).body(new ApiResponse(true, "User registered successfully"));
100+
}
101+
}
Lines changed: 81 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,81 @@
1+
//package com.baghaniya.springsecurity.controller;
2+
//
3+
//import com.baghaniya.springsecurity.repository.UserRepository;
4+
//import org.slf4j.Logger;
5+
//import org.slf4j.LoggerFactory;
6+
//import org.springframework.beans.factory.annotation.Autowired;
7+
//import org.springframework.security.access.prepost.PreAuthorize;
8+
//import org.springframework.web.bind.annotation.*;
9+
//
10+
///**
11+
// * Created by RAHUL on Jul, 2018
12+
// */
13+
//
14+
//@RestController
15+
//@RequestMapping("/api")
16+
//public class UserController {
17+
//
18+
// @Autowired
19+
// private UserRepository userRepository;
20+
//
21+
// @Autowired
22+
// private PollRepository pollRepository;
23+
//
24+
// @Autowired
25+
// private VoteRepository voteRepository;
26+
//
27+
// @Autowired
28+
// private PollService pollService;
29+
//
30+
// private static final Logger logger = LoggerFactory.getLogger(UserController.class);
31+
//
32+
// @GetMapping("/user/me")
33+
// @PreAuthorize("hasRole('USER')")
34+
// public UserSummary getCurrentUser(@CurrentUser UserPrincipal currentUser) {
35+
// UserSummary userSummary = new UserSummary(currentUser.getId(), currentUser.getUsername(), currentUser.getName());
36+
// return userSummary;
37+
// }
38+
//
39+
// @GetMapping("/user/checkUsernameAvailability")
40+
// public UserIdentityAvailability checkUsernameAvailability(@RequestParam(value = "username") String username) {
41+
// Boolean isAvailable = !userRepository.existsByUsername(username);
42+
// return new UserIdentityAvailability(isAvailable);
43+
// }
44+
//
45+
// @GetMapping("/user/checkEmailAvailability")
46+
// public UserIdentityAvailability checkEmailAvailability(@RequestParam(value = "email") String email) {
47+
// Boolean isAvailable = !userRepository.existsByEmail(email);
48+
// return new UserIdentityAvailability(isAvailable);
49+
// }
50+
//
51+
// @GetMapping("/users/{username}")
52+
// public UserProfile getUserProfile(@PathVariable(value = "username") String username) {
53+
// User user = userRepository.findByUsername(username)
54+
// .orElseThrow(() -> new ResourceNotFoundException("User", "username", username));
55+
//
56+
// long pollCount = pollRepository.countByCreatedBy(user.getId());
57+
// long voteCount = voteRepository.countByUserId(user.getId());
58+
//
59+
// UserProfile userProfile = new UserProfile(user.getId(), user.getUsername(), user.getName(), user.getCreatedAt(), pollCount, voteCount);
60+
//
61+
// return userProfile;
62+
// }
63+
//
64+
// @GetMapping("/users/{username}/polls")
65+
// public PagedResponse<PollResponse> getPollsCreatedBy(@PathVariable(value = "username") String username,
66+
// @CurrentUser UserPrincipal currentUser,
67+
// @RequestParam(value = "page", defaultValue = AppConstants.DEFAULT_PAGE_NUMBER) int page,
68+
// @RequestParam(value = "size", defaultValue = AppConstants.DEFAULT_PAGE_SIZE) int size) {
69+
// return pollService.getPollsCreatedBy(username, currentUser, page, size);
70+
// }
71+
//
72+
//
73+
// @GetMapping("/users/{username}/votes")
74+
// public PagedResponse<PollResponse> getPollsVotedBy(@PathVariable(value = "username") String username,
75+
// @CurrentUser UserPrincipal currentUser,
76+
// @RequestParam(value = "page", defaultValue = AppConstants.DEFAULT_PAGE_NUMBER) int page,
77+
// @RequestParam(value = "size", defaultValue = AppConstants.DEFAULT_PAGE_SIZE) int size) {
78+
// return pollService.getPollsVotedBy(username, currentUser, page, size);
79+
// }
80+
//
81+
//}
Lines changed: 18 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,18 @@
1+
package com.baghaniya.springsecurity.exception;
2+
3+
import org.springframework.http.HttpStatus;
4+
import org.springframework.web.bind.annotation.ResponseStatus;
5+
6+
/**
7+
* Created by RAHUL on Jul, 2018
8+
*/
9+
@ResponseStatus(HttpStatus.INTERNAL_SERVER_ERROR)
10+
public class AppException extends RuntimeException {
11+
public AppException(String message) {
12+
super(message);
13+
}
14+
15+
public AppException(String message, Throwable cause) {
16+
super(message, cause);
17+
}
18+
}
Lines changed: 19 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,19 @@
1+
package com.baghaniya.springsecurity.exception;
2+
import org.springframework.http.HttpStatus;
3+
import org.springframework.web.bind.annotation.ResponseStatus;
4+
/**
5+
* Created by RAHUL on Jul, 2018
6+
*/
7+
8+
9+
@ResponseStatus(HttpStatus.BAD_REQUEST)
10+
public class BadRequestException extends RuntimeException {
11+
12+
public BadRequestException(String message) {
13+
super(message);
14+
}
15+
16+
public BadRequestException(String message, Throwable cause) {
17+
super(message, cause);
18+
}
19+
}

0 commit comments

Comments
 (0)