У меня ниже вывод в режиме отладки для весенней безопасности Oauth2 jwt. Я могу получить токен и с помощью URL: http://192.168.1.229: 8081 / oauth / token? Grant_type = пароль и имя пользователя = jack & пароль = пароль с базовой аутентификацией c: отправлено имя пользователя и пароль. И это правильно работает в почтальоне, а также при запросе из браузера.
Используются зависимости для безопасности
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-security</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.security</groupId>
<artifactId>spring-security-jwt</artifactId>
<!-- <version>1.0.9.RELEASE</version> -->
</dependency>
<dependency>
<groupId>org.springframework.security.oauth</groupId>
<artifactId>spring-security-oauth2</artifactId>
</dependency>
Я использую Spring boot 1.5.9.Release
2020-03-05 14:41:40 DEBUG o.s.s.w.u.m.OrRequestMatcher:65 - Trying to match using Ant [pattern='/oauth/token']
2020-03-05 14:41:40 DEBUG o.s.s.w.u.m.AntPathRequestMatcher:157 - Checking match of request : '/oauth/token'; against '/oauth/token'
2020-03-05 14:41:40 DEBUG o.s.s.w.u.m.OrRequestMatcher:68 - matched
2020-03-05 14:41:40 DEBUG o.s.s.w.FilterChainProxy:325 - /oauth/token?grant_type=password&username=jack&password=password at position 1 of 11 in additional filter chain; firing Filter: 'WebAsyncManagerIntegrationFilter'
2020-03-05 14:41:40 DEBUG o.s.s.w.FilterChainProxy:325 - /oauth/token?grant_type=password&username=jack&password=password at position 2 of 11 in additional filter chain; firing Filter: 'SecurityContextPersistenceFilter'
2020-03-05 14:41:40 DEBUG o.s.s.w.FilterChainProxy:325 - /oauth/token?grant_type=password&username=jack&password=password at position 3 of 11 in additional filter chain; firing Filter: 'HeaderWriterFilter'
2020-03-05 14:41:40 DEBUG o.s.s.w.FilterChainProxy:325 - /oauth/token?grant_type=password&username=jack&password=password at position 4 of 11 in additional filter chain; firing Filter: 'LogoutFilter'
2020-03-05 14:41:40 DEBUG o.s.s.w.u.m.OrRequestMatcher:65 - Trying to match using Ant [pattern='/logout', GET]
2020-03-05 14:41:40 DEBUG o.s.s.w.u.m.AntPathRequestMatcher:137 - Request 'POST /oauth/token' doesn't match 'GET /logout
2020-03-05 14:41:40 DEBUG o.s.s.w.u.m.OrRequestMatcher:65 - Trying to match using Ant [pattern='/logout', POST]
2020-03-05 14:41:40 DEBUG o.s.s.w.u.m.AntPathRequestMatcher:157 - Checking match of request : '/oauth/token'; against '/logout'
2020-03-05 14:41:40 DEBUG o.s.s.w.u.m.OrRequestMatcher:65 - Trying to match using Ant [pattern='/logout', PUT]
2020-03-05 14:41:40 DEBUG o.s.s.w.u.m.AntPathRequestMatcher:137 - Request 'POST /oauth/token' doesn't match 'PUT /logout
2020-03-05 14:41:40 DEBUG o.s.s.w.u.m.OrRequestMatcher:65 - Trying to match using Ant [pattern='/logout', DELETE]
2020-03-05 14:41:40 DEBUG o.s.s.w.u.m.AntPathRequestMatcher:137 - Request 'POST /oauth/token' doesn't match 'DELETE /logout
2020-03-05 14:41:40 DEBUG o.s.s.w.u.m.OrRequestMatcher:72 - No matches found
2020-03-05 14:41:40 DEBUG o.s.s.w.FilterChainProxy:325 - /oauth/token?grant_type=password&username=jack&password=password at position 5 of 11 in additional filter chain; firing Filter: 'BasicAuthenticationFilter'
2020-03-05 14:41:40 DEBUG o.s.s.w.a.w.BasicAuthenticationFilter:170 - Basic Authentication Authorization header found for user 'fooClientId'
2020-03-05 14:41:40 DEBUG o.s.s.a.ProviderManager:169 - Authentication attempt using org.springframework.security.authentication.dao.DaoAuthenticationProvider
2020-03-05 14:41:40 DEBUG o.s.s.w.a.w.BasicAuthenticationFilter:183 - Authentication success: org.springframework.security.authentication.UsernamePasswordAuthenticationToken@3727aacc: Principal: org.springframework.security.core.userdetails.User@c2a3012c: Username: fooClientId; Password: [PROTECTED]; Enabled: true; AccountNonExpired: true; credentialsNonExpired: true; AccountNonLocked: true; Granted Authorities: ADMIN,ROLE_CLIENT,ROLE_TRUSTED_CLIENT,USER; Credentials: [PROTECTED]; Authenticated: true; Details: org.springframework.security.web.authentication.WebAuthenticationDetails@ffff8868: RemoteIpAddress: 192.168.1.229; SessionId: null; Granted Authorities: ADMIN, ROLE_CLIENT, ROLE_TRUSTED_CLIENT, USER
2020-03-05 14:41:40 DEBUG o.s.s.w.FilterChainProxy:325 - /oauth/token?grant_type=password&username=jack&password=password at position 6 of 11 in additional filter chain; firing Filter: 'RequestCacheAwareFilter'
2020-03-05 14:41:40 DEBUG o.s.s.w.FilterChainProxy:325 - /oauth/token?grant_type=password&username=jack&password=password at position 7 of 11 in additional filter chain; firing Filter: 'SecurityContextHolderAwareRequestFilter'
2020-03-05 14:41:40 DEBUG o.s.s.w.FilterChainProxy:325 - /oauth/token?grant_type=password&username=jack&password=password at position 8 of 11 in additional filter chain; firing Filter: 'AnonymousAuthenticationFilter'
2020-03-05 14:41:40 DEBUG o.s.s.w.a.AnonymousAuthenticationFilter:106 - SecurityContextHolder not populated with anonymous token, as it already contained: 'org.springframework.security.authentication.UsernamePasswordAuthenticationToken@3727aacc: Principal: org.springframework.security.core.userdetails.User@c2a3012c: Username: fooClientId; Password: [PROTECTED]; Enabled: true; AccountNonExpired: true; credentialsNonExpired: true; AccountNonLocked: true; Granted Authorities: ADMIN,ROLE_CLIENT,ROLE_TRUSTED_CLIENT,USER; Credentials: [PROTECTED]; Authenticated: true; Details: org.springframework.security.web.authentication.WebAuthenticationDetails@ffff8868: RemoteIpAddress: 192.168.1.229; SessionId: null; Granted Authorities: ADMIN, ROLE_CLIENT, ROLE_TRUSTED_CLIENT, USER'
2020-03-05 14:41:40 DEBUG o.s.s.w.FilterChainProxy:325 - /oauth/token?grant_type=password&username=jack&password=password at position 9 of 11 in additional filter chain; firing Filter: 'SessionManagementFilter'
2020-03-05 14:41:40 DEBUG o.s.s.w.a.s.CompositeSessionAuthenticationStrategy:87 - Delegating to org.springframework.security.web.authentication.session.ChangeSessionIdAuthenticationStrategy@8942ece
2020-03-05 14:41:40 DEBUG o.s.s.w.FilterChainProxy:325 - /oauth/token?grant_type=password&username=jack&password=password at position 10 of 11 in additional filter chain; firing Filter: 'ExceptionTranslationFilter'
2020-03-05 14:41:40 DEBUG o.s.s.w.FilterChainProxy:325 - /oauth/token?grant_type=password&username=jack&password=password at position 11 of 11 in additional filter chain; firing Filter: 'FilterSecurityInterceptor'
2020-03-05 14:41:40 DEBUG o.s.s.w.u.m.AntPathRequestMatcher:157 - Checking match of request : '/oauth/token'; against '/oauth/token'
2020-03-05 14:41:40 DEBUG o.s.s.w.a.i.FilterSecurityInterceptor:219 - Secure object: FilterInvocation: URL: /oauth/token?grant_type=password&username=jack&password=password; Attributes: [fullyAuthenticated]
2020-03-05 14:41:40 DEBUG o.s.s.w.a.i.FilterSecurityInterceptor:348 - Previously Authenticated: org.springframework.security.authentication.UsernamePasswordAuthenticationToken@3727aacc: Principal: org.springframework.security.core.userdetails.User@c2a3012c: Username: fooClientId; Password: [PROTECTED]; Enabled: true; AccountNonExpired: true; credentialsNonExpired: true; AccountNonLocked: true; Granted Authorities: ADMIN,ROLE_CLIENT,ROLE_TRUSTED_CLIENT,USER; Credentials: [PROTECTED]; Authenticated: true; Details: org.springframework.security.web.authentication.WebAuthenticationDetails@ffff8868: RemoteIpAddress: 192.168.1.229; SessionId: null; Granted Authorities: ADMIN, ROLE_CLIENT, ROLE_TRUSTED_CLIENT, USER
2020-03-05 14:41:40 DEBUG o.s.s.a.v.AffirmativeBased:66 - Voter: org.springframework.security.web.access.expression.WebExpressionVoter@67ac40e1, returned: 1
2020-03-05 14:41:40 DEBUG o.s.s.w.a.i.FilterSecurityInterceptor:243 - Authorization successful
2020-03-05 14:41:40 DEBUG o.s.s.w.a.i.FilterSecurityInterceptor:256 - RunAsManager did not change Authentication object
2020-03-05 14:41:40 DEBUG o.s.s.w.FilterChainProxy:310 - /oauth/token?grant_type=password&username=jack&password=password reached end of additional filter chain; proceeding with original chain
2020-03-05 14:41:40 DEBUG o.s.s.o.p.e.FrameworkEndpointHandlerMapping:310 - Looking up handler method for path /oauth/token
2020-03-05 14:41:40 DEBUG o.s.s.o.p.e.FrameworkEndpointHandlerMapping:317 - Returning handler method [public org.springframework.http.ResponseEntity<org.springframework.security.oauth2.common.OAuth2AccessToken> org.springframework.security.oauth2.provider.endpoint.TokenEndpoint.postAccessToken(java.security.Principal,java.util.Map<java.lang.String, java.lang.String>) throws org.springframework.web.HttpRequestMethodNotSupportedException]
2020-03-05 14:41:40 DEBUG o.s.s.o.p.p.ResourceOwnerPasswordTokenGranter:63 - Getting access token for: fooClientId
2020-03-05 14:41:40 DEBUG o.s.s.a.ProviderManager:169 - Authentication attempt using org.springframework.security.authentication.dao.DaoAuthenticationProvider
2020-03-05 14:41:40 DEBUG o.h.SQL:92 - select userinfo0_.id as id1_58_, userinfo0_.enabled as enabled2_58_, userinfo0_.password as password3_58_, userinfo0_.role as role4_58_, userinfo0_.username as username5_58_ from users userinfo0_ where userinfo0_.username=? and userinfo0_.enabled=?
2020-03-05 14:41:40 TRACE o.h.t.d.s.BasicBinder:65 - binding parameter [1] as [VARCHAR] - [jack]
2020-03-05 14:41:40 TRACE o.h.t.d.s.BasicBinder:65 - binding parameter [2] as [SMALLINT] - [1]
2020-03-05 14:41:40 DEBUG o.s.s.w.h.w.HstsHeaderWriter:130 - Not injecting HSTS header since it did not match the requestMatcher org.springframework.security.web.header.writers.HstsHeaderWriter$SecureRequestMatcher@545a789c
2020-03-05 14:41:40 DEBUG o.s.s.w.a.ExceptionTranslationFilter:117 - Chain processed normally
2020-03-05 14:41:40 DEBUG o.s.s.w.c.SecurityContextPersistenceFilter:119 - SecurityContextHolder now cleared, as request processing completed
Когда я попытался отправить токен носителя, полученный из ответа, вместе с {"access_token": "данные токена", "тип токена": "носитель", "refresh_token": "refre sh данные токена", "expires_in ": 179," scope ":" read write "," jti ":" jti data "}
Авторизация: Тип содержимого носителя: application / json http://192.168.1.229: 8081 / api / validateuser , [Метод: POST] Данные: {"useremail": "test@gmail.com", "пароль": "password123"}
Я получаю результат правильно, когда запрашиваю через почтальона, но когда запрошенный через браузер с angular 6 с (получить или опубликовать запросы), я получаю следующее: «Доступ запрещен (пользователь анонимный); перенаправление на точку входа аутентификации»
Principal: anonymousUser; Полномочия: [ЗАЩИЩЕНО]; Аутентифицировано: правда; Подробности: org.springframework.security.web.authentication. WebAuthenticationDetails@ffff8868: RemoteIpAddress: 192.168.1.229; SessionId: null; Предоставленные полномочия: ROLE_ANONYMOUS
2020-03-05 14:50:04 DEBUG o.s.s.w.u.m.OrRequestMatcher:65 - Trying to match using Ant [pattern='/oauth/token']
2020-03-05 14:50:04 DEBUG o.s.s.w.u.m.AntPathRequestMatcher:157 - Checking match of request : '/api/provider/provider_check_login'; against '/oauth/token'
2020-03-05 14:50:04 DEBUG o.s.s.w.u.m.OrRequestMatcher:65 - Trying to match using Ant [pattern='/oauth/token_key']
2020-03-05 14:50:04 DEBUG o.s.s.w.u.m.AntPathRequestMatcher:157 - Checking match of request : '/api/provider/provider_check_login'; against '/oauth/token_key'
2020-03-05 14:50:04 DEBUG o.s.s.w.u.m.OrRequestMatcher:65 - Trying to match using Ant [pattern='/oauth/check_token']
2020-03-05 14:50:04 DEBUG o.s.s.w.u.m.AntPathRequestMatcher:157 - Checking match of request : '/api/provider/provider_check_login'; against '/oauth/check_token'
2020-03-05 14:50:04 DEBUG o.s.s.w.u.m.OrRequestMatcher:72 - No matches found
2020-03-05 14:50:04 DEBUG o.s.s.w.u.m.AntPathRequestMatcher:147 - Request '/api/provider/provider_check_login' matched by universal pattern '/**'
2020-03-05 14:50:04 DEBUG o.s.s.w.FilterChainProxy:325 - /api/provider/provider_check_login at position 1 of 11 in additional filter chain; firing Filter: 'WebAsyncManagerIntegrationFilter'
2020-03-05 14:50:04 DEBUG o.s.s.w.FilterChainProxy:325 - /api/provider/provider_check_login at position 2 of 11 in additional filter chain; firing Filter: 'SecurityContextPersistenceFilter'
2020-03-05 14:50:04 DEBUG o.s.s.w.FilterChainProxy:325 - /api/provider/provider_check_login at position 3 of 11 in additional filter chain; firing Filter: 'HeaderWriterFilter'
2020-03-05 14:50:04 DEBUG o.s.s.w.FilterChainProxy:325 - /api/provider/provider_check_login at position 4 of 11 in additional filter chain; firing Filter: 'LogoutFilter'
2020-03-05 14:50:04 DEBUG o.s.s.w.u.m.OrRequestMatcher:65 - Trying to match using Ant [pattern='/logout', GET]
2020-03-05 14:50:04 DEBUG o.s.s.w.u.m.AntPathRequestMatcher:137 - Request 'OPTIONS /api/provider/provider_check_login' doesn't match 'GET /logout
2020-03-05 14:50:04 DEBUG o.s.s.w.u.m.OrRequestMatcher:65 - Trying to match using Ant [pattern='/logout', POST]
2020-03-05 14:50:04 DEBUG o.s.s.w.u.m.AntPathRequestMatcher:137 - Request 'OPTIONS /api/provider/provider_check_login' doesn't match 'POST /logout
2020-03-05 14:50:04 DEBUG o.s.s.w.u.m.OrRequestMatcher:65 - Trying to match using Ant [pattern='/logout', PUT]
2020-03-05 14:50:04 DEBUG o.s.s.w.u.m.AntPathRequestMatcher:137 - Request 'OPTIONS /api/provider/provider_check_login' doesn't match 'PUT /logout
2020-03-05 14:50:04 DEBUG o.s.s.w.u.m.OrRequestMatcher:65 - Trying to match using Ant [pattern='/logout', DELETE]
2020-03-05 14:50:04 DEBUG o.s.s.w.u.m.AntPathRequestMatcher:137 - Request 'OPTIONS /api/provider/provider_check_login' doesn't match 'DELETE /logout
2020-03-05 14:50:04 DEBUG o.s.s.w.u.m.OrRequestMatcher:72 - No matches found
2020-03-05 14:50:04 DEBUG o.s.s.w.FilterChainProxy:325 - /api/provider/provider_check_login at position 5 of 11 in additional filter chain; firing Filter: 'OAuth2AuthenticationProcessingFilter'
2020-03-05 14:50:04 DEBUG o.s.s.o.p.a.BearerTokenExtractor:54 - Token not found in headers. Trying request parameters.
2020-03-05 14:50:04 DEBUG o.s.s.o.p.a.BearerTokenExtractor:57 - Token not found in request parameters. Not an OAuth2 request.
2020-03-05 14:50:04 DEBUG o.s.s.o.p.a.OAuth2AuthenticationProcessingFilter:141 - No token in request, will continue chain.
2020-03-05 14:50:04 DEBUG o.s.s.w.FilterChainProxy:325 - /api/provider/provider_check_login at position 6 of 11 in additional filter chain; firing Filter: 'RequestCacheAwareFilter'
2020-03-05 14:50:04 DEBUG o.s.s.w.FilterChainProxy:325 - /api/provider/provider_check_login at position 7 of 11 in additional filter chain; firing Filter: 'SecurityContextHolderAwareRequestFilter'
2020-03-05 14:50:04 DEBUG o.s.s.w.FilterChainProxy:325 - /api/provider/provider_check_login at position 8 of 11 in additional filter chain; firing Filter: 'AnonymousAuthenticationFilter'
2020-03-05 14:50:04 DEBUG o.s.s.w.a.AnonymousAuthenticationFilter:100 - Populated SecurityContextHolder with anonymous token: 'org.springframework.security.authentication.AnonymousAuthenticationToken@6faaf9b0: Principal: anonymousUser; Credentials: [PROTECTED]; Authenticated: true; Details: org.springframework.security.web.authentication.WebAuthenticationDetails@ffff8868: RemoteIpAddress: 192.168.1.229; SessionId: null; Granted Authorities: ROLE_ANONYMOUS'
2020-03-05 14:50:04 DEBUG o.s.s.w.FilterChainProxy:325 - /api/provider/provider_check_login at position 9 of 11 in additional filter chain; firing Filter: 'SessionManagementFilter'
2020-03-05 14:50:04 DEBUG o.s.s.w.FilterChainProxy:325 - /api/provider/provider_check_login at position 10 of 11 in additional filter chain; firing Filter: 'ExceptionTranslationFilter'
2020-03-05 14:50:04 DEBUG o.s.s.w.FilterChainProxy:325 - /api/provider/provider_check_login at position 11 of 11 in additional filter chain; firing Filter: 'FilterSecurityInterceptor'
2020-03-05 14:50:04 DEBUG o.s.s.w.a.i.FilterSecurityInterceptor:219 - Secure object: FilterInvocation: URL: /api/provider/provider_check_login; Attributes: [#oauth2.throwOnError(authenticated)]
2020-03-05 14:50:04 DEBUG o.s.s.w.a.i.FilterSecurityInterceptor:348 - Previously Authenticated: org.springframework.security.authentication.AnonymousAuthenticationToken@6faaf9b0: Principal: anonymousUser; Credentials: [PROTECTED]; Authenticated: true; Details: org.springframework.security.web.authentication.WebAuthenticationDetails@ffff8868: RemoteIpAddress: 192.168.1.229; SessionId: null; Granted Authorities: ROLE_ANONYMOUS
2020-03-05 14:50:04 DEBUG o.s.s.a.v.AffirmativeBased:66 - Voter: org.springframework.security.web.access.expression.WebExpressionVoter@1e735191, returned: -1
2020-03-05 14:50:04 DEBUG o.s.s.w.a.ExceptionTranslationFilter:174 - 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(AbstractSecurityInterceptor.java:233)
at org.springframework.security.web.access.intercept.FilterSecurityInterceptor.invoke(FilterSecurityInterceptor.java:124)
at org.springframework.security.web.access.intercept.FilterSecurityInterceptor.doFilter(FilterSecurityInterceptor.java:91)
at org.springframework.security.web.FilterChainProxy$VirtualFilterChain.doFilter(FilterChainProxy.java:331)
at org.springframework.security.web.access.ExceptionTranslationFilter.doFilter(ExceptionTranslationFilter.java:115)
at org.springframework.security.web.FilterChainProxy$VirtualFilterChain.doFilter(FilterChainProxy.java:331)
at org.springframework.security.web.session.SessionManagementFilter.doFilter(SessionManagementFilter.java:137)
at org.springframework.security.web.FilterChainProxy$VirtualFilterChain.doFilter(FilterChainProxy.java:331)
at org.springframework.security.web.authentication.AnonymousAuthenticationFilter.doFilter(AnonymousAuthenticationFilter.java:111)
at org.springframework.security.web.FilterChainProxy$VirtualFilterChain.doFilter(FilterChainProxy.java:331)
at org.springframework.security.web.servletapi.SecurityContextHolderAwareRequestFilter.doFilter(SecurityContextHolderAwareRequestFilter.java:169)
at org.springframework.security.web.FilterChainProxy$VirtualFilterChain.doFilter(FilterChainProxy.java:331)
at org.springframework.security.web.savedrequest.RequestCacheAwareFilter.doFilter(RequestCacheAwareFilter.java:63)
at org.springframework.security.web.FilterChainProxy$VirtualFilterChain.doFilter(FilterChainProxy.java:331)
at org.springframework.security.oauth2.provider.authentication.OAuth2AuthenticationProcessingFilter.doFilter(OAuth2AuthenticationProcessingFilter.java:176)
at org.springframework.security.web.FilterChainProxy$VirtualFilterChain.doFilter(FilterChainProxy.java:331)
at org.springframework.security.web.authentication.logout.LogoutFilter.doFilter(LogoutFilter.java:121)
at org.springframework.security.web.FilterChainProxy$VirtualFilterChain.doFilter(FilterChainProxy.java:331)
at org.springframework.security.web.header.HeaderWriterFilter.doFilterInternal(HeaderWriterFilter.java:66)
at org.springframework.web.filter.OncePerRequestFilter.doFilter(OncePerRequestFilter.java:107)
at org.springframework.security.web.FilterChainProxy$VirtualFilterChain.doFilter(FilterChainProxy.java:331)
at org.springframework.security.web.context.SecurityContextPersistenceFilter.doFilter(SecurityContextPersistenceFilter.java:105)
at org.springframework.security.web.FilterChainProxy$VirtualFilterChain.doFilter(FilterChainProxy.java:331)
at org.springframework.security.web.context.request.async.WebAsyncManagerIntegrationFilter.doFilterInternal(WebAsyncManagerIntegrationFilter.java:56)
at org.springframework.web.filter.OncePerRequestFilter.doFilter(OncePerRequestFilter.java:107)
at org.springframework.security.web.FilterChainProxy$VirtualFilterChain.doFilter(FilterChainProxy.java:331)
at org.springframework.security.web.FilterChainProxy.doFilterInternal(FilterChainProxy.java:214)
at org.springframework.security.web.FilterChainProxy.doFilter(FilterChainProxy.java:177)
at org.springframework.web.filter.DelegatingFilterProxy.invokeDelegate(DelegatingFilterProxy.java:346)
at org.springframework.web.filter.DelegatingFilterProxy.doFilter(DelegatingFilterProxy.java:262)
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:197)
at org.springframework.web.filter.OncePerRequestFilter.doFilter(OncePerRequestFilter.java:107)
at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:193)
at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:166)
at org.com.ideabytes.configuration.MvcConfig$SimpleCorsFilter.doFilter(MvcConfig.java:61)
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:198)
at org.apache.catalina.core.StandardContextValve.invoke(StandardContextValve.java:96)
at org.apache.catalina.authenticator.AuthenticatorBase.invoke(AuthenticatorBase.java:478)
at org.apache.catalina.core.StandardHostValve.invoke(StandardHostValve.java:140)
at org.apache.catalina.valves.ErrorReportValve.invoke(ErrorReportValve.java:80)
at org.apache.catalina.core.StandardEngineValve.invoke(StandardEngineValve.java:87)
at org.apache.catalina.connector.CoyoteAdapter.service(CoyoteAdapter.java:342)
at org.apache.coyote.http11.Http11Processor.service(Http11Processor.java:799)
at org.apache.coyote.AbstractProcessorLight.process(AbstractProcessorLight.java:66)
at org.apache.coyote.AbstractProtocol$ConnectionHandler.process(AbstractProtocol.java:861)
at org.apache.tomcat.util.net.NioEndpoint$SocketProcessor.doRun(NioEndpoint.java:1455)
at org.apache.tomcat.util.net.SocketProcessorBase.run(SocketProcessorBase.java:49)
at java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1149)
at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:624)
at org.apache.tomcat.util.threads.TaskThread$WrappingRunnable.run(TaskThread.java:61)
at java.lang.Thread.run(Thread.java:748)
2020-03-05 14:50:04 DEBUG o.s.s.w.a.ExceptionTranslationFilter:203 - Calling Authentication entry point.
2020-03-05 14:50:04 DEBUG o.s.s.w.h.w.HstsHeaderWriter:130 - Not injecting HSTS header since it did not match the requestMatcher org.springframework.security.web.header.writers.HstsHeaderWriter$SecureRequestMatcher@77258577
2020-03-05 14:50:04 DEBUG o.s.s.o.p.e.DefaultOAuth2ExceptionRenderer:101 - Written [error="unauthorized", error_description="Full authentication is required to access this resource"] as "application/json;charset=UTF-8" using [org.springframework.http.converter.json.MappingJackson2HttpMessageConverter@7539b7f]
2020-03-05 14:50:04 DEBUG o.s.s.w.c.SecurityContextPersistenceFilter:119 - SecurityContextHolder now cleared, as request processing completed
Я сохранил security.oauth2.resource.filter-order = 3, но не использовал.
Моя конфигурация ресурса:
@Configuration
@EnableResourceServer
public class ResourceServerConfiguration extends ResourceServerConfigurerAdapter {
//private static final String RESOURCE_ID = "resource-server-rest-api";
//private static final String SECURED_READ_SCOPE = "#oauth2.hasScope('read')";
//private static final String SECURED_WRITE_SCOPE = "#oauth2.hasScope('write')";
//private static final String SECURED_PATTERN = "/secured/**";
@Override
public void configure(ResourceServerSecurityConfigurer resources) {
resources.resourceId(RESOURCE_ID);
}
@Override
public void configure(HttpSecurity http) throws Exception {
/*http.requestMatchers()
.antMatchers(SECURED_PATTERN).and().authorizeRequests()
.antMatchers(HttpMethod.POST, SECURED_PATTERN).access(SECURED_WRITE_SCOPE)
.anyRequest().access(SECURED_READ_SCOPE);*/
http.antMatcher("/**")
.authorizeRequests().anyRequest().authenticated();
}
}
Моя настройка безопасности:
@EnableWebSecurity
@EnableGlobalMethodSecurity(securedEnabled = true)
public class SecurityConfig extends WebSecurityConfigurerAdapter {
@Autowired
UserDetailsServiceImpl userDetailsService;
@Override
protected void configure(HttpSecurity http) throws Exception {
http.csrf().disable().sessionManagement().sessionCreationPolicy(SessionCreationPolicy.STATELESS).and()
.authorizeRequests().antMatchers("/oauth/token").permitAll().anyRequest().authenticated().and()
.authorizeRequests().antMatchers(HttpMethod.GET, "/user").hasRole("ADMIN");
}
@Bean
public DaoAuthenticationProvider authenticationProvider() {
DaoAuthenticationProvider provider = new DaoAuthenticationProvider();
provider.setPasswordEncoder(bCryptPasswordEncoder());
provider.setUserDetailsService(userDetailsService);
return provider;
}
// @Autowired
// public void globalUserDetails(AuthenticationManagerBuilder auth) throws Exception {
// auth.inMemoryAuthentication()
// .withUser("bill").password("abc123").roles("ADMIN").and()
// .withUser("bob").password("abc123").roles("USER");
// }
@Bean
public BCryptPasswordEncoder bCryptPasswordEncoder() {
return new BCryptPasswordEncoder();
}
@Override
@Bean
public AuthenticationManager authenticationManagerBean() throws Exception {
return super.authenticationManagerBean();
}
@Autowired
public void configureGlobal(AuthenticationManagerBuilder auth) throws Exception {
auth.authenticationProvider(authenticationProvider());
}
}
Моя конфигурация Oauth:
@Configuration
@EnableAuthorizationServer
public class OAuthConfiguration extends AuthorizationServerConfigurerAdapter {
@Autowired
@Qualifier("authenticationManagerBean")
private AuthenticationManager authenticationManager;
@Autowired
UserDetailsService userDetailsService;
@Override
public void configure(final AuthorizationServerSecurityConfigurer oauthServer) throws Exception {
oauthServer.tokenKeyAccess("permitAll()").checkTokenAccess("isAuthenticated()");
}
@Override
public void configure(ClientDetailsServiceConfigurer clients) throws Exception {
clients.inMemory()
.withClient("user").secret("secret")
.authorizedGrantTypes("password", "authorization_code", "refresh_token").scopes("read","write")
.authorities("ROLE_CLIENT", "ROLE_TRUSTED_CLIENT", "USER","ADMIN")
.autoApprove(true)
.accessTokenValiditySeconds(180)//Access token is only valid for 3 minutes.
.refreshTokenValiditySeconds(600);//Refresh token is only valid for 10 minutes.;
}
@Override
public void configure(final AuthorizationServerEndpointsConfigurer endpoints) throws Exception {
endpoints.tokenStore(tokenStore()).authenticationManager(authenticationManager).accessTokenConverter(defaultAccessTokenConverter())
.userDetailsService(userDetailsService);
}
@Bean
public TokenStore tokenStore(){
return new JwtTokenStore(defaultAccessTokenConverter());
}
@Bean
public JwtAccessTokenConverter defaultAccessTokenConverter() {
JwtAccessTokenConverter converter = new JwtAccessTokenConverter();
converter.setSigningKey("123");
return converter;
}
}