Changeset 5a9c93b
- Timestamp:
- 03/05/24 14:15:44 (15 months ago)
- Branches:
- main
- Children:
- db39d9e
- Parents:
- a2c6c2b
- Files:
-
- 18 added
- 1 deleted
- 5 edited
Legend:
- Unmodified
- Added
- Removed
-
my-react-app/src/axios_helper.js
ra2c6c2b r5a9c93b 4 4 axios.defaults.headers.post["Content-Type"] = 'application/json' 5 5 6 export const getAuthToken = () => { 7 return window.localStorage.getItem("auth_token"); 8 } 9 10 export const setAuthToken = (token) => { 11 window.localStorage.setItem("auth_token", token); 12 } 13 6 14 export const request = (method, url, data) => { 15 let headers = {}; 16 if(getAuthToken() !== null && getAuthToken() !== "null") { 17 headers = {"Authorization" : `Bearer ${getAuthToken()}`}; 18 } 19 7 20 return axios({ 8 21 method: method, -
my-react-app/src/components/AppContent.js
ra2c6c2b r5a9c93b 2 2 import WelcomeContent from "./WelcomeContent"; 3 3 import AuthContent from "./AuthContent"; 4 import LoginForm from "./LoginForm"; 5 import { request, setAuthToken } from "../axios_helper"; 6 import Buttons from './Buttons' 4 7 5 8 export default class AppContent extends React.Component { 9 constructor(props) { 10 super(props); 11 this.state = { 12 componentToShow: "welcome" 13 }; 14 }; 15 16 login = () => { 17 this.setState({componentToShow: "login"}) 18 } 19 20 logout = () => { 21 this.setState({componentToShow: "welcome"}) 22 } 23 24 onLogin = (e, email, password) => { 25 e.preventDefault(); 26 request( 27 "POST", 28 "/api/login", 29 {login: email, password: password} 30 ).then((response) => { 31 this.setState({componentToShow: "restaurants"}) 32 setAuthToken(response.data.token); 33 }).catch((error) => { 34 this.setState({componentToShow: "welcome"}) 35 }); 36 }; 37 38 onRegister = (e, firstName, lastName, email, password) => { 39 e.preventDefault(); 40 request( 41 "POST", 42 "/api/register", 43 { 44 firstName: firstName, 45 lastName: lastName, 46 login: email, 47 password: password 48 } 49 ).then((response) => { 50 this.setState({componentToShow: "restaurants"}) 51 setAuthToken(response.data.token); 52 }).catch((error) => { 53 this.setState({componentToShow: "welcome"}) 54 }); 55 }; 56 6 57 render() { 7 58 return ( 8 59 <div> 9 <WelcomeContent/> 10 <AuthContent/> 60 <Buttons login={this.login} logout={this.logout}></Buttons> 61 {this.state.componentToShow === "welcome" && <WelcomeContent/>} 62 {this.state.componentToShow === "restaurants" && <AuthContent/>} 63 {this.state.componentToShow === "login" && <LoginForm onLogin={this.onLogin} onRegister={this.onRegister}/>} 11 64 </div> 12 65 ) -
pom.xml
ra2c6c2b r5a9c93b 99 99 <dependency> 100 100 <groupId>org.mapstruct</groupId> 101 <artifactId>mapstruct-processor</artifactId> 102 <version>1.5.3.Final</version> 101 <artifactId>mapstruct</artifactId> 102 <version>1.4.2.Final</version> <!-- Replace with the latest version --> 103 </dependency> 104 105 <dependency> 106 <groupId>com.auth0</groupId> 107 <artifactId>java-jwt</artifactId> 108 <version>4.3.0</version> 103 109 </dependency> 104 110 </dependencies> -
src/main/java/com/example/rezevirajmasa/demo/config/SecurityConfig.java
ra2c6c2b r5a9c93b 1 1 package com.example.rezevirajmasa.demo.config; 2 2 3 import com.example.rezevirajmasa.demo.model.exceptions.CustomerAuthenticationEntryPoint; 4 import com.example.rezevirajmasa.demo.web.filters.JwtAuthFilter; 3 5 import org.springframework.context.annotation.Bean; 4 6 import org.springframework.context.annotation.Configuration; 7 import org.springframework.http.HttpMethod; 5 8 import org.springframework.security.authentication.AuthenticationManager; 6 9 import org.springframework.security.config.annotation.authentication.builders.AuthenticationManagerBuilder; … … 9 12 import org.springframework.security.config.annotation.web.configuration.WebSecurityCustomizer; 10 13 import org.springframework.security.config.annotation.web.configurers.AbstractHttpConfigurer; 14 import org.springframework.security.config.http.SessionCreationPolicy; 11 15 import org.springframework.security.core.userdetails.UserDetailsService; 12 16 import org.springframework.security.web.SecurityFilterChain; 13 import org.springframework.security.web.util.matcher.AntPathRequestMatcher; 14 import org.springframework.web.cors.CorsConfiguration; 15 import org.springframework.web.cors.UrlBasedCorsConfigurationSource; 16 import org.springframework.web.filter.CorsFilter; 17 import org.springframework.security.web.authentication.www.BasicAuthenticationFilter; 17 18 import org.springframework.web.servlet.config.annotation.CorsRegistry; 18 19 import org.springframework.web.servlet.config.annotation.WebMvcConfigurer; 19 20 20 21 21 @Configuration … … 23 23 public class SecurityConfig implements WebMvcConfigurer { 24 24 private final UserDetailsService userDetailsService; 25 private final CustomerAuthenticationEntryPoint customerAuthenticationEntryPoint; 26 private final UserAuthProvider userAuthProvider; 25 27 26 public SecurityConfig(UserDetailsService userDetailsService ) {28 public SecurityConfig(UserDetailsService userDetailsService, CustomerAuthenticationEntryPoint customerAuthenticationEntryPoint, UserAuthProvider userAuthProvider) { 27 29 this.userDetailsService = userDetailsService; 30 this.customerAuthenticationEntryPoint = customerAuthenticationEntryPoint; 31 this.userAuthProvider = userAuthProvider; 28 32 } 29 33 … … 43 47 } 44 48 49 // @Bean 50 // public SecurityFilterChain securityFilterChain(HttpSecurity http) throws Exception { 51 // 52 // http 53 // .csrf(AbstractHttpConfigurer::disable) 54 // .authorizeHttpRequests( (requests) -> requests 55 // .requestMatchers(AntPathRequestMatcher.antMatcher("/"), AntPathRequestMatcher.antMatcher("/restaurants")) 56 // .permitAll() 57 // .anyRequest() 58 // .hasAnyRole("ADMIN", "USER") 59 // ) 60 // .formLogin((form) -> form 61 // .permitAll() 62 // .failureUrl("/login?error=BadCredentials") 63 // .defaultSuccessUrl("/restaurants", true) 64 // ) 65 // .logout((logout) -> logout 66 // .logoutUrl("/logout") 67 // .clearAuthentication(true) 68 // .invalidateHttpSession(true) 69 // .deleteCookies("JSESSIONID") 70 // .logoutSuccessUrl("/") 71 // ); 72 // 73 // return http.build(); 74 // } 75 45 76 @Bean 46 public SecurityFilterChain securityFilterChain(HttpSecurity http) throws Exception { 47 77 public SecurityFilterChain securityFilterChain(HttpSecurity http) throws Exception { 48 78 http 79 .exceptionHandling((exception) -> exception.authenticationEntryPoint(customerAuthenticationEntryPoint)) 80 .addFilterBefore(new JwtAuthFilter(userAuthProvider), BasicAuthenticationFilter.class) 49 81 .csrf(AbstractHttpConfigurer::disable) 50 .authorizeHttpRequests( (requests) -> requests 51 .requestMatchers(AntPathRequestMatcher.antMatcher("/"), AntPathRequestMatcher.antMatcher("/restaurants")) 52 .permitAll() 53 .anyRequest() 54 .hasAnyRole("ADMIN", "USER") 55 ) 56 .formLogin((form) -> form 57 .permitAll() 58 .failureUrl("/login?error=BadCredentials") 59 .defaultSuccessUrl("/restaurants", true) 60 ) 61 .logout((logout) -> logout 62 .logoutUrl("/logout") 63 .clearAuthentication(true) 64 .invalidateHttpSession(true) 65 .deleteCookies("JSESSIONID") 66 .logoutSuccessUrl("/") 82 .sessionManagement(sess -> sess.sessionCreationPolicy(SessionCreationPolicy.STATELESS)) 83 .authorizeHttpRequests((requests) -> requests 84 .requestMatchers(HttpMethod.POST, "/api/login", "/api/register").permitAll() 85 .anyRequest().authenticated() 67 86 ); 68 69 87 return http.build(); 70 88 } 71 72 89 @Bean 73 90 public AuthenticationManager authManager(HttpSecurity http) throws Exception { -
src/main/java/com/example/rezevirajmasa/demo/web/rest/AuthController.java
ra2c6c2b r5a9c93b 1 1 package com.example.rezevirajmasa.demo.web.rest; 2 2 3 import com.example.rezevirajmasa.demo.config.UserAuthProvider; 4 import com.example.rezevirajmasa.demo.dto.CredentialsDto; 5 import com.example.rezevirajmasa.demo.dto.SignUpDto; 6 import com.example.rezevirajmasa.demo.dto.UserDto; 3 7 import com.example.rezevirajmasa.demo.model.Customer; 4 8 import com.example.rezevirajmasa.demo.service.CustomerService; 9 import com.example.rezevirajmasa.demo.service.UserService; 10 import lombok.RequiredArgsConstructor; 5 11 import org.apache.coyote.Response; 6 12 import org.springframework.beans.factory.annotation.Autowired; … … 14 20 import org.springframework.web.bind.annotation.RestController; 15 21 16 @CrossOrigin(origins = "http://localhost:3000/") 22 import java.net.URI; 23 24 @RequiredArgsConstructor 17 25 @RestController 18 26 public class AuthController { 19 private final CustomerService customerService; 20 private final PasswordEncoder passwordEncoder; 21 22 public AuthController(CustomerService customerService, PasswordEncoder passwordEncoder) { 23 this.customerService = customerService; 24 this.passwordEncoder = passwordEncoder; 27 private final UserService userService; 28 private final UserAuthProvider userAuthProvider; 29 @PostMapping("/api/login") 30 public ResponseEntity<UserDto> login(@RequestBody CredentialsDto credentialsDto) { 31 UserDto user = userService.login(credentialsDto); 32 user.setToken(userAuthProvider.createToken(user.getEmail())); 33 return ResponseEntity.ok(user); 25 34 } 26 35 27 @PostMapping("/api/login") 28 public ResponseEntity<String> login(@RequestBody Customer customer) { 29 Customer exisitngCustomer = customerService.findByEmail(customer.getEmail()); 30 31 if(passwordEncoder.matches(customer.getPassword(), exisitngCustomer.getPassword())) { 32 String token = generateToken(exisitngCustomer); 33 return ResponseEntity.ok(token); 34 } else { 35 return ResponseEntity.status(HttpStatus.UNAUTHORIZED).build(); 36 } 37 } 38 39 private String generateToken(Customer customer) { 40 // Implement your token generation logic here 41 return "dummy_token"; 36 @PostMapping("/api/register") 37 public ResponseEntity<UserDto> register(@RequestBody SignUpDto signUpDto) { 38 UserDto user = userService.register(signUpDto); 39 user.setToken(userAuthProvider.createToken(user.getEmail())); 40 return ResponseEntity.created(URI.create("/users/" + user.getId())) 41 .body(user); 42 42 } 43 43 }
Note:
See TracChangeset
for help on using the changeset viewer.