我的 spring 授权服务器依赖项:-
<dependency>
<groupId>org.springframework.security</groupId>
<artifactId>spring-security-oauth2-authorization-server</artifactId>
<version>1.0.0</version>
</dependency>
授权服务器的SecurityConfig类:-
公共类 SecurityConfig {
@Autowired
private JwtAuthenticationEntryPoint authenticationEntryPoint;
@Bean
@Order(1)
public SecurityFilterChain asSecurityFilterChain(HttpSecurity http) throws Exception {
OAuth2AuthorizationServerConfiguration.applyDefaultSecurity(http);
http.getConfigurer(OAuth2AuthorizationServerConfigurer.class)
.authorizationEndpoint(a -> a.authenticationProviders(getAuthorizationEndPoints()))
.oidc(Customizer.withDefaults());
http.exceptionHandling(exception -> exception
.authenticationEntryPoint(authenticationEntryPoint));
return http.build();
}
@Bean
@Order(2)
public SecurityFilterChain appSecurityFilterChain(HttpSecurity http) throws Exception {
http.csrf().disable();
http.cors(c -> c.configurationSource(
request -> {
CorsConfiguration config = new CorsConfiguration();
config.addAllowedOrigin(request.getHeader("Origin"));
config.setAllowedMethods(List.of("GET", "POST", "DELETE", "LINK", "UNLINK", "PATCH", "PUT", "OPTIONS"));
config.setAllowedHeaders(List.of("Content-Type, Accept, X-Requested-With, remember-me"));
config.setAllowCredentials(true);
config.setExposedHeaders(List.of("Authorization"));
config.setMaxAge(3600L);
return config;
}
));
http
.httpBasic().disable()
.formLogin().disable()
.authorizeHttpRequests()
.requestMatchers("/authenticate").permitAll()
.anyRequest().authenticated();
return http.build();
}
}
问题:-
它抛出
2023-05-16T15:31:51.127+05:30 TRACE 63279 --- [nio-7171-exec-4] o.s.s.w.a.ExceptionTranslationFilter:发送 AnonymousAuthenticationToken [Principal=anonymousUser,Credentials=[PROTECTED],Authenticated=true,Details= WebAuthenticationDetails [RemoteIpAddress=0:0:0:0:0:0:0:1, SessionId=null], Granted Authorities=[ROLE_ANONYMOUS]] 到身份验证入口点,因为访问被拒绝
org.springframework.security.access.AccessDeniedException:拒绝访问 在 org.springframework.security.web.access.intercept.AuthorizationFilter.doFilter(AuthorizationFilter.java:98) ~[spring-security-web-6.0.3.jar:6.0.3]
当我使用 formlogin() 时,它用于重定向到 HTTP://localhost:7171/login 并询问用户名和密码并返回 authorization_code 需要在下面输入“http://localhost:7171/oauth2 /token " 给出 OAuth2 令牌。 如何将它与 UI 集成。
如何编写自定义身份验证来进行身份验证并提供 oauth2 令牌?
您的授权服务器应配置表单登录(它负责对用户进行身份验证),并且您的体系结构中的 OAuth2 客户端应该使用
Authorization code
流程(使用 PKCE)在涉及用户时获取令牌。
您的前端不应访问用户凭据(包含登录名和密码的表单)。出于安全原因,
password
和 implicit
流程均已弃用。
OAuth2 客户端应该使用一个库来存储令牌并处理您遇到的所有重定向问题。
目前至少有 2 个选项来定义什么是 OAuth2 客户端:
Authorization
访问令牌的 Bearer
标头替换会话 cookie现在经常首选第二个选项,因为:
HttpOnly
)spring-cloud-gateway
可以配置为 BFF:使用 spring-boot-starter-oauth2-client
并使用 TokenRelay
过滤器。我写了一个教程那里.