-
Notifications
You must be signed in to change notification settings - Fork 12
no-task: заменил basic auth на кастомную схему #1
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
base: master
Are you sure you want to change the base?
Changes from all commits
File filter
Filter by extension
Conversations
Jump to
Diff view
Diff view
There are no files selected for viewing
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,130 @@ | ||
| package pro.akosarev.sandbox; | ||
|
|
||
| import com.fasterxml.jackson.databind.ObjectMapper; | ||
| import jakarta.servlet.FilterChain; | ||
| import jakarta.servlet.ServletException; | ||
| import jakarta.servlet.http.HttpServletRequest; | ||
| import jakarta.servlet.http.HttpServletResponse; | ||
| import org.springframework.core.log.LogMessage; | ||
| import org.springframework.http.HttpMethod; | ||
| import org.springframework.security.authentication.AuthenticationManager; | ||
| import org.springframework.security.authentication.UsernamePasswordAuthenticationToken; | ||
| import org.springframework.security.core.Authentication; | ||
| import org.springframework.security.core.AuthenticationException; | ||
| import org.springframework.security.core.context.SecurityContext; | ||
| import org.springframework.security.core.context.SecurityContextHolder; | ||
| import org.springframework.security.core.context.SecurityContextHolderStrategy; | ||
| import org.springframework.security.web.context.RequestAttributeSecurityContextRepository; | ||
| import org.springframework.security.web.context.SecurityContextRepository; | ||
| import org.springframework.security.web.util.matcher.AntPathRequestMatcher; | ||
| import org.springframework.security.web.util.matcher.RequestMatcher; | ||
| import org.springframework.util.Assert; | ||
| import org.springframework.web.filter.OncePerRequestFilter; | ||
|
|
||
| import java.io.IOException; | ||
|
|
||
| public class RequestLoginPasswordFilter extends OncePerRequestFilter { | ||
|
|
||
| private SecurityContextHolderStrategy securityContextHolderStrategy = SecurityContextHolder.getContextHolderStrategy(); | ||
| private ObjectMapper objectMapper; | ||
| private String defaultUsernameJsonBodyParameter = "username"; | ||
| private String defaultPasswordJsonBodyParameter = "password"; | ||
| private String nativeAppHeader = "X-native"; | ||
| private RequestMatcher requestMatcher = new AntPathRequestMatcher("/jwt/tokens", HttpMethod.POST.name()); | ||
| private AuthenticationManager authenticationManager; | ||
| private SecurityContextRepository securityContextRepository = new RequestAttributeSecurityContextRepository(); | ||
|
|
||
| @Override | ||
| protected void doFilterInternal(HttpServletRequest request, HttpServletResponse response, FilterChain chain) throws ServletException, IOException { | ||
| if (this.requestMatcher.matches(request)) { | ||
| try { | ||
| var isNative = checkNativeHeader(request); | ||
| if (!isNative) { | ||
|
Owner
There was a problem hiding this comment. Choose a reason for hiding this commentThe reason will be displayed to describe this comment to others. Learn more. Не совсем понятно - а зачем?) Кто угодно может добавить заголовок
Author
There was a problem hiding this comment. Choose a reason for hiding this commentThe reason will be displayed to describe this comment to others. Learn more. для иллюстрации) можно добавить значение секретное например и его сверять) |
||
| response.sendError(HttpServletResponse.SC_BAD_REQUEST); | ||
| return; | ||
| } | ||
| UsernamePasswordAuthenticationToken authRequest = convert(request); | ||
| if (authRequest == null) { | ||
| this.logger.trace("Did not process authentication request on transform to UsernamePasswordAuthenticationToken"); | ||
| chain.doFilter(request, response); | ||
| return; | ||
| } | ||
|
|
||
| String username = authRequest.getName(); | ||
| this.logger.trace(LogMessage.format("Found username '%s'", username)); | ||
|
|
||
| Authentication authResult = this.authenticationManager.authenticate(authRequest); | ||
| SecurityContext context = this.securityContextHolderStrategy.createEmptyContext(); | ||
| context.setAuthentication(authResult); | ||
| this.securityContextHolderStrategy.setContext(context); | ||
| if (this.logger.isDebugEnabled()) { | ||
| this.logger.debug(LogMessage.format("Set SecurityContextHolder to %s", authResult)); | ||
| } | ||
| this.securityContextRepository.saveContext(context, request, response); | ||
| } catch (AuthenticationException var8) { | ||
| this.securityContextHolderStrategy.clearContext(); | ||
| this.logger.debug("Failed to process authentication request", var8); | ||
| response.sendError(HttpServletResponse.SC_FORBIDDEN); | ||
|
Owner
There was a problem hiding this comment. Choose a reason for hiding this commentThe reason will be displayed to describe this comment to others. Learn more. вместо отправки ошибки лучше пользоваться |
||
| return; | ||
| } | ||
|
|
||
| chain.doFilter(request, response); | ||
| } | ||
| chain.doFilter(request, response); | ||
|
Owner
There was a problem hiding this comment. Choose a reason for hiding this commentThe reason will be displayed to describe this comment to others. Learn more.
|
||
| } | ||
|
|
||
| private boolean checkNativeHeader(HttpServletRequest request) { | ||
| return request.getHeader(this.nativeAppHeader) != null; | ||
| } | ||
|
|
||
| private UsernamePasswordAuthenticationToken convert(HttpServletRequest request) throws IOException { | ||
| try { | ||
| var jsonRequest = this.objectMapper.readTree(request.getReader()); | ||
| var username = jsonRequest.get(defaultUsernameJsonBodyParameter).asText(); | ||
| var password= jsonRequest.get(defaultPasswordJsonBodyParameter).asText(); | ||
| if (username != null && password != null) { | ||
| return new UsernamePasswordAuthenticationToken(username, password); | ||
| } | ||
| } catch (IOException e) { | ||
| logger.error(e); | ||
| return null; | ||
| } | ||
| return null; | ||
| } | ||
|
|
||
| public RequestLoginPasswordFilter objectMapper(ObjectMapper objectMapper) { | ||
| Assert.notNull(objectMapper, "Should not be null"); | ||
| this.objectMapper = objectMapper; | ||
| return this; | ||
| } | ||
|
|
||
| public RequestLoginPasswordFilter defaultUsernameJsonBodyParameter(String defaultUsernameJsonBodyParameter) { | ||
| Assert.notNull(defaultUsernameJsonBodyParameter, "Should not be null"); | ||
| this.defaultUsernameJsonBodyParameter = defaultUsernameJsonBodyParameter; | ||
| return this; | ||
| } | ||
|
|
||
| public RequestLoginPasswordFilter defaultPasswordJsonBodyParameter(String defaultPasswordJsonBodyParameter) { | ||
| Assert.notNull(defaultPasswordJsonBodyParameter, "Should not be null"); | ||
| this.defaultPasswordJsonBodyParameter = defaultPasswordJsonBodyParameter; | ||
| return this; | ||
| } | ||
|
|
||
| public RequestLoginPasswordFilter requestMatcher(RequestMatcher requestMatcher) { | ||
| Assert.notNull(requestMatcher, "Should not be null"); | ||
| this.requestMatcher = requestMatcher; | ||
| return this; | ||
| } | ||
|
|
||
| public RequestLoginPasswordFilter authenticationManager(AuthenticationManager authenticationManager) { | ||
| Assert.notNull(authenticationManager, "Should not be null"); | ||
| this.authenticationManager = authenticationManager; | ||
| return this; | ||
| } | ||
|
|
||
| public RequestLoginPasswordFilter nativeAppHeader(String nativeAppHeader) { | ||
| Assert.notNull(nativeAppHeader, "Should not be null"); | ||
| this.nativeAppHeader = nativeAppHeader; | ||
| return this; | ||
| } | ||
| } | ||
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
Вместо своего фильтра можно использовать
AuthenticationFilter, а логику получения аутентификационных данных реализовать в классе, реализующемAuthenticationConverterThere was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
о, спасибо за замечание)
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
Честно говоря, попробовал - не получилось.
builder .addFilterAfter(requestJwtTokensFilter, ExceptionTranslationFilter.class) .addFilterAfter(authenticationFilter, ExceptionTranslationFilter.class)менял местами эти две строчки (authenticationFilter - это созданный с кастомным конвертером) - все равно в дебаггере вижу что он пытается провести конвертацию через Jwt конвертер.
Плюс, конструктор принимающий менеджер аутентификации и конвертер не дает конфигурировать путь, по которому он должен отрабатывать. Короче какая-то беда. Хотя идея переиспользовать по максимуму спринговый функционал мне нравится.