如何在Spring安全OAuth2中使用permitAll()在公共页面上共享User Principal / securityContext

时间:2017-05-02 11:34:17

标签: spring spring-security oauth-2.0 spring-session

我们使用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 个答案:

答案 0 :(得分:0)

我从user()返回了Principal对象。看下面的代码,它解决了我的问题。     @RequestMapping({ "/user", "/me" }) public Principal user(Principal principal) { return principal; }

相关问题