如何在 Spring Security OAuth2 中使用 permitAll() 在公共页面上共享 User Principal/securityContext
Posted
技术标签:
【中文标题】如何在 Spring Security OAuth2 中使用 permitAll() 在公共页面上共享 User Principal/securityContext【英文标题】:how to share User Principal/ securityContext on Public pages with permitAll() in spring security OAuth2 【发布时间】:2017-09-29 21:59:18 【问题描述】:我们在 Spring Boot 中使用 OAuth [LDAP/社交登录] 开发了一个 SSO 应用程序。应用程序有一些公共页面和一些受保护的页面。要求是我们希望公共页面上的一些内容基于经过身份验证的用户。问题是一旦我们登录一个应用程序并访问另一个应用程序的公共页面,用户主体在公共页面上不可用,除非我们访问同一应用程序的受保护页面之一。任何实现这一目标的建议/样本,都会在这里有所帮助。下面是我的资源服务器代码。
public class SocialApplication extends WebSecurityConfigurerAdapter
@Autowired
CustomLdapAuthoritiesPopulator ldapAuthoritiesPopulator;
@Autowired
CustomLogoutSuccessHandler customLogoutSuccessHandler;
@RequestMapping( "/user", "/me" )
public Map<String, String> user(Principal principal)
Map<String, String> map = new LinkedHashMap<>();
map.put("name", principal.getName());
return map;
@Override
public void configure(WebSecurity web) throws Exception
web.ignoring().antMatchers("/page1Prv");
@Override
protected void configure(HttpSecurity http) throws Exception
http.antMatcher("/**").authorizeRequests().antMatchers("/login", "/index**", "/webjars/**").permitAll()
.anyRequest().authenticated().and().authorizeRequests().anyRequest().fullyAuthenticated().and()
.formLogin().loginPage("/login").defaultSuccessUrl("/").and().logout()
.logoutSuccessHandler(customLogoutSuccessHandler).permitAll().and().csrf()
.csrfTokenRepository(CookieCsrfTokenRepository.withHttpOnlyFalse()).and()
.addFilterBefore(ssoFilter(), BasicAuthenticationFilter.class);
//.userDetailsService(userDetailsService);
http.httpBasic().and().authorizeRequests().anyRequest().authenticated().and().csrf().disable();
@Override
protected void configure(AuthenticationManagerBuilder authenticationManagerBuilder) throws Exception
authenticationManagerBuilder.ldapAuthentication()
.contextSource()
.url("ldap://localhost:10389/dc=example,dc=com").managerDn("uid=admin,ou=system")
.managerPassword("secret").and()
.ldapAuthoritiesPopulator(ldapAuthoritiesPopulator)
.userSearchBase("ou=users").userSearchFilter("(cn=0)");
@Configuration
@EnableResourceServer
protected static class ResourceServerConfiguration extends ResourceServerConfigurerAdapter
@Override
public void configure(HttpSecurity http) throws Exception
http.antMatcher("/me").authorizeRequests().anyRequest().authenticated();
public static void main(String[] args)
SpringApplication.run(SocialApplication.class, args);
【问题讨论】:
【参考方案1】:我从 user() 返回了 Principal 对象。看下面的代码,它解决了我的问题。
@RequestMapping( "/user", "/me" )
public Principal user(Principal principal)
return principal;
【讨论】:
以上是关于如何在 Spring Security OAuth2 中使用 permitAll() 在公共页面上共享 User Principal/securityContext的主要内容,如果未能解决你的问题,请参考以下文章
如何在 spring-security-oauth 中获取经过身份验证的用户
您如何在代理后面使用 spring-security OAuth2,但仅将 ForwardedHeaderTransformer 用于 OAuth 组件
如何使用spring-security,oauth2调整实体的正确登录?
Spring Security OAuth 2:如何在 oauth/token 请求后获取访问令牌和附加数据