#java #spring-boot #spring-security #jwt-auth
#java #пружинный ботинок #spring-безопасность #jwt-аутентификация
Вопрос:
Я пытаюсь обработать токены JWT и разрешить доступ к определенным конечным точкам REST на основе ролей. Однако я хочу разрешить доступ к «/» и для анонимных пользователей. Дело в том, что это хорошо работает, если я выполняю его в eclipse / STS, но не работает, когда я запускаю jar-файл проекта, созданного с помощью maven.
MainController.java
package app.controller;
@RestController
public class MainController{
@GetMapping(value = "/", produces = MediaType.TEXT_PLAIN_VALUE)
public String index() {
return "This is Home page";
}
}
Мой WebApplication.java выглядит примерно так —
@SpringBootApplication(scanBasePackageClasses = { WebApplication.class, Endpoint.class })
@ComponentScan(basePackages = { "app.controller" })
@Import(package1.ServiceApplication.class)
public class WebApplication {
/**
* Runs the application with the given (optional) arguments.
*
* @param args Optional arguments (might be {@code null or empty}.
*/
public static void main(String[] args) {
// System.setProperty("spring.config.location",
// "classpath:/application.properties,classpath:/application-dev.properties,classpath:/application.app.properties");
SpringApplication.run(WebApplication.class, args);
}
}
Мой WebSecurityConfig выглядит следующим образом —
@EnableWebSecurity
@Configuration
class WebSecurityConfig extends WebSecurityConfigurerAdapter implements WebMvcConfigurer {
@Override
protected void configure(HttpSecurity http) throws Exception {
http.cors();
http.csrf().disable().addFilterBefore(new JWTAuthorizationFilter(), UsernamePasswordAuthenticationFilter.class)
.authorizeRequests().antMatchers("/**").permitAll()
.antMatchers(HttpMethod.GET, "/endpoint1/service1/**").permitAll()
.antMatchers(HttpMethod.GET, "/sse/register").permitAll()
.antMatchers(HttpMethod.POST, "/endpoint1/service2/**").hasAnyAuthority("Admin")
.antMatchers(HttpMethod.GET, "/").permitAll().anyRequest().authenticated();
}
@Bean
CorsConfigurationSource corsConfigurationSource() {
final UrlBasedCorsConfigurationSource source = new UrlBasedCorsConfigurationSource();
source.registerCorsConfiguration("/**", new CorsConfiguration().applyPermitDefaultValues());
return source;
}
@Override
public void addCorsMappings(CorsRegistry registry) {
registry.addMapping("/**").allowedMethods("*");
}
}
Мой JWTAuthorizationFilter выглядит следующим образом —
public class JWTAuthorizationFilter extends OncePerRequestFilter {
private final String HEADER = "Authorization";
private final String PREFIX = "Bearer ";
@Override
protected void doFilterInternal(HttpServletRequest request, HttpServletResponse response, FilterChain chain)
throws ServletException, IOException {
try {
if (checkJWTToken(request, response)) {
DecodedJWT decoded = validateToken(request);
setUpSpringAuthentication(decoded, decoded.getClaims().get("Username").asString());
} else {
SecurityContextHolder.clearContext();
}
chain.doFilter(request, response);
} catch (ExpiredJwtException | UnsupportedJwtException | MalformedJwtException e) {
response.setStatus(HttpServletResponse.SC_FORBIDDEN);
response.sendError(HttpServletResponse.SC_FORBIDDEN, e.getMessage());
return;
}
}
private DecodedJWT validateToken(HttpServletRequest request) {
String jwtToken = request.getHeader(HEADER).replace(PREFIX, "");
DecodedJWT decoded = JWT.decode(jwtToken);
return decoded;
}
private void setUpSpringAuthentication(DecodedJWT claims, String Subject) {
List<HashMap> Auth = new ArrayList<HashMap>();
Auth = claims.getClaim("UserFunctions").asList(HashMap.class);
List<String> Roles = new ArrayList<String>();
for (HashMap userFunction : Auth) {
Roles.add(userFunction.get("name").toString());
}
String allowedRoles[] = {"Admin","Moderator" };
Collection<String> intersection = CollectionUtils.intersection(Roles, Arrays.asList(allowedRoles));
if (intersection.size() > 0) {
UsernamePasswordAuthenticationToken auth = new UsernamePasswordAuthenticationToken(Subject, null,
Roles.stream().map(SimpleGrantedAuthority::new).collect(Collectors.toList()));
SecurityContextHolder.getContext().setAuthentication(auth);
} else {
throw new UnsupportedJwtException("Role Not supported");
}
}
private boolean checkJWTToken(HttpServletRequest request, HttpServletResponse res) {
String authenticationHeader = request.getHeader(HEADER);
if (authenticationHeader == null || !authenticationHeader.startsWith(PREFIX))
return false;
return true;
}
}
Я включил spring-boot-starter-web, а также в maven-plugin я указал MainController в качестве основного класса в теге execution в pom.xml .
Ошибка на консоли выглядит следующим образом —
2021-01-18 12:43:02 - Started WebApplication in 22.083 seconds (JVM running for 23.385)
2021-01-18 12:43:06 - Received: 0 records
2021-01-18 12:43:06 - Commit list: {}
2021-01-18 12:43:08 - Initializing Spring DispatcherServlet 'dispatcherServlet'
2021-01-18 12:43:08 - Initializing Servlet 'dispatcherServlet'
2021-01-18 12:43:08 - Detected StandardServletMultipartResolver
2021-01-18 12:43:08 - enableLoggingRequestDetails='false': request parameters and headers will be masked to prevent unsa
fe logging of potentially sensitive data
2021-01-18 12:43:08 - Completed initialization in 17 ms
2021-01-18 12:43:08 - / at position 1 of 12 in additional filter chain; firing Filter: 'WebAsyncManagerIntegrationFilter
'
2021-01-18 12:43:08 - / at position 2 of 12 in additional filter chain; firing Filter: 'SecurityContextPersistenceFilter
'
2021-01-18 12:43:08 - No HttpSession currently exists
2021-01-18 12:43:08 - No SecurityContext was available from the HttpSession: null. A new one will be created.
2021-01-18 12:43:08 - / at position 3 of 12 in additional filter chain; firing Filter: 'HeaderWriterFilter'
2021-01-18 12:43:08 - / at position 4 of 12 in additional filter chain; firing Filter: 'CorsFilter'
2021-01-18 12:43:08 - Mapped to de.destatis.veplus.berichtskreisverwaltung.app.controller.MainController#index()
2021-01-18 12:43:08 - Mapped to ResourceHttpRequestHandler ["classpath:/META-INF/resources/", "classpath:/resources/", "
classpath:/static/", "classpath:/public/", "/"]
2021-01-18 12:43:08 - / at position 5 of 12 in additional filter chain; firing Filter: 'LogoutFilter'
2021-01-18 12:43:08 - Trying to match using Ant [pattern='/logout', GET]
2021-01-18 12:43:08 - Checking match of request : '/'; against '/logout'
2021-01-18 12:43:08 - Trying to match using Ant [pattern='/logout', POST]
2021-01-18 12:43:08 - Request 'GET /' doesn't match 'POST /logout'
2021-01-18 12:43:08 - Trying to match using Ant [pattern='/logout', PUT]
2021-01-18 12:43:08 - Request 'GET /' doesn't match 'PUT /logout'
2021-01-18 12:43:08 - Trying to match using Ant [pattern='/logout', DELETE]
2021-01-18 12:43:08 - Request 'GET /' doesn't match 'DELETE /logout'
2021-01-18 12:43:08 - No matches found
2021-01-18 12:43:08 - / at position 6 of 12 in additional filter chain; firing Filter: 'JWTAuthorizationFilter'
2021-01-18 12:43:08 - / at position 7 of 12 in additional filter chain; firing Filter: 'RequestCacheAwareFilter'
2021-01-18 12:43:08 - saved request doesn't match
2021-01-18 12:43:08 - / at position 8 of 12 in additional filter chain; firing Filter: 'SecurityContextHolderAwareReques
tFilter'
2021-01-18 12:43:08 - / at position 9 of 12 in additional filter chain; firing Filter: 'AnonymousAuthenticationFilter'
2021-01-18 12:43:08 - Populated SecurityContextHolder with anonymous token: 'org.springframework.security.authentication
.AnonymousAuthenticationToken@b2c95650: Principal: anonymousUser; Credentials: [PROTECTED]; Authenticated: true; Details
: org.springframework.security.web.authentication.WebAuthenticationDetails@b364: RemoteIpAddress: 0:0:0:0:0:0:0:1; Sessi
onId: null; Granted Authorities: ROLE_ANONYMOUS'
2021-01-18 12:43:08 - / at position 10 of 12 in additional filter chain; firing Filter: 'SessionManagementFilter'
2021-01-18 12:43:08 - Requested session ID FB8CC99FE54AE21707059B17E94B4729 is invalid.
2021-01-18 12:43:08 - / at position 11 of 12 in additional filter chain; firing Filter: 'ExceptionTranslationFilter'
2021-01-18 12:43:08 - / at position 12 of 12 in additional filter chain; firing Filter: 'FilterSecurityInterceptor'
2021-01-18 12:43:08 - Checking match of request : '/'; against '/endpoint1/service1/**'
2021-01-18 12:43:08 - Checking match of request : '/'; against '/sse/register'
2021-01-18 12:43:08 - Request 'GET /' doesn't match 'POST /endpoint2/service2'
2021-01-18 12:43:08 - Secure object: FilterInvocation: URL: /; Attributes: [authenticated]
2021-01-18 12:43:08 - Previously Authenticated: org.springframework.security.authentication.AnonymousAuthenticationToken
@b2c95650: Principal: anonymousUser; Credentials: [PROTECTED]; Authenticated: true; Details: org.springframework.securit
y.web.authentication.WebAuthenticationDetails@b364: RemoteIpAddress: 0:0:0:0:0:0:0:1; SessionId: null; Granted Authoriti
es: ROLE_ANONYMOUS
2021-01-18 12:43:08 - Voter: org.springframework.security.web.access.expression.WebExpressionVoter@22498aa3, returned: -
1
2021-01-18 12:43:08 - Access is denied (user is anonymous); redirecting to authentication entry point
org.springframework.security.access.AccessDeniedException: Access is denied
at org.springframework.security.access.vote.AffirmativeBased.decide(AffirmativeBased.java:84)
at org.springframework.security.access.intercept.AbstractSecurityInterceptor.beforeInvocation(AbstractSecurityIn
terceptor.java:233)
at org.springframework.security.web.access.intercept.FilterSecurityInterceptor.invoke(FilterSecurityInterceptor.
java:123)
at org.springframework.security.web.access.intercept.FilterSecurityInterceptor.doFilter(FilterSecurityIntercepto
r.java:90)
at org.springframework.security.web.FilterChainProxy$VirtualFilterChain.doFilter(FilterChainProxy.java:334)
at org.springframework.security.web.access.ExceptionTranslationFilter.doFilter(ExceptionTranslationFilter.java:1
18)
at org.springframework.security.web.FilterChainProxy$VirtualFilterChain.doFilter(FilterChainProxy.java:334)
at org.springframework.security.web.session.SessionManagementFilter.doFilter(SessionManagementFilter.java:137)
at org.springframework.security.web.FilterChainProxy$VirtualFilterChain.doFilter(FilterChainProxy.java:334)
at org.springframework.security.web.authentication.AnonymousAuthenticationFilter.doFilter(AnonymousAuthenticatio
nFilter.java:111)
at org.springframework.security.web.FilterChainProxy$VirtualFilterChain.doFilter(FilterChainProxy.java:334)
at org.springframework.security.web.servletapi.SecurityContextHolderAwareRequestFilter.doFilter(SecurityContextH
olderAwareRequestFilter.java:158)
at org.springframework.security.web.FilterChainProxy$VirtualFilterChain.doFilter(FilterChainProxy.java:334)
at org.springframework.security.web.savedrequest.RequestCacheAwareFilter.doFilter(RequestCacheAwareFilter.java:6
3)
at org.springframework.security.web.FilterChainProxy$VirtualFilterChain.doFilter(FilterChainProxy.java:334)
at de.destatis.veplus.berichtskreisverwaltung.svc.model.business.berichtskreis.JWTAuthorizationFilter.doFilterIn
ternal(JWTAuthorizationFilter.java:49)
at org.springframework.web.filter.OncePerRequestFilter.doFilter(OncePerRequestFilter.java:119)
at org.springframework.security.web.FilterChainProxy$VirtualFilterChain.doFilter(FilterChainProxy.java:334)
at org.springframework.security.web.authentication.logout.LogoutFilter.doFilter(LogoutFilter.java:116)
at org.springframework.security.web.FilterChainProxy$VirtualFilterChain.doFilter(FilterChainProxy.java:334)
at org.springframework.web.filter.CorsFilter.doFilterInternal(CorsFilter.java:92)
at org.springframework.web.filter.OncePerRequestFilter.doFilter(OncePerRequestFilter.java:119)
at org.springframework.security.web.FilterChainProxy$VirtualFilterChain.doFilter(FilterChainProxy.java:334)
at org.springframework.security.web.header.HeaderWriterFilter.doHeadersAfter(HeaderWriterFilter.java:92)
at org.springframework.security.web.header.HeaderWriterFilter.doFilterInternal(HeaderWriterFilter.java:77)
at org.springframework.web.filter.OncePerRequestFilter.doFilter(OncePerRequestFilter.java:119)
at org.springframework.security.web.FilterChainProxy$VirtualFilterChain.doFilter(FilterChainProxy.java:334)
at org.springframework.security.web.context.SecurityContextPersistenceFilter.doFilter(SecurityContextPersistence
Filter.java:105)
at org.springframework.security.web.FilterChainProxy$VirtualFilterChain.doFilter(FilterChainProxy.java:334)
at org.springframework.security.web.context.request.async.WebAsyncManagerIntegrationFilter.doFilterInternal(WebA
syncManagerIntegrationFilter.java:56)
at org.springframework.web.filter.OncePerRequestFilter.doFilter(OncePerRequestFilter.java:119)
at org.springframework.security.web.FilterChainProxy$VirtualFilterChain.doFilter(FilterChainProxy.java:334)
at org.springframework.security.web.FilterChainProxy.doFilterInternal(FilterChainProxy.java:215)
at org.springframework.security.web.FilterChainProxy.doFilter(FilterChainProxy.java:178)
at org.springframework.web.filter.DelegatingFilterProxy.invokeDelegate(DelegatingFilterProxy.java:358)
at org.springframework.web.filter.DelegatingFilterProxy.doFilter(DelegatingFilterProxy.java:271)
at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:193)
at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:166)
at org.springframework.web.filter.RequestContextFilter.doFilterInternal(RequestContextFilter.java:100)
at org.springframework.web.filter.OncePerRequestFilter.doFilter(OncePerRequestFilter.java:119)
at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:193)
at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:166)
at org.springframework.web.filter.FormContentFilter.doFilterInternal(FormContentFilter.java:93)
at org.springframework.web.filter.OncePerRequestFilter.doFilter(OncePerRequestFilter.java:119)
at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:193)
at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:166)
at org.springframework.boot.actuate.metrics.web.servlet.WebMvcMetricsFilter.doFilterInternal(WebMvcMetricsFilter
.java:93)
at org.springframework.web.filter.OncePerRequestFilter.doFilter(OncePerRequestFilter.java:119)
at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:193)
at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:166)
at org.springframework.web.filter.CharacterEncodingFilter.doFilterInternal(CharacterEncodingFilter.java:201)
at org.springframework.web.filter.OncePerRequestFilter.doFilter(OncePerRequestFilter.java:119)
at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:193)
at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:166)
at org.apache.catalina.core.StandardWrapperValve.invoke(StandardWrapperValve.java:202)
at org.apache.catalina.core.StandardContextValve.invoke(StandardContextValve.java:97)
at org.apache.catalina.authenticator.AuthenticatorBase.invoke(AuthenticatorBase.java:541)
at org.apache.catalina.core.StandardHostValve.invoke(StandardHostValve.java:143)
at org.apache.catalina.valves.ErrorReportValve.invoke(ErrorReportValve.java:92)
at org.apache.catalina.core.StandardEngineValve.invoke(StandardEngineValve.java:78)
at org.apache.catalina.connector.CoyoteAdapter.service(CoyoteAdapter.java:343)
at org.apache.coyote.http11.Http11Processor.service(Http11Processor.java:374)
at org.apache.coyote.AbstractProcessorLight.process(AbstractProcessorLight.java:65)
at org.apache.coyote.AbstractProtocol$ConnectionHandler.process(AbstractProtocol.java:868)
at org.apache.tomcat.util.net.NioEndpoint$SocketProcessor.doRun(NioEndpoint.java:1590)
at org.apache.tomcat.util.net.SocketProcessorBase.run(SocketProcessorBase.java:49)
at java.base/java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1128)
at java.base/java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:628)
at org.apache.tomcat.util.threads.TaskThread$WrappingRunnable.run(TaskThread.java:61)
at java.base/java.lang.Thread.run(Thread.java:834)
2021-01-18 12:43:08 - Trying to match using NegatedRequestMatcher [requestMatcher=Ant [pattern='/**/favicon.*']]
2021-01-18 12:43:08 - Checking match of request : '/'; against '/**/favicon.*'
2021-01-18 12:43:08 - matches = true
2021-01-18 12:43:08 - Trying to match using NegatedRequestMatcher [requestMatcher=MediaTypeRequestMatcher [contentNegoti
ationStrategy=org.springframework.web.accept.ContentNegotiationManager@4743a322, matchingMediaTypes=[application/json],
useEquals=false, ignoredMediaTypes=[*/*]]]
2021-01-18 12:43:08 - httpRequestMediaTypes=[text/html, application/xhtml xml, image/avif, image/webp, image/apng, appli
cation/xml;q=0.9, application/signed-exchange;v=b3;q=0.9, */*;q=0.8]
2021-01-18 12:43:08 - Processing text/html
2021-01-18 12:43:08 - application/json .isCompatibleWith text/html = false
2021-01-18 12:43:08 - Processing application/xhtml xml
2021-01-18 12:43:08 - application/json .isCompatibleWith application/xhtml xml = false
2021-01-18 12:43:08 - Processing image/avif
2021-01-18 12:43:08 - application/json .isCompatibleWith image/avif = false
2021-01-18 12:43:08 - Processing image/webp
2021-01-18 12:43:08 - application/json .isCompatibleWith image/webp = false
2021-01-18 12:43:08 - Processing image/apng
2021-01-18 12:43:08 - application/json .isCompatibleWith image/apng = false
2021-01-18 12:43:08 - Processing application/xml;q=0.9
2021-01-18 12:43:08 - application/json .isCompatibleWith application/xml;q=0.9 = false
2021-01-18 12:43:08 - Processing application/signed-exchange;v=b3;q=0.9
2021-01-18 12:43:08 - application/json .isCompatibleWith application/signed-exchange;v=b3;q=0.9 = false
2021-01-18 12:43:08 - Processing */*;q=0.8
2021-01-18 12:43:08 - Ignoring
2021-01-18 12:43:08 - Did not match any media types
2021-01-18 12:43:08 - matches = true
2021-01-18 12:43:08 - Trying to match using NegatedRequestMatcher [requestMatcher=RequestHeaderRequestMatcher [expectedH
eaderName=X-Requested-With, expectedHeaderValue=XMLHttpRequest]]
2021-01-18 12:43:08 - matches = true
2021-01-18 12:43:08 - Trying to match using NegatedRequestMatcher [requestMatcher=MediaTypeRequestMatcher [contentNegoti
ationStrategy=org.springframework.web.accept.ContentNegotiationManager@4743a322, matchingMediaTypes=[multipart/form-data
], useEquals=false, ignoredMediaTypes=[*/*]]]
2021-01-18 12:43:08 - httpRequestMediaTypes=[text/html, application/xhtml xml, image/avif, image/webp, image/apng, appli
cation/xml;q=0.9, application/signed-exchange;v=b3;q=0.9, */*;q=0.8]
2021-01-18 12:43:08 - Processing text/html
2021-01-18 12:43:08 - multipart/form-data .isCompatibleWith text/html = false
2021-01-18 12:43:08 - Processing application/xhtml xml
2021-01-18 12:43:08 - multipart/form-data .isCompatibleWith application/xhtml xml = false
2021-01-18 12:43:08 - Processing image/avif
2021-01-18 12:43:08 - multipart/form-data .isCompatibleWith image/avif = false
2021-01-18 12:43:08 - Processing image/webp
2021-01-18 12:43:08 - multipart/form-data .isCompatibleWith image/webp = false
2021-01-18 12:43:08 - Processing image/apng
2021-01-18 12:43:08 - multipart/form-data .isCompatibleWith image/apng = false
2021-01-18 12:43:08 - Processing application/xml;q=0.9
2021-01-18 12:43:08 - multipart/form-data .isCompatibleWith application/xml;q=0.9 = false
2021-01-18 12:43:08 - Processing application/signed-exchange;v=b3;q=0.9
2021-01-18 12:43:08 - multipart/form-data .isCompatibleWith application/signed-exchange;v=b3;q=0.9 = false
2021-01-18 12:43:08 - Processing */*;q=0.8
2021-01-18 12:43:08 - Ignoring
2021-01-18 12:43:08 - Did not match any media types
2021-01-18 12:43:08 - matches = true
2021-01-18 12:43:08 - Trying to match using NegatedRequestMatcher [requestMatcher=MediaTypeRequestMatcher [contentNegoti
ationStrategy=org.springframework.web.accept.ContentNegotiationManager@4743a322, matchingMediaTypes=[text/event-stream],
useEquals=false, ignoredMediaTypes=[*/*]]]
2021-01-18 12:43:08 - httpRequestMediaTypes=[text/html, application/xhtml xml, image/avif, image/webp, image/apng, appli
cation/xml;q=0.9, application/signed-exchange;v=b3;q=0.9, */*;q=0.8]
2021-01-18 12:43:08 - Processing text/html
2021-01-18 12:43:08 - text/event-stream .isCompatibleWith text/html = false
2021-01-18 12:43:08 - Processing application/xhtml xml
2021-01-18 12:43:08 - text/event-stream .isCompatibleWith application/xhtml xml = false
2021-01-18 12:43:08 - Processing image/avif
2021-01-18 12:43:08 - text/event-stream .isCompatibleWith image/avif = false
2021-01-18 12:43:08 - Processing image/webp
2021-01-18 12:43:08 - text/event-stream .isCompatibleWith image/webp = false
2021-01-18 12:43:08 - Processing image/apng
2021-01-18 12:43:08 - text/event-stream .isCompatibleWith image/apng = false
2021-01-18 12:43:08 - Processing application/xml;q=0.9
2021-01-18 12:43:08 - text/event-stream .isCompatibleWith application/xml;q=0.9 = false
2021-01-18 12:43:08 - Processing application/signed-exchange;v=b3;q=0.9
2021-01-18 12:43:08 - text/event-stream .isCompatibleWith application/signed-exchange;v=b3;q=0.9 = false
2021-01-18 12:43:08 - Processing */*;q=0.8
2021-01-18 12:43:08 - Ignoring
2021-01-18 12:43:08 - Did not match any media types
2021-01-18 12:43:08 - matches = true
2021-01-18 12:43:08 - All requestMatchers returned true
2021-01-18 12:43:08 - DefaultSavedRequest added to Session: DefaultSavedRequest[http://localhost:8088/]
2021-01-18 12:43:08 - Calling Authentication entry point.
2021-01-18 12:43:08 - Pre-authenticated entry point called. Rejecting access
2021-01-18 12:43:08 - Not injecting HSTS header since it did not match the requestMatcher org.springframework.security.w
eb.header.writers.HstsHeaderWriter$SecureRequestMatcher@38598d07
2021-01-18 12:43:08 - SecurityContext is empty or contents are anonymous - context will not be stored in HttpSession.
2021-01-18 12:43:08 - SecurityContextHolder now cleared, as request processing completed
2021-01-18 12:43:08 - /error at position 1 of 12 in additional filter chain; firing Filter: 'WebAsyncManagerIntegrationF
ilter'
2021-01-18 12:43:08 - /error at position 2 of 12 in additional filter chain; firing Filter: 'SecurityContextPersistenceF
ilter'
2021-01-18 12:43:08 - HttpSession returned null object for SPRING_SECURITY_CONTEXT
2021-01-18 12:43:08 - No SecurityContext was available from the HttpSession: org.apache.catalina.session.StandardSession
Facade@6c44748c. A new one will be created.
2021-01-18 12:43:08 - /error at position 3 of 12 in additional filter chain; firing Filter: 'HeaderWriterFilter'
2021-01-18 12:43:08 - /error at position 4 of 12 in additional filter chain; firing Filter: 'CorsFilter'
2021-01-18 12:43:08 - /error at position 5 of 12 in additional filter chain; firing Filter: 'LogoutFilter'
2021-01-18 12:43:08 - Trying to match using Ant [pattern='/logout', GET]
2021-01-18 12:43:08 - Checking match of request : '/error'; against '/logout'
2021-01-18 12:43:08 - Trying to match using Ant [pattern='/logout', POST]
2021-01-18 12:43:08 - Request 'GET /error' doesn't match 'POST /logout'
2021-01-18 12:43:08 - Trying to match using Ant [pattern='/logout', PUT]
2021-01-18 12:43:08 - Request 'GET /error' doesn't match 'PUT /logout'
2021-01-18 12:43:08 - Trying to match using Ant [pattern='/logout', DELETE]
2021-01-18 12:43:08 - Request 'GET /error' doesn't match 'DELETE /logout'
2021-01-18 12:43:08 - No matches found
2021-01-18 12:43:08 - /error at position 6 of 12 in additional filter chain; firing Filter: 'JWTAuthorizationFilter'
2021-01-18 12:43:08 - /error at position 7 of 12 in additional filter chain; firing Filter: 'RequestCacheAwareFilter'
2021-01-18 12:43:08 - pathInfo: both null (property equals)
2021-01-18 12:43:08 - queryString: both null (property equals)
2021-01-18 12:43:08 - requestURI: arg1=/; arg2=/error (property not equals)
2021-01-18 12:43:08 - saved request doesn't match
2021-01-18 12:43:08 - /error at position 8 of 12 in additional filter chain; firing Filter: 'SecurityContextHolderAwareR
equestFilter'
2021-01-18 12:43:08 - /error at position 9 of 12 in additional filter chain; firing Filter: 'AnonymousAuthenticationFilt
er'
2021-01-18 12:43:08 - Populated SecurityContextHolder with anonymous token: 'org.springframework.security.authentication
.AnonymousAuthenticationToken@bdd0af00: Principal: anonymousUser; Credentials: [PROTECTED]; Authenticated: true; Details
: org.springframework.security.web.authentication.WebAuthenticationDetails@fffde5d4: RemoteIpAddress: 0:0:0:0:0:0:0:1; S
essionId: 0853132E10B7AFDEE30EE4F9EFF1944C; Granted Authorities: ROLE_ANONYMOUS'
2021-01-18 12:43:08 - /error at position 10 of 12 in additional filter chain; firing Filter: 'SessionManagementFilter'
2021-01-18 12:43:08 - /error at position 11 of 12 in additional filter chain; firing Filter: 'ExceptionTranslationFilter
'
2021-01-18 12:43:08 - /error at position 12 of 12 in additional filter chain; firing Filter: 'FilterSecurityInterceptor'
2021-01-18 12:43:08 - /error reached end of additional filter chain; proceeding with original chain
2021-01-18 12:43:08 - "ERROR" dispatch for GET "/error", parameters={}
2021-01-18 12:43:08 - Mapped to org.springframework.boot.autoconfigure.web.servlet.error.BasicErrorController#errorHtml(
HttpServletRequest, HttpServletResponse)
2021-01-18 12:43:08 - Opening JPA EntityManager in OpenEntityManagerInViewInterceptor
2021-01-18 12:43:09 - Selected 'text/html' given [text/html, text/html;q=0.8]
2021-01-18 12:43:09 - Closing JPA EntityManager in OpenEntityManagerInViewInterceptor
2021-01-18 12:43:09 - Exiting from "ERROR" dispatch, status 403
2021-01-18 12:43:09 - Chain processed normally
2021-01-18 12:43:09 - SecurityContext is empty or contents are anonymous - context will not be stored in HttpSession.
2021-01-18 12:43:09 - SecurityContextHolder now cleared, as request processing completed
порт определяется как 8088 в application.properties вместе с spring.mvc.dispatch-options-request=true.
Может кто-нибудь, пожалуйста, указать, какую ошибку я совершаю?
Комментарии:
1. есть ли какая-либо разница в файле конфигурации? и какие активные профили одинаковы как
eclipse
в среде, так иmaven
в окружающей среде.2. Простое любопытство, какую версию spring security вы используете?
3. @MDRuhulAmin У меня есть два профиля, определенных в pom.xml , «dev» и «prod». Значение по умолчанию — «dev». Однако я не уверен в профилях eclipse.
4. используется @akuma8, 5.3.4.
5. С spring security 5 вы можете упростить всю логику фильтрации, которую вы определили: docs.spring.io/spring-security/site/docs/current/reference /… Также, просматривая имеющиеся у нас журналы
Granted Authoriti es: ROLE_ANONYMOUS
, для обеспечения безопасности Spring пользователь не проходит проверку подлинности.