Final Implementation of AuthService
This commit is contained in:
@@ -1,8 +1,10 @@
|
|||||||
package com.hideyoshi.backendportfolio.base.security.config;
|
package com.hideyoshi.backendportfolio.base.security.config;
|
||||||
|
|
||||||
|
import com.fasterxml.jackson.databind.ObjectMapper;
|
||||||
import com.hideyoshi.backendportfolio.base.config.RestAuthenticationEntryPointConfig;
|
import com.hideyoshi.backendportfolio.base.config.RestAuthenticationEntryPointConfig;
|
||||||
import com.hideyoshi.backendportfolio.base.security.filter.CustomAuthenticationFilter;
|
import com.hideyoshi.backendportfolio.base.security.filter.CustomAuthenticationFilter;
|
||||||
import com.hideyoshi.backendportfolio.base.security.filter.CustomAuthorizationFilter;
|
import com.hideyoshi.backendportfolio.base.security.filter.CustomAuthorizationFilter;
|
||||||
|
import com.hideyoshi.backendportfolio.base.security.model.AuthDTO;
|
||||||
import com.hideyoshi.backendportfolio.base.security.oauth.repo.OAuthRequestRepository;
|
import com.hideyoshi.backendportfolio.base.security.oauth.repo.OAuthRequestRepository;
|
||||||
import com.hideyoshi.backendportfolio.base.security.service.AuthService;
|
import com.hideyoshi.backendportfolio.base.security.service.AuthService;
|
||||||
import com.hideyoshi.backendportfolio.util.exception.AuthenticationInvalidException;
|
import com.hideyoshi.backendportfolio.util.exception.AuthenticationInvalidException;
|
||||||
@@ -27,6 +29,8 @@ import javax.servlet.http.HttpServletRequest;
|
|||||||
import javax.servlet.http.HttpServletResponse;
|
import javax.servlet.http.HttpServletResponse;
|
||||||
import java.io.IOException;
|
import java.io.IOException;
|
||||||
|
|
||||||
|
import static org.springframework.http.MediaType.APPLICATION_JSON_VALUE;
|
||||||
|
|
||||||
@Log4j2
|
@Log4j2
|
||||||
@Configuration
|
@Configuration
|
||||||
@EnableWebSecurity
|
@EnableWebSecurity
|
||||||
@@ -95,11 +99,11 @@ public class SecurityConfig extends WebSecurityConfigurerAdapter {
|
|||||||
|
|
||||||
OAuth2User oauthUser = (OAuth2User) authentication.getPrincipal();
|
OAuth2User oauthUser = (OAuth2User) authentication.getPrincipal();
|
||||||
|
|
||||||
this.authService.loginOAuthUser(
|
AuthDTO authUser = this.authService.loginOAuthUser(oauthUser, request);
|
||||||
request,
|
|
||||||
response,
|
response.setContentType(APPLICATION_JSON_VALUE);
|
||||||
oauthUser
|
new ObjectMapper()
|
||||||
);
|
.writeValue(response.getOutputStream(), authUser);
|
||||||
|
|
||||||
}
|
}
|
||||||
|
|
||||||
|
|||||||
@@ -1,6 +1,8 @@
|
|||||||
package com.hideyoshi.backendportfolio.base.security.filter;
|
package com.hideyoshi.backendportfolio.base.security.filter;
|
||||||
|
|
||||||
|
import com.fasterxml.jackson.databind.ObjectMapper;
|
||||||
import com.hideyoshi.backendportfolio.base.config.RestAuthenticationEntryPointConfig;
|
import com.hideyoshi.backendportfolio.base.config.RestAuthenticationEntryPointConfig;
|
||||||
|
import com.hideyoshi.backendportfolio.base.security.model.AuthDTO;
|
||||||
import com.hideyoshi.backendportfolio.base.security.service.AuthService;
|
import com.hideyoshi.backendportfolio.base.security.service.AuthService;
|
||||||
import com.hideyoshi.backendportfolio.base.user.model.UserDTO;
|
import com.hideyoshi.backendportfolio.base.user.model.UserDTO;
|
||||||
import lombok.extern.log4j.Log4j2;
|
import lombok.extern.log4j.Log4j2;
|
||||||
@@ -15,6 +17,8 @@ import javax.servlet.http.HttpServletRequest;
|
|||||||
import javax.servlet.http.HttpServletResponse;
|
import javax.servlet.http.HttpServletResponse;
|
||||||
import java.io.IOException;
|
import java.io.IOException;
|
||||||
|
|
||||||
|
import static org.springframework.http.MediaType.APPLICATION_JSON_VALUE;
|
||||||
|
|
||||||
@Log4j2
|
@Log4j2
|
||||||
public class CustomAuthenticationFilter extends UsernamePasswordAuthenticationFilter {
|
public class CustomAuthenticationFilter extends UsernamePasswordAuthenticationFilter {
|
||||||
|
|
||||||
@@ -50,12 +54,16 @@ public class CustomAuthenticationFilter extends UsernamePasswordAuthenticationFi
|
|||||||
@Override
|
@Override
|
||||||
protected void successfulAuthentication(HttpServletRequest request, HttpServletResponse response, FilterChain chain, Authentication authentication) throws IOException {
|
protected void successfulAuthentication(HttpServletRequest request, HttpServletResponse response, FilterChain chain, Authentication authentication) throws IOException {
|
||||||
|
|
||||||
this.authService.loginUser(
|
AuthDTO authUser = this.authService.loginUser(
|
||||||
request,
|
request,
|
||||||
response,
|
response,
|
||||||
(UserDTO) authentication.getPrincipal()
|
(UserDTO) authentication.getPrincipal()
|
||||||
);
|
);
|
||||||
|
|
||||||
|
response.setContentType(APPLICATION_JSON_VALUE);
|
||||||
|
new ObjectMapper()
|
||||||
|
.writeValue(response.getOutputStream(), authUser);
|
||||||
|
|
||||||
}
|
}
|
||||||
|
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -19,9 +19,9 @@ public enum OAuthMapper {
|
|||||||
this.provider = provider;
|
this.provider = provider;
|
||||||
}
|
}
|
||||||
|
|
||||||
public static OAuthMapper byValue(String name) {
|
public static OAuthMapper byValue(Provider provider) {
|
||||||
for (OAuthMapper e : values()) {
|
for (OAuthMapper e : values()) {
|
||||||
if (e.getProvider().getName().equals(name)) {
|
if (e.getProvider().equals(provider)) {
|
||||||
return e;
|
return e;
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -56,21 +56,6 @@ public class AuthService {
|
|||||||
@Value("${com.hideyoshi.refreshTokenDuration}")
|
@Value("${com.hideyoshi.refreshTokenDuration}")
|
||||||
private Integer REFRESH_TOKEN_DURATION;
|
private Integer REFRESH_TOKEN_DURATION;
|
||||||
|
|
||||||
public UsernamePasswordAuthenticationToken extractAccessTokenInfo(String accessToken) {
|
|
||||||
DecodedJWT decodedJWT = this.decodeToken(accessToken)
|
|
||||||
.orElseThrow(() -> new BadRequestException("Invalid Token"));
|
|
||||||
|
|
||||||
String username = decodedJWT.getSubject();
|
|
||||||
String[] roles = decodedJWT.getClaim("roles").asArray(String.class);
|
|
||||||
|
|
||||||
Collection<SimpleGrantedAuthority> authorities = new ArrayList<>();
|
|
||||||
stream(roles).forEach(role -> {
|
|
||||||
authorities.add(new SimpleGrantedAuthority(role));
|
|
||||||
});
|
|
||||||
|
|
||||||
return new UsernamePasswordAuthenticationToken(username, null, authorities);
|
|
||||||
}
|
|
||||||
|
|
||||||
public AuthDTO signupUser(@Valid UserDTO user, HttpServletRequest request) {
|
public AuthDTO signupUser(@Valid UserDTO user, HttpServletRequest request) {
|
||||||
user.setProvider(Provider.LOCAL);
|
user.setProvider(Provider.LOCAL);
|
||||||
|
|
||||||
@@ -84,17 +69,26 @@ public class AuthService {
|
|||||||
|
|
||||||
}
|
}
|
||||||
|
|
||||||
public void loginUser(HttpServletRequest request, HttpServletResponse response, @Valid UserDTO user) throws IOException {
|
public AuthDTO loginUser(HttpServletRequest request, HttpServletResponse response, @Valid UserDTO user) throws IOException {
|
||||||
user.setProfilePictureUrl(this.extractProfilePictureUrl(user));
|
user.setProfilePictureUrl(this.extractProfilePictureUrl(user));
|
||||||
|
|
||||||
AuthDTO authObject = this.generateNewAuthenticatedUser(
|
return this.generateNewAuthenticatedUser(
|
||||||
user,
|
user,
|
||||||
request
|
request
|
||||||
);
|
);
|
||||||
|
}
|
||||||
|
|
||||||
response.setContentType(APPLICATION_JSON_VALUE);
|
public AuthDTO loginOAuthUser(OAuth2User oauthUser, HttpServletRequest request) {
|
||||||
new ObjectMapper()
|
Provider clientProvider = Provider.byValue(
|
||||||
.writeValue(response.getOutputStream(), authObject);
|
this.getClientFromUrl(request.getRequestURL().toString())
|
||||||
|
);
|
||||||
|
|
||||||
|
OAuthMap oauthMap = this.generateOAuthMap(clientProvider, oauthUser);
|
||||||
|
|
||||||
|
return this.processOAuthPostLogin(
|
||||||
|
this.generateAuthenticatedUserFromOAuth(oauthMap, oauthUser),
|
||||||
|
request
|
||||||
|
);
|
||||||
}
|
}
|
||||||
|
|
||||||
public AuthDTO refreshAccessToken(String requestToken, HttpServletRequest request) {
|
public AuthDTO refreshAccessToken(String requestToken, HttpServletRequest request) {
|
||||||
@@ -117,28 +111,26 @@ public class AuthService {
|
|||||||
|
|
||||||
}
|
}
|
||||||
|
|
||||||
public void loginOAuthUser(HttpServletRequest request,
|
|
||||||
HttpServletResponse response,
|
|
||||||
OAuth2User oauthUser) throws IOException {
|
|
||||||
|
|
||||||
String clientId = this.getClientFromUrl(request.getRequestURL().toString());
|
|
||||||
OAuthMap oauthMap = this.generateOAuthMap(clientId, oauthUser);
|
|
||||||
|
|
||||||
AuthDTO authObject = this.processOAuthPostLogin(
|
|
||||||
this.generateAuthenticatedUserFromOAuth(oauthMap, oauthUser),
|
|
||||||
request
|
|
||||||
);
|
|
||||||
|
|
||||||
response.setContentType(APPLICATION_JSON_VALUE);
|
|
||||||
new ObjectMapper()
|
|
||||||
.writeValue(response.getOutputStream(), authObject);
|
|
||||||
}
|
|
||||||
|
|
||||||
public UserDTO getLoggedUser() {
|
public UserDTO getLoggedUser() {
|
||||||
String username = (String) SecurityContextHolder.getContext().getAuthentication().getPrincipal();
|
String username = (String) SecurityContextHolder.getContext().getAuthentication().getPrincipal();
|
||||||
return userService.getUser(username);
|
return userService.getUser(username);
|
||||||
}
|
}
|
||||||
|
|
||||||
|
public UsernamePasswordAuthenticationToken extractAccessTokenInfo(String accessToken) {
|
||||||
|
DecodedJWT decodedJWT = this.decodeToken(accessToken)
|
||||||
|
.orElseThrow(() -> new BadRequestException("Invalid Token"));
|
||||||
|
|
||||||
|
String username = decodedJWT.getSubject();
|
||||||
|
String[] roles = decodedJWT.getClaim("roles").asArray(String.class);
|
||||||
|
|
||||||
|
Collection<SimpleGrantedAuthority> authorities = new ArrayList<>();
|
||||||
|
stream(roles).forEach(role -> {
|
||||||
|
authorities.add(new SimpleGrantedAuthority(role));
|
||||||
|
});
|
||||||
|
|
||||||
|
return new UsernamePasswordAuthenticationToken(username, null, authorities);
|
||||||
|
}
|
||||||
|
|
||||||
private Optional<DecodedJWT> decodeToken(String token) {
|
private Optional<DecodedJWT> decodeToken(String token) {
|
||||||
Algorithm algorithm = Algorithm.HMAC256(TOKEN_SECRET.getBytes());
|
Algorithm algorithm = Algorithm.HMAC256(TOKEN_SECRET.getBytes());
|
||||||
JWTVerifier verifier = JWT.require(algorithm).build();
|
JWTVerifier verifier = JWT.require(algorithm).build();
|
||||||
@@ -166,9 +158,9 @@ public class AuthService {
|
|||||||
return urlPartition[urlPartition.length - 1];
|
return urlPartition[urlPartition.length - 1];
|
||||||
}
|
}
|
||||||
|
|
||||||
private OAuthMap generateOAuthMap(String clientId, OAuth2User oauthUser) {
|
private OAuthMap generateOAuthMap(Provider clientProvider, OAuth2User oauthUser) {
|
||||||
try {
|
try {
|
||||||
return OAuthMapper.byValue(clientId).getMap()
|
return OAuthMapper.byValue(clientProvider).getMap()
|
||||||
.getDeclaredConstructor(OAuth2User.class).newInstance(oauthUser);
|
.getDeclaredConstructor(OAuth2User.class).newInstance(oauthUser);
|
||||||
} catch (Exception e) {
|
} catch (Exception e) {
|
||||||
throw new BadRequestException("Unsupported OAuth Client.");
|
throw new BadRequestException("Unsupported OAuth Client.");
|
||||||
|
|||||||
Reference in New Issue
Block a user