好的,开始工作了......您需要自定义 saml2Login - 用新的定制器替换 withDefaults() 方法(下面的 Saml2LoginSettings):
SAMLSecurityconfig.java:
@EnableWebSecurity
public class SAMLSecurityConfig extends WebSecurityConfigurerAdapter {
@Autowired
RelyingPartyRegistrationRepository relyingPartyRegistrationRepository;
@Autowired
Saml2LoginSettings settings;
protected void configure(HttpSecurity http) throws Exception {
RelyingPartyRegistrationResolver relyingPartyRegistrationResolver =
new DefaultRelyingPartyRegistrationResolver(this.relyingPartyRegistrationRepository);
Saml2MetadataFilter filter = new Saml2MetadataFilter(relyingPartyRegistrationResolver, new OpenSamlMetadataResolver());
http
.saml2Login(settings)
.addFilterBefore(filter, Saml2WebSsoAuthenticationFilter.class).antMatcher("/**") //
.authorizeRequests()
.antMatchers("/attributes").hasAuthority("ADMIN")
.anyRequest().authenticated();
使用 Saml2LoginSettings.java:
@Component
class Saml2LoginSettings implements Customizer <Saml2LoginConfigurer<HttpSecurity>> {
@Override
public void customize(Saml2LoginConfigurer<HttpSecurity> t) {
t.successHandler(new SavedRequestAwareAuthenticationSuccessHandler() {
@Override
public void onAuthenticationSuccess(HttpServletRequest request, HttpServletResponse response,
Authentication authentication) throws IOException, ServletException {
authentication = assignAuthorities (authentication, request);
super.onAuthenticationSuccess(request, response, authentication);
}
});
}
分配权限有点麻烦,但这是有效的:
private Authentication assignAuthorities (Authentication authentication, HttpServletRequest request) {
Collection<SimpleGrantedAuthority> oldAuthorities = (Collection<SimpleGrantedAuthority>)SecurityContextHolder.getContext()
.getAuthentication().getAuthorities();
DefaultSaml2AuthenticatedPrincipal princ = (DefaultSaml2AuthenticatedPrincipal) authentication.getPrincipal();
if (princ.getAttribute("urn:oid:1.3.6.1.4.1.5923.1.1.1.7").contains("urn:mace:dir:entitlement:common-lib-terms")) {
List<SimpleGrantedAuthority> updatedAuthorities = new ArrayList<SimpleGrantedAuthority>();
updatedAuthorities.addAll(oldAuthorities);
updatedAuthorities.add(new SimpleGrantedAuthority("ADMIN"));
Saml2Authentication sAuth = (Saml2Authentication) authentication;
sAuth = new Saml2Authentication(
(AuthenticatedPrincipal) SecurityContextHolder.getContext().getAuthentication().getPrincipal(),
sAuth.getSaml2Response(),
updatedAuthorities
);
SecurityContextHolder.getContext().setAuthentication(sAuth);
return sAuth;
}
else
return authentication;
}
示例代码here https://github.com/jim-reespotter/SpringBootSAML