54. Logging in and generating JWT (#5 Section 7: Generate JWT)

This commit is contained in:
Art
2021-09-07 17:02:25 +03:00
parent ca24902de6
commit cebe382dbd
3 changed files with 52 additions and 6 deletions

View File

@ -5,6 +5,8 @@ import net.shyshkin.study.fullstack.supportportal.backend.filter.JwtAccessDenied
import net.shyshkin.study.fullstack.supportportal.backend.filter.JwtAuthenticationEntryPoint; import net.shyshkin.study.fullstack.supportportal.backend.filter.JwtAuthenticationEntryPoint;
import net.shyshkin.study.fullstack.supportportal.backend.filter.JwtAuthorizationFilter; import net.shyshkin.study.fullstack.supportportal.backend.filter.JwtAuthorizationFilter;
import org.springframework.beans.factory.annotation.Value; import org.springframework.beans.factory.annotation.Value;
import org.springframework.context.annotation.Bean;
import org.springframework.security.authentication.AuthenticationManager;
import org.springframework.security.config.annotation.authentication.builders.AuthenticationManagerBuilder; import org.springframework.security.config.annotation.authentication.builders.AuthenticationManagerBuilder;
import org.springframework.security.config.annotation.method.configuration.EnableGlobalMethodSecurity; import org.springframework.security.config.annotation.method.configuration.EnableGlobalMethodSecurity;
import org.springframework.security.config.annotation.web.builders.HttpSecurity; import org.springframework.security.config.annotation.web.builders.HttpSecurity;
@ -55,4 +57,11 @@ public class SecurityConfig extends WebSecurityConfigurerAdapter {
.userDetailsService(userDetailsService) .userDetailsService(userDetailsService)
.passwordEncoder(passwordEncoder); .passwordEncoder(passwordEncoder);
} }
@Bean
@Override
public AuthenticationManager authenticationManagerBean() throws Exception {
return super.authenticationManagerBean();
}
} }

View File

@ -1,16 +1,29 @@
package net.shyshkin.study.fullstack.supportportal.backend.controller; package net.shyshkin.study.fullstack.supportportal.backend.controller;
import lombok.RequiredArgsConstructor; import lombok.RequiredArgsConstructor;
import net.shyshkin.study.fullstack.supportportal.backend.constant.SecurityConstants;
import net.shyshkin.study.fullstack.supportportal.backend.domain.HttpResponse;
import net.shyshkin.study.fullstack.supportportal.backend.domain.User; import net.shyshkin.study.fullstack.supportportal.backend.domain.User;
import net.shyshkin.study.fullstack.supportportal.backend.service.UserService; import net.shyshkin.study.fullstack.supportportal.backend.service.UserService;
import net.shyshkin.study.fullstack.supportportal.backend.utility.JwtTokenProvider;
import org.springframework.http.ResponseEntity;
import org.springframework.security.authentication.AuthenticationManager;
import org.springframework.security.authentication.UsernamePasswordAuthenticationToken;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.web.bind.annotation.*; import org.springframework.web.bind.annotation.*;
import static org.springframework.http.HttpStatus.OK;
@RestController @RestController
@RequestMapping("user") @RequestMapping("user")
@RequiredArgsConstructor @RequiredArgsConstructor
public class UserResource { public class UserResource {
private final UserService userService; private final UserService userService;
private final AuthenticationManager authenticationManager;
private final JwtTokenProvider jwtTokenProvider;
@GetMapping("home") @GetMapping("home")
public String showUser() { public String showUser() {
@ -21,4 +34,28 @@ public class UserResource {
public User register(@RequestBody User user) { public User register(@RequestBody User user) {
return userService.register(user.getFirstName(), user.getLastName(), user.getUsername(), user.getEmail()); return userService.register(user.getFirstName(), user.getLastName(), user.getUsername(), user.getEmail());
} }
@PostMapping("login")
public ResponseEntity<HttpResponse> login(@RequestBody User user) {
authenticate(user.getUsername(), user.getPassword());
UserDetails userDetails = userService.loadUserByUsername(user.getUsername());
HttpResponse httpResponse = HttpResponse.builder()
.httpStatus(OK)
.reason(OK.getReasonPhrase().toUpperCase())
.message("User logged in successfully")
.httpStatusCode(OK.value())
.build();
return ResponseEntity.ok()
.header(SecurityConstants.JWT_TOKEN_HEADER, jwtTokenProvider.generateJwtToken(userDetails))
.body(httpResponse);
}
private void authenticate(String username, String password) {
Authentication auth = new UsernamePasswordAuthenticationToken(username, password);
authenticationManager.authenticate(auth);
}
} }

View File

@ -5,13 +5,13 @@ import com.auth0.jwt.JWTVerifier;
import com.auth0.jwt.algorithms.Algorithm; import com.auth0.jwt.algorithms.Algorithm;
import com.auth0.jwt.exceptions.JWTVerificationException; import com.auth0.jwt.exceptions.JWTVerificationException;
import lombok.RequiredArgsConstructor; import lombok.RequiredArgsConstructor;
import net.shyshkin.study.fullstack.supportportal.backend.domain.UserPrincipal;
import org.apache.commons.lang3.StringUtils; import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Value; import org.springframework.beans.factory.annotation.Value;
import org.springframework.security.authentication.UsernamePasswordAuthenticationToken; import org.springframework.security.authentication.UsernamePasswordAuthenticationToken;
import org.springframework.security.core.Authentication; import org.springframework.security.core.Authentication;
import org.springframework.security.core.GrantedAuthority; import org.springframework.security.core.GrantedAuthority;
import org.springframework.security.core.authority.SimpleGrantedAuthority; import org.springframework.security.core.authority.SimpleGrantedAuthority;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.web.authentication.WebAuthenticationDetailsSource; import org.springframework.security.web.authentication.WebAuthenticationDetailsSource;
import org.springframework.stereotype.Service; import org.springframework.stereotype.Service;
@ -32,13 +32,13 @@ public class JwtTokenProvider {
@Value("${app.jwt.secret}") @Value("${app.jwt.secret}")
private String secret; private String secret;
public String generateJwtToken(UserPrincipal userPrincipal) { public String generateJwtToken(UserDetails userDetails) {
String[] claims = getClaimsFromUser(userPrincipal); String[] claims = getClaimsFromUser(userDetails);
return JWT.create() return JWT.create()
.withIssuer(GET_ARRAYS_LLC) .withIssuer(GET_ARRAYS_LLC)
.withAudience(GET_ARRAYS_ADMINISTRATION) .withAudience(GET_ARRAYS_ADMINISTRATION)
.withIssuedAt(new Date()) .withIssuedAt(new Date())
.withSubject(userPrincipal.getUsername()) .withSubject(userDetails.getUsername())
.withArrayClaim(AUTHORITIES, claims) .withArrayClaim(AUTHORITIES, claims)
.withExpiresAt(new Date(System.currentTimeMillis() + EXPIRATION_TIME)) .withExpiresAt(new Date(System.currentTimeMillis() + EXPIRATION_TIME))
.sign(Algorithm.HMAC512(secret)); .sign(Algorithm.HMAC512(secret));
@ -81,8 +81,8 @@ public class JwtTokenProvider {
} }
} }
private String[] getClaimsFromUser(UserPrincipal userPrincipal) { private String[] getClaimsFromUser(UserDetails userDetails) {
return userPrincipal.getAuthorities() return userDetails.getAuthorities()
.stream() .stream()
.map(GrantedAuthority::getAuthority) .map(GrantedAuthority::getAuthority)
.toArray(String[]::new); .toArray(String[]::new);