spring-boot - OAUTH2:从客户端 UI 访问 REST 端点以保护 URI 返回anonymousUser
问题描述
我正在研究 OAUTH2 spring security,我应该从客户端 UI 访问http://localhost:8082/ui - REST 端点,这将在登录后将我带到安全 URI http://localhost:8082/secure身份验证服务器http://localhost:8081/auth/login。
但是在点击客户端 UI http://localhost:8082/ui之后,它直接将我带到http://localhost:8082/secure,而不是提示登录页面。并在安全页面上返回“anonymousUser”值。
我在下面共享我的客户端和服务器,返回值是“欢迎登录用户!==匿名用户”。如果我做错了,任何帮助都会非常感激。
我的客户端配置
@EnableOAuth2Sso
@Configuration
@EnableWebSecurity
public class OauthConfig extends WebSecurityConfigurerAdapter {
@Autowired
private OAuth2ClientContextFilter oauth2ClientContextFilter;
@Override
protected void configure(HttpSecurity http) throws Exception {
http
.authorizeRequests()
.antMatchers("/**")
.permitAll()
.antMatchers("/", "/login/**")
.permitAll()
.anyRequest()
.authenticated().and()
.httpBasic().and().addFilterAfter(oauth2ClientContextFilter, SecurityContextPersistenceFilter.class);
}
@Bean
protected OAuth2RestTemplate OAuth2RestTemplate(
OAuth2ProtectedResourceDetails resource, OAuth2ClientContext context) {
return new OAuth2RestTemplate(resource, context);
}
}
应用程序.yml
server:
port: 8082
servlet:
context-path: /ui
session:
cookieName: UISESSION
security:
oauth2:
client:
clientId: ClientId
clientSecret: secret
accessTokenUri: http://localhost:8081/auth/oauth/token
userAuthorizationUri: http://localhost:8081/auth/oauth/authorize
scope: openid
resource:
userInfoUri: http://localhost:8081/auth/rest/hello/principal
preferTokenInfo: false
应用程序属性
spring.thymeleaf.cache= false
spring.mvc.view.prefix=/
spring.mvc.view.suffix=.html
spring.autoconfigure.exclude=org.springframework.boot.autoconfigure.security.SecurityAutoConfiguration
server.port= 8082
server.servlet.session.cookie.name=UISESSION
spring.thymeleaf.mode=LEGACYHTML5
management.endpoints.web.expose=*
服务器端授权服务器
@Configuration
@EnableAuthorizationServer
public class AuthorisationServerConfig extends AuthorizationServerConfigurerAdapter {
@Autowired
private AuthenticationManager authenticationManager;
@Override
public void configure(AuthorizationServerSecurityConfigurer security) throws Exception {
// TODO Auto-generated method stub
//security.allowFormAuthenticationForClients();
security.tokenKeyAccess("permitAll()")
.checkTokenAccess("isAuthenticated()");
}
@Override
public void configure(ClientDetailsServiceConfigurer clients) throws Exception {
clients.inMemory().withClient("ClientId")//.authorities("ROLE_ADMIN")
.secret("{noop}secret")
.authorizedGrantTypes("authorization_code").scopes("user_info").autoApprove(true);
}
@Override
public void configure(AuthorizationServerEndpointsConfigurer endpoints) throws Exception {
// TODO Auto-generated method stub
endpoints.authenticationManager(authenticationManager);
}
}
服务端资源服务器
@EnableResourceServer
@Configuration
@Order(1000)
public class ResourceServerConfig extends WebSecurityConfigurerAdapter {
@Autowired
private AuthenticationManager authenticationManager;
@Autowired
private UserDetailsService customUserDetailsService;
@Autowired
public ResourceServerConfig(AuthenticationManager authenticationManager,
CustomUserDetailsService customUserDetailsService) {
this.authenticationManager = authenticationManager;
this.customUserDetailsService = customUserDetailsService;
}
@Override
protected void configure(HttpSecurity http) throws Exception {
http.requestMatchers().antMatchers("/login","/oauth/authorize").and().authorizeRequests()
.anyRequest().authenticated().and().formLogin().permitAll();
}
@Override
protected void configure(AuthenticationManagerBuilder auth) throws Exception {
auth.parentAuthenticationManager(authenticationManager).
userDetailsService(customUserDetailsService);
}
}
服务器端服务
@Service
public class CustomUserDetailsService implements UserDetailsService{
@Autowired
private UserRepository userRepository;
@Override
public UserDetails loadUserByUsername(String username) throws UsernameNotFoundException {
// TODO Auto-generated method stub
Optional<Users> userOptional= userRepository.findByName(username);
userOptional.orElseThrow(() -> new UsernameNotFoundException("user not found"));
return userOptional.map(users -> new CustomUserDetails(users)).get();
}
}
解决方案
推荐阅读
- python - python中2个日期之间的差异
- android - React Native:BLE,发现和广播(广告数据)
- javascript - JSON stringify 在有空格或非字母字符时创建下划线,为什么?
- gnuplot - gnuplot:如何避免使用填充曲线缩放到 0?
- c# - 将文件Linux服务器保存到Windows服务器时找不到路径c#的一部分
- mysql - My SQL 存储过程中的 ELSEIF 异常
- html - 如何更改 matInput 占位符的字体颜色
- dropwizard - 在 Dropwizard 2.x 中注册 ContainerRequestFilter 的推荐方法是什么?
- r - 使用 r 从 dataPreparation 包中使用 whichAreBijection 命令识别的数据框中自动删除双射列
- html - 在异步管道中设置 img src 对象 url 时防止图像闪烁