首页 > 解决方案 > 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();
    }


}

标签: spring-bootspring-securityoauth-2.0spring-data-jpaspring-rest

解决方案


推荐阅读