Skip to content

retrievingAttributes

Jim Potter edited this page Dec 14, 2021 · 3 revisions

Retrieving and using attributes

The attributes in the SAML assertion are available in various ways:

Method #1 - from the @AuthenticaionPrincipal

AttributeReportercontroller.java:

@RestController
public class AttributeReporterController {
    
    @GetMapping("/attributes")
	public String getAttributes(@AuthenticationPrincipal Saml2AuthenticatedPrincipal principal) {
		String result = "<h3>Details<h3>\n";
        result += "Name: " + principal.getName() + "<br/>\n";
        result += "sp entityID: " + principal.getRelyingPartyRegistrationId() + "<br/>\n";

        result += "Attributes:<br/>\n";
        for (String attName : principal.getAttributes().keySet()) {
            result += attName+": " + principal.getAttributes().get(attName)+"<br/>\n";
        }
	return result;
    }
}

See Saml2AuthenticatedPrincipal JavaDocs

Re-run the app, browse to http://localhost:8080, login, got to http://localhost:8080/attributes

Method 2 - via processing within the saml2Login() call

This shares code with authority processing, see later

SAMLSecurityConfig.java:

-- import static org.springframework.security.config.Customizer.withDefaults;

++     @Autowired
++     Saml2LoginSettings settings;

--           .saml2Login(withDefaults())
++           .saml2Login(settings)

so we need to define Saml2LoginSettings:

@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 {

                // do stuff...
                super.onAuthenticationSuccess(request, response, authentication);
            }
...

Where stuff could pull the assertion values from the principal and place them in session attributes:

        DefaultSaml2AuthenticatedPrincipal princ = (DefaultSaml2AuthenticatedPrincipal) authentication.getPrincipal();
        request.getSession().setAttribute("givenName", princ.getFirstAttribute("urn:oid:0.9.2342.19200300.100.1.1"));

Clone this wiki locally