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

10738 - Implement Authentication controller #19

Closed
Tracked by #1
njtalba5127 opened this issue Dec 8, 2022 · 5 comments · Fixed by #35 or #36
Closed
Tracked by #1

10738 - Implement Authentication controller #19

njtalba5127 opened this issue Dec 8, 2022 · 5 comments · Fixed by #35 or #36
Assignees
Labels
enhancement New feature or request

Comments

@njtalba5127
Copy link
Member

njtalba5127 commented Dec 8, 2022

Timestamp: (10738) / 11632

@njtalba5127 njtalba5127 mentioned this issue Dec 8, 2022
23 tasks
@njtalba5127 njtalba5127 added the enhancement New feature or request label Dec 8, 2022
@njtalba5127 njtalba5127 self-assigned this Dec 8, 2022
@njtalba5127
Copy link
Member Author

create new java class file called "AuthenticationController.java" inside the controllers package.

AuthenticationController.java

package com.nellyxinwei.backend.controllers;

import org.springframework.http.ResponseEntity;
import org.springframework.security.authentication.AuthenticationManager;
import org.springframework.security.authentication.UsernamePasswordAuthenticationToken;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import com.nellyxinwei.backend.dto.AuthenticationRequest;

import lombok.RequiredArgsConstructor;

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

  private final AuthenticationManager authenticationManager;

  public ResponseEntity<String> authenticate(
      @RequestBody AuthenticationRequest request) {
    authenticationManager.authenticate(
        new UsernamePasswordAuthenticationToken(request.getEmail(), request.getPassword()));
  }
}

@njtalba5127
Copy link
Member Author

create a new package called "dto", and in it create a new java class file called "AuthenticationRequest.java"

AuthenticationRequest.java:

package com.nellyxinwei.backend.dto;

import lombok.Getter;
import lombok.NoArgsConstructor;
import lombok.Setter;

@Getter
@Setter
@NoArgsConstructor
public class AuthenticationRequest {
  public String email;
  public String password;
}

@njtalba5127
Copy link
Member Author

.
└── backend
    ├── HELP.md
    ├── mvnw
    ├── mvnw.cmd
    ├── pom.xml
    ├── src
    │   ├── main
    │   │   ├── java
    │   │   │   └── com
    │   │   │       └── nellyxinwei
    │   │   │           └── backend
    │   │   │               ├── BackendApplication.java
    │   │   │               ├── config
    │   │   │               │   ├── JwtAthFilter.java
    │   │   │               │   ├── JwtUtils.java
    │   │   │               │   └── SecurityConfig.java
    │   │   │               ├── controllers
    │   │   │               │   ├── AuthenticationController.java
    │   │   │               │   └── GreetingsController.java
    │   │   │               └── dto
    │   │   │                   └── AuthenticationRequest.java

@njtalba5127
Copy link
Member Author

create a new bean inside SecurityConfig.java

SecurityConfig.java

package com.nellyxinwei.backend.config;

import java.util.Collection;
import java.util.Collections;
import java.util.List;

import org.apache.tomcat.jni.User;
import org.springframework.context.annotation.Bean;
import org.springframework.security.authentication.AuthenticationManager;
import org.springframework.security.authentication.AuthenticationProvider;
import org.springframework.security.authentication.dao.DaoAuthenticationProvider;
import org.springframework.security.config.annotation.authentication.configuration.AuthenticationConfiguration;
import org.springframework.security.config.annotation.web.builders.HttpSecurity;
import org.springframework.security.config.annotation.web.configuration.EnableWebSecurity;
import org.springframework.security.config.http.SessionCreationPolicy;
import org.springframework.security.core.authority.SimpleGrantedAuthority;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.core.userdetails.UsernameNotFoundException;
import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder;
import org.springframework.security.crypto.password.NoOpPasswordEncoder;
import org.springframework.security.crypto.password.PasswordEncoder;
import org.springframework.security.web.SecurityFilterChain;
import org.springframework.security.web.authentication.UsernamePasswordAuthenticationFilter;

import io.jsonwebtoken.lang.Arrays;
import lombok.RequiredArgsConstructor;

@EnableWebSecurity
@RequiredArgsConstructor
public class SecurityConfig {

  private final JwtAthFilter jwtAthFilter;

  private final static List<UserDetails>APPLICATION_USERS = Arrays.asList(
    new User(
      "[email protected]",
      "password",
      Collections.singleton(new SimpleGrantedAuthority("ROLE_ADMIN"))
    ),
    new User(
      "[email protected]",
      "password",
      Collections.singleton(new SimpleGrantedAuthority("ROLE_USER"))
    )
  )

  @Bean
  public SecurityFilterChain securityFilterChain(HttpSecurity http) throws Exception {
    http
        .authorizeRequests()
        .anyRequest()
        .authenticated()
        .and()
        .sessionManagement()
        .sessionCreationPolicy(SessionCreationPolicy.STATELESS)
        .and()
        .authenticationProvider(authenticationProvider())
        .addFilterBefore(jwtAthFilter, UsernamePasswordAuthenticationFilter.class);
    return http.build();
  }

  @Bean
  public AuthenticationProvider authenticationProvider() {
    final DaoAuthenticationProvider authenticationProvider = new DaoAuthenticationProvider();
    authenticationProvider.setUserDetailsService(userDetailsService());
    authenticationProvider.setPasswordEncoder(passwordEncoder());
    return authenticationProvider;
  }

  @Bean
  public AuthenticationManager authenticationManager(AuthenticationConfiguration config) throws Exception{
    return config.getAuthenticationManager();
  }

  @Bean
  public PasswordEncoder passwordEncoder() {
    // return new BCryptPasswordEncoder();
    return NoOpPasswordEncoder.getInstance();
  }

  @Bean
  public UserDetailsService userDetailsService() {
    return new UserDetailsService() {
      @Override
      public UserDetails loadUserByUsername(String email) throws UsernameNotFoundException {
        return APPLICATION_USERS
            .stream()
            .filter(u -> u.getUsername().equals(email))
            .findFirst()
            .orElseThrow(() -> new UsernameNotFoundException("No user was found"));
      }
    };
  }
}

@njtalba5127
Copy link
Member Author

back to our AuthenticationController.java

AuthenticationController.java

package com.nellyxinwei.backend.controllers;

import org.springframework.http.ResponseEntity;
import org.springframework.security.authentication.AuthenticationManager;
import org.springframework.security.authentication.UsernamePasswordAuthenticationToken;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import com.nellyxinwei.backend.config.JwtUtils;
import com.nellyxinwei.backend.dto.AuthenticationRequest;

import lombok.RequiredArgsConstructor;

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

  private final AuthenticationManager authenticationManager;
  private final UserDetailsService userDetailsService;
  private final JwtUtils jwtUtils;

  @PostMapping("/authenticate")
  public ResponseEntity<String> authenticate(
      @RequestBody AuthenticationRequest request) {
    authenticationManager.authenticate(
        new UsernamePasswordAuthenticationToken(request.getEmail(), request.getPassword()));
    final UserDetails user = userDetailsService.loadUserByUsername(request.getEmail());
    if (user != null) {
      return ResponseEntity.ok(jwtUtils.generateToken(user));
    }
    return ResponseEntity.status(400).body("Some error has occured");
  }
}

This was linked to pull requests Dec 16, 2022
Repository owner moved this from In Progress to Done in 2223-1202WinterFuyu-Projects Dec 16, 2022
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment