kandi background
Explore Kits

spring-security | image:https://img | Security library

 by   spring-projects Java Version: 5.7.0-RC1 License: Apache-2.0

 by   spring-projects Java Version: 5.7.0-RC1 License: Apache-2.0

Download this library from

kandi X-RAY | spring-security Summary

spring-security is a Java library typically used in Security, Spring Boot, Spring applications. spring-security has no bugs, it has no vulnerabilities, it has build file available, it has a Permissive License and it has high support. You can download it from GitHub, Maven.
Spring Security provides security services for the Spring IO Platform. Spring Security 6.0 requires Spring 6.0 as a minimum and also requires Java 17. For a detailed list of features and access to the latest release, please visit Spring projects.
Support
Support
Quality
Quality
Security
Security
License
License
Reuse
Reuse

kandi-support Support

  • spring-security has a highly active ecosystem.
  • It has 6747 star(s) with 4997 fork(s). There are 431 watchers for this library.
  • There were 9 major release(s) in the last 6 months.
  • There are 808 open issues and 8428 have been closed. On average issues are closed in 5 days. There are 24 open pull requests and 0 closed requests.
  • It has a positive sentiment in the developer community.
  • The latest version of spring-security is 5.7.0-RC1
spring-security Support
Best in #Security
Average in #Security
spring-security Support
Best in #Security
Average in #Security

quality kandi Quality

  • spring-security has 0 bugs and 0 code smells.
spring-security Quality
Best in #Security
Average in #Security
spring-security Quality
Best in #Security
Average in #Security

securitySecurity

  • spring-security has no vulnerabilities reported, and its dependent libraries have no vulnerabilities reported.
  • spring-security code analysis shows 0 unresolved vulnerabilities.
  • There are 0 security hotspots that need review.
spring-security Security
Best in #Security
Average in #Security
spring-security Security
Best in #Security
Average in #Security

license License

  • spring-security is licensed under the Apache-2.0 License. This license is Permissive.
  • Permissive licenses have the least restrictions, and you can use them in most projects.
spring-security License
Best in #Security
Average in #Security
spring-security License
Best in #Security
Average in #Security

buildReuse

  • spring-security releases are available to install and integrate.
  • Deployable package is available in Maven.
  • Build file is available. You can build the component from source.
  • Installation instructions, examples and code snippets are available.
  • It has 292355 lines of code, 23068 functions and 3371 files.
  • It has medium code complexity. Code complexity directly impacts maintainability of the code.
spring-security Reuse
Best in #Security
Average in #Security
spring-security Reuse
Best in #Security
Average in #Security
Top functions reviewed by kandi - BETA

kandi has reviewed spring-security and discovered the below as its top functions. This is intended to give you an instant insight into spring-security implemented functionality, and help decide if they suit your requirements.

  • Create session management filters .
  • Generate the HTML page for the login page .
  • Encode bytes to a byte array
  • Create filter bean definition .
  • Checks that login page is not accessible .
  • Eks key .
  • Parses filter invocations request urls .
  • Determines whether a particular permission is granted or not .
  • Performs the authorization of the given object .
  • Converts the claims set to claims set .

spring-security Key Features

Spring Security

Check out sources

copy iconCopydownload iconDownload
git clone git@github.com:spring-projects/spring-security.git

Install all spring-\* jars into your local Maven cache

copy iconCopydownload iconDownload
./gradlew publishToMavenLocal

Compile and test; build all jars, distribution zips, and docs

copy iconCopydownload iconDownload
./gradlew build

Spring Security SAML and UserDetailsService

copy iconCopydownload iconDownload
repositories {
    mavenCentral()
    maven { url "https://repo.spring.io/milestone" }
    maven { url "https://repo.spring.io/snapshot" }
    maven { url "https://build.shibboleth.net/nexus/content/repositories/releases/" }
}

dependencies {
    constraints {
        implementation "org.opensaml:opensaml-core:4.1.1"
        implementation "org.opensaml:opensaml-saml-api:4.1.1"
        implementation "org.opensaml:opensaml-saml-impl:4.1.1"
    }
    implementation 'org.springframework.boot:spring-boot-starter-security'
    implementation 'org.springframework.boot:spring-boot-starter-thymeleaf'
    implementation 'org.springframework.boot:spring-boot-starter-web'
    implementation 'org.springframework.security:spring-security-saml2-service-provider'
    implementation 'org.thymeleaf.extras:thymeleaf-extras-springsecurity6'

    testImplementation 'net.sourceforge.htmlunit:htmlunit:2.44.0'
    testImplementation 'org.springframework.boot:spring-boot-starter-test'
    testImplementation 'org.springframework.security:spring-security-test'
    testImplementation 'org.awaitility:awaitility:4.2.0'
}

How to get JWT claims in a Spring Service or Controller

copy iconCopydownload iconDownload
 .addFilterBefore(new TokenAuthenticationFilter(tokenHelper, jwtUserDetailsService), BasicAuthenticationFilter.class);
@Override
public void doFilterInternal(
        HttpServletRequest request,
        HttpServletResponse response,
        FilterChain chain
) throws IOException, ServletException {

    String username;
    String authToken = tokenHelper.getToken(request);

    if (authToken != null) {
        // get username from token
        username = tokenHelper.getUsernameFromToken(authToken);
        if (username != null) {
            // get user
            UserDetails userDetails = userDetailsService.loadUserByUsername(username);
            if (tokenHelper.validateToken(authToken, userDetails)) {
                // create authentication
                TokenBasedAuthentication authentication = new TokenBasedAuthentication(userDetails);
                authentication.setToken(authToken);
                SecurityContextHolder.getContext().setAuthentication(authentication);
            }
        }
    }
    chain.doFilter(request, response);
}
public String getToken( HttpServletRequest request ) {
    /**
     *  Getting the token from Authentication header
     *  e.g Bearer your_token
     */
    String authHeader = getAuthHeaderFromHeader( request );
    if ( authHeader != null && authHeader.startsWith("Bearer ")) {
        return authHeader.substring(7);
    }

    return null;
}
public String getUsernameFromToken(String token) {
    String username;
    try {
        final Claims claims = this.getAllClaimsFromToken(token);
        username = claims.getSubject();
    } catch (Exception e) {
        username = null;
    }
    return username;
}
private Claims getAllClaimsFromToken(String token) {
    Claims claims;
    try {
        claims = Jwts.parser()
                .setSigningKey(SECRET)
                .parseClaimsJws(token)
                .getBody();
    } catch (Exception e) {
        claims = null;
    }
    return claims;
}+
import io.jsonwebtoken.Claims;
import io.jsonwebtoken.Jwts;
import io.jsonwebtoken.SignatureAlgorithm;
import com.nimbusds.jose.JWSSigner;
import com.nimbusds.jose.JWSVerifier;
import com.nimbusds.jose.KeyLengthException;
import com.nimbusds.jose.crypto.MACSigner;
import com.nimbusds.jose.crypto.MACVerifier;
import com.nimbusds.jwt.SignedJWT;
-----------------------
 .addFilterBefore(new TokenAuthenticationFilter(tokenHelper, jwtUserDetailsService), BasicAuthenticationFilter.class);
@Override
public void doFilterInternal(
        HttpServletRequest request,
        HttpServletResponse response,
        FilterChain chain
) throws IOException, ServletException {

    String username;
    String authToken = tokenHelper.getToken(request);

    if (authToken != null) {
        // get username from token
        username = tokenHelper.getUsernameFromToken(authToken);
        if (username != null) {
            // get user
            UserDetails userDetails = userDetailsService.loadUserByUsername(username);
            if (tokenHelper.validateToken(authToken, userDetails)) {
                // create authentication
                TokenBasedAuthentication authentication = new TokenBasedAuthentication(userDetails);
                authentication.setToken(authToken);
                SecurityContextHolder.getContext().setAuthentication(authentication);
            }
        }
    }
    chain.doFilter(request, response);
}
public String getToken( HttpServletRequest request ) {
    /**
     *  Getting the token from Authentication header
     *  e.g Bearer your_token
     */
    String authHeader = getAuthHeaderFromHeader( request );
    if ( authHeader != null && authHeader.startsWith("Bearer ")) {
        return authHeader.substring(7);
    }

    return null;
}
public String getUsernameFromToken(String token) {
    String username;
    try {
        final Claims claims = this.getAllClaimsFromToken(token);
        username = claims.getSubject();
    } catch (Exception e) {
        username = null;
    }
    return username;
}
private Claims getAllClaimsFromToken(String token) {
    Claims claims;
    try {
        claims = Jwts.parser()
                .setSigningKey(SECRET)
                .parseClaimsJws(token)
                .getBody();
    } catch (Exception e) {
        claims = null;
    }
    return claims;
}+
import io.jsonwebtoken.Claims;
import io.jsonwebtoken.Jwts;
import io.jsonwebtoken.SignatureAlgorithm;
import com.nimbusds.jose.JWSSigner;
import com.nimbusds.jose.JWSVerifier;
import com.nimbusds.jose.KeyLengthException;
import com.nimbusds.jose.crypto.MACSigner;
import com.nimbusds.jose.crypto.MACVerifier;
import com.nimbusds.jwt.SignedJWT;
-----------------------
 .addFilterBefore(new TokenAuthenticationFilter(tokenHelper, jwtUserDetailsService), BasicAuthenticationFilter.class);
@Override
public void doFilterInternal(
        HttpServletRequest request,
        HttpServletResponse response,
        FilterChain chain
) throws IOException, ServletException {

    String username;
    String authToken = tokenHelper.getToken(request);

    if (authToken != null) {
        // get username from token
        username = tokenHelper.getUsernameFromToken(authToken);
        if (username != null) {
            // get user
            UserDetails userDetails = userDetailsService.loadUserByUsername(username);
            if (tokenHelper.validateToken(authToken, userDetails)) {
                // create authentication
                TokenBasedAuthentication authentication = new TokenBasedAuthentication(userDetails);
                authentication.setToken(authToken);
                SecurityContextHolder.getContext().setAuthentication(authentication);
            }
        }
    }
    chain.doFilter(request, response);
}
public String getToken( HttpServletRequest request ) {
    /**
     *  Getting the token from Authentication header
     *  e.g Bearer your_token
     */
    String authHeader = getAuthHeaderFromHeader( request );
    if ( authHeader != null && authHeader.startsWith("Bearer ")) {
        return authHeader.substring(7);
    }

    return null;
}
public String getUsernameFromToken(String token) {
    String username;
    try {
        final Claims claims = this.getAllClaimsFromToken(token);
        username = claims.getSubject();
    } catch (Exception e) {
        username = null;
    }
    return username;
}
private Claims getAllClaimsFromToken(String token) {
    Claims claims;
    try {
        claims = Jwts.parser()
                .setSigningKey(SECRET)
                .parseClaimsJws(token)
                .getBody();
    } catch (Exception e) {
        claims = null;
    }
    return claims;
}+
import io.jsonwebtoken.Claims;
import io.jsonwebtoken.Jwts;
import io.jsonwebtoken.SignatureAlgorithm;
import com.nimbusds.jose.JWSSigner;
import com.nimbusds.jose.JWSVerifier;
import com.nimbusds.jose.KeyLengthException;
import com.nimbusds.jose.crypto.MACSigner;
import com.nimbusds.jose.crypto.MACVerifier;
import com.nimbusds.jwt.SignedJWT;
-----------------------
 .addFilterBefore(new TokenAuthenticationFilter(tokenHelper, jwtUserDetailsService), BasicAuthenticationFilter.class);
@Override
public void doFilterInternal(
        HttpServletRequest request,
        HttpServletResponse response,
        FilterChain chain
) throws IOException, ServletException {

    String username;
    String authToken = tokenHelper.getToken(request);

    if (authToken != null) {
        // get username from token
        username = tokenHelper.getUsernameFromToken(authToken);
        if (username != null) {
            // get user
            UserDetails userDetails = userDetailsService.loadUserByUsername(username);
            if (tokenHelper.validateToken(authToken, userDetails)) {
                // create authentication
                TokenBasedAuthentication authentication = new TokenBasedAuthentication(userDetails);
                authentication.setToken(authToken);
                SecurityContextHolder.getContext().setAuthentication(authentication);
            }
        }
    }
    chain.doFilter(request, response);
}
public String getToken( HttpServletRequest request ) {
    /**
     *  Getting the token from Authentication header
     *  e.g Bearer your_token
     */
    String authHeader = getAuthHeaderFromHeader( request );
    if ( authHeader != null && authHeader.startsWith("Bearer ")) {
        return authHeader.substring(7);
    }

    return null;
}
public String getUsernameFromToken(String token) {
    String username;
    try {
        final Claims claims = this.getAllClaimsFromToken(token);
        username = claims.getSubject();
    } catch (Exception e) {
        username = null;
    }
    return username;
}
private Claims getAllClaimsFromToken(String token) {
    Claims claims;
    try {
        claims = Jwts.parser()
                .setSigningKey(SECRET)
                .parseClaimsJws(token)
                .getBody();
    } catch (Exception e) {
        claims = null;
    }
    return claims;
}+
import io.jsonwebtoken.Claims;
import io.jsonwebtoken.Jwts;
import io.jsonwebtoken.SignatureAlgorithm;
import com.nimbusds.jose.JWSSigner;
import com.nimbusds.jose.JWSVerifier;
import com.nimbusds.jose.KeyLengthException;
import com.nimbusds.jose.crypto.MACSigner;
import com.nimbusds.jose.crypto.MACVerifier;
import com.nimbusds.jwt.SignedJWT;
-----------------------
 .addFilterBefore(new TokenAuthenticationFilter(tokenHelper, jwtUserDetailsService), BasicAuthenticationFilter.class);
@Override
public void doFilterInternal(
        HttpServletRequest request,
        HttpServletResponse response,
        FilterChain chain
) throws IOException, ServletException {

    String username;
    String authToken = tokenHelper.getToken(request);

    if (authToken != null) {
        // get username from token
        username = tokenHelper.getUsernameFromToken(authToken);
        if (username != null) {
            // get user
            UserDetails userDetails = userDetailsService.loadUserByUsername(username);
            if (tokenHelper.validateToken(authToken, userDetails)) {
                // create authentication
                TokenBasedAuthentication authentication = new TokenBasedAuthentication(userDetails);
                authentication.setToken(authToken);
                SecurityContextHolder.getContext().setAuthentication(authentication);
            }
        }
    }
    chain.doFilter(request, response);
}
public String getToken( HttpServletRequest request ) {
    /**
     *  Getting the token from Authentication header
     *  e.g Bearer your_token
     */
    String authHeader = getAuthHeaderFromHeader( request );
    if ( authHeader != null && authHeader.startsWith("Bearer ")) {
        return authHeader.substring(7);
    }

    return null;
}
public String getUsernameFromToken(String token) {
    String username;
    try {
        final Claims claims = this.getAllClaimsFromToken(token);
        username = claims.getSubject();
    } catch (Exception e) {
        username = null;
    }
    return username;
}
private Claims getAllClaimsFromToken(String token) {
    Claims claims;
    try {
        claims = Jwts.parser()
                .setSigningKey(SECRET)
                .parseClaimsJws(token)
                .getBody();
    } catch (Exception e) {
        claims = null;
    }
    return claims;
}+
import io.jsonwebtoken.Claims;
import io.jsonwebtoken.Jwts;
import io.jsonwebtoken.SignatureAlgorithm;
import com.nimbusds.jose.JWSSigner;
import com.nimbusds.jose.JWSVerifier;
import com.nimbusds.jose.KeyLengthException;
import com.nimbusds.jose.crypto.MACSigner;
import com.nimbusds.jose.crypto.MACVerifier;
import com.nimbusds.jwt.SignedJWT;
-----------------------
 .addFilterBefore(new TokenAuthenticationFilter(tokenHelper, jwtUserDetailsService), BasicAuthenticationFilter.class);
@Override
public void doFilterInternal(
        HttpServletRequest request,
        HttpServletResponse response,
        FilterChain chain
) throws IOException, ServletException {

    String username;
    String authToken = tokenHelper.getToken(request);

    if (authToken != null) {
        // get username from token
        username = tokenHelper.getUsernameFromToken(authToken);
        if (username != null) {
            // get user
            UserDetails userDetails = userDetailsService.loadUserByUsername(username);
            if (tokenHelper.validateToken(authToken, userDetails)) {
                // create authentication
                TokenBasedAuthentication authentication = new TokenBasedAuthentication(userDetails);
                authentication.setToken(authToken);
                SecurityContextHolder.getContext().setAuthentication(authentication);
            }
        }
    }
    chain.doFilter(request, response);
}
public String getToken( HttpServletRequest request ) {
    /**
     *  Getting the token from Authentication header
     *  e.g Bearer your_token
     */
    String authHeader = getAuthHeaderFromHeader( request );
    if ( authHeader != null && authHeader.startsWith("Bearer ")) {
        return authHeader.substring(7);
    }

    return null;
}
public String getUsernameFromToken(String token) {
    String username;
    try {
        final Claims claims = this.getAllClaimsFromToken(token);
        username = claims.getSubject();
    } catch (Exception e) {
        username = null;
    }
    return username;
}
private Claims getAllClaimsFromToken(String token) {
    Claims claims;
    try {
        claims = Jwts.parser()
                .setSigningKey(SECRET)
                .parseClaimsJws(token)
                .getBody();
    } catch (Exception e) {
        claims = null;
    }
    return claims;
}+
import io.jsonwebtoken.Claims;
import io.jsonwebtoken.Jwts;
import io.jsonwebtoken.SignatureAlgorithm;
import com.nimbusds.jose.JWSSigner;
import com.nimbusds.jose.JWSVerifier;
import com.nimbusds.jose.KeyLengthException;
import com.nimbusds.jose.crypto.MACSigner;
import com.nimbusds.jose.crypto.MACVerifier;
import com.nimbusds.jwt.SignedJWT;
-----------------------
 .addFilterBefore(new TokenAuthenticationFilter(tokenHelper, jwtUserDetailsService), BasicAuthenticationFilter.class);
@Override
public void doFilterInternal(
        HttpServletRequest request,
        HttpServletResponse response,
        FilterChain chain
) throws IOException, ServletException {

    String username;
    String authToken = tokenHelper.getToken(request);

    if (authToken != null) {
        // get username from token
        username = tokenHelper.getUsernameFromToken(authToken);
        if (username != null) {
            // get user
            UserDetails userDetails = userDetailsService.loadUserByUsername(username);
            if (tokenHelper.validateToken(authToken, userDetails)) {
                // create authentication
                TokenBasedAuthentication authentication = new TokenBasedAuthentication(userDetails);
                authentication.setToken(authToken);
                SecurityContextHolder.getContext().setAuthentication(authentication);
            }
        }
    }
    chain.doFilter(request, response);
}
public String getToken( HttpServletRequest request ) {
    /**
     *  Getting the token from Authentication header
     *  e.g Bearer your_token
     */
    String authHeader = getAuthHeaderFromHeader( request );
    if ( authHeader != null && authHeader.startsWith("Bearer ")) {
        return authHeader.substring(7);
    }

    return null;
}
public String getUsernameFromToken(String token) {
    String username;
    try {
        final Claims claims = this.getAllClaimsFromToken(token);
        username = claims.getSubject();
    } catch (Exception e) {
        username = null;
    }
    return username;
}
private Claims getAllClaimsFromToken(String token) {
    Claims claims;
    try {
        claims = Jwts.parser()
                .setSigningKey(SECRET)
                .parseClaimsJws(token)
                .getBody();
    } catch (Exception e) {
        claims = null;
    }
    return claims;
}+
import io.jsonwebtoken.Claims;
import io.jsonwebtoken.Jwts;
import io.jsonwebtoken.SignatureAlgorithm;
import com.nimbusds.jose.JWSSigner;
import com.nimbusds.jose.JWSVerifier;
import com.nimbusds.jose.KeyLengthException;
import com.nimbusds.jose.crypto.MACSigner;
import com.nimbusds.jose.crypto.MACVerifier;
import com.nimbusds.jwt.SignedJWT;

JHipster - Spring. Oauth2 resource server configuration. Create resource server

copy iconCopydownload iconDownload
.oauth2ResourceServer()
    .jwt()
    .jwtAuthenticationConverter(authenticationConverter())
    .and()
.and()
    .oauth2Client();

Spring Authorization Server: How to use login form hosted on a separate application?

copy iconCopydownload iconDownload
    @Bean
    @Order(1)
    public SecurityFilterChain authorizationServerSecurityFilterChain(HttpSecurity http) throws Exception {
        OAuth2AuthorizationServerConfiguration.applyDefaultSecurity(http);
        // @formatter:off
        http
            .exceptionHandling(exceptionHandling -> exceptionHandling
                .authenticationEntryPoint(new LoginUrlAuthenticationEntryPoint("https://some-other-sso.example/login"))
            );
        // @formatter:on
        return http.build();
    }

    @Bean
    @Order(2)
    public SecurityFilterChain standardSecurityFilterChain(HttpSecurity http) throws Exception {
        // @formatter:off
        http
            .authorizeRequests(authorize -> authorize
                .anyRequest().authenticated()
            )
            .oauth2ResourceServer(OAuth2ResourceServerConfigurer::jwt);
        // @formatter:on

        return http.build();
    }

    @Bean
    public JwtDecoder jwtDecoder(PublicKey publicKey) {
        return NimbusJwtDecoder.withPublicKey((RSAPublicKey) publicKey).build();
    }

    @Bean
    public BearerTokenResolver bearerTokenResolver() {
        DefaultBearerTokenResolver bearerTokenResolver = new DefaultBearerTokenResolver();
        bearerTokenResolver.setAllowUriQueryParameter(true);
        return bearerTokenResolver;
    }
@Controller
public class SsoController {
    private AuthenticationSuccessHandler successHandler = new SavedRequestAwareAuthenticationSuccessHandler();

    @GetMapping("/login")
    public void login(HttpServletRequest request, HttpServletResponse response, Authentication authentication)
            throws ServletException, IOException {
        this.successHandler.onAuthenticationSuccess(request, response, authentication);
    }
}
-----------------------
    @Bean
    @Order(1)
    public SecurityFilterChain authorizationServerSecurityFilterChain(HttpSecurity http) throws Exception {
        OAuth2AuthorizationServerConfiguration.applyDefaultSecurity(http);
        // @formatter:off
        http
            .exceptionHandling(exceptionHandling -> exceptionHandling
                .authenticationEntryPoint(new LoginUrlAuthenticationEntryPoint("https://some-other-sso.example/login"))
            );
        // @formatter:on
        return http.build();
    }

    @Bean
    @Order(2)
    public SecurityFilterChain standardSecurityFilterChain(HttpSecurity http) throws Exception {
        // @formatter:off
        http
            .authorizeRequests(authorize -> authorize
                .anyRequest().authenticated()
            )
            .oauth2ResourceServer(OAuth2ResourceServerConfigurer::jwt);
        // @formatter:on

        return http.build();
    }

    @Bean
    public JwtDecoder jwtDecoder(PublicKey publicKey) {
        return NimbusJwtDecoder.withPublicKey((RSAPublicKey) publicKey).build();
    }

    @Bean
    public BearerTokenResolver bearerTokenResolver() {
        DefaultBearerTokenResolver bearerTokenResolver = new DefaultBearerTokenResolver();
        bearerTokenResolver.setAllowUriQueryParameter(true);
        return bearerTokenResolver;
    }
@Controller
public class SsoController {
    private AuthenticationSuccessHandler successHandler = new SavedRequestAwareAuthenticationSuccessHandler();

    @GetMapping("/login")
    public void login(HttpServletRequest request, HttpServletResponse response, Authentication authentication)
            throws ServletException, IOException {
        this.successHandler.onAuthenticationSuccess(request, response, authentication);
    }
}

How to fetch calendar events for a user using Microsoft Graph API with java

copy iconCopydownload iconDownload
AuthorizationCode authorizationCode = new AuthorizationCode(httpServletRequest.getParameter("code"));
        String currentUri = httpServletRequest.getRequestURL().toString();
        
        IAuthenticationResult result;
        ConfidentialClientApplication app;
        try {
            app = createClientApplication();

            String authCode = authorizationCode.getValue();
            Set<String> scopes = new HashSet<String>();
            scopes.add("Calendars.ReadWrite"); //see this line
            
            AuthorizationCodeParameters parameters = AuthorizationCodeParameters.builder(authCode, new URI(currentUri)).scopes(scopes)
                    .build();
            
            Future<IAuthenticationResult> future = app.acquireToken(parameters);
            result = future.get();
        } catch (ExecutionException e) {
            throw e.getCause();
        }

        if (result == null) {
            throw new ServiceUnavailableException("authentication result was null");
        }

        return result;
JWTClaimsSet claims = JWTParser.parse(result.idToken()).getJWTClaimsSet();
String accessToken = result.accessToken();
-----------------------
AuthorizationCode authorizationCode = new AuthorizationCode(httpServletRequest.getParameter("code"));
        String currentUri = httpServletRequest.getRequestURL().toString();
        
        IAuthenticationResult result;
        ConfidentialClientApplication app;
        try {
            app = createClientApplication();

            String authCode = authorizationCode.getValue();
            Set<String> scopes = new HashSet<String>();
            scopes.add("Calendars.ReadWrite"); //see this line
            
            AuthorizationCodeParameters parameters = AuthorizationCodeParameters.builder(authCode, new URI(currentUri)).scopes(scopes)
                    .build();
            
            Future<IAuthenticationResult> future = app.acquireToken(parameters);
            result = future.get();
        } catch (ExecutionException e) {
            throw e.getCause();
        }

        if (result == null) {
            throw new ServiceUnavailableException("authentication result was null");
        }

        return result;
JWTClaimsSet claims = JWTParser.parse(result.idToken()).getJWTClaimsSet();
String accessToken = result.accessToken();

Calling javac the way Maven does

copy iconCopydownload iconDownload
stockapp-spring-boot (master)$ mvn clean compile 
[INFO] Scanning for projects...
[INFO] ------------------------------------------------------------------------
[INFO] Reactor Build Order:
[INFO] 
[INFO] stockapp-spring-boot                                               [pom]
[INFO] stockapp                                                           [jar]
[INFO] 
[INFO] -------------< it.raffaele.esposito:stockapp-spring-boot >--------------
[INFO] Building stockapp-spring-boot 1.2.2-SNAPSHOT                       [1/2]
[INFO] --------------------------------[ pom ]---------------------------------
[INFO] 
[INFO] --- maven-clean-plugin:2.5:clean (default-clean) @ stockapp-spring-boot ---

 ...

[INFO] --- maven-resources-plugin:3.2.0:resources (default-resources) @ stockapp ---
[INFO] Using 'UTF-8' encoding to copy filtered resources.
[INFO] Using 'UTF-8' encoding to copy filtered properties files.
[INFO] Copying 14 resources
[INFO] The encoding used to copy filtered properties files have not been set. This means that the same encoding will be used to copy filtered properties files as when copying other filtered resources. This might not be what you want! Run your build with --debug to see which files might be affected. Read more at https://maven.apache.org/plugins/maven-resources-plugin/examples/filtering-properties-files.html
[INFO] 
[INFO] --- maven-resources-plugin:3.2.0:copy-resources (Copy Vue frontend into Spring Boot target static folder) @ stockapp ---
[INFO] Using 'UTF-8' encoding to copy filtered resources.
[INFO] Using 'UTF-8' encoding to copy filtered properties files.
[INFO] Copying 8 resources
[INFO] 
[INFO] --- maven-compiler-plugin:3.7.0:compile (default-compile) @ stockapp ---
[INFO] Changes detected - recompiling the module!
[INFO] Compiling 27 source files to stockapp-spring-boot/stockapp/target/classes
[INFO] stockapp-spring-boot/stockapp/src/main/java/it/raffaele/esposito/app/service/MappingFunctions.java: stockapp-spring-boot/stockapp/src/main/java/it/raffaele/esposito/app/service/MappingFunctions.java uses or overrides a deprecated API.
[INFO] stockapp-spring-boot/stockapp/src/main/java/it/raffaele/esposito/app/service/MappingFunctions.java: Recompile with -Xlint:deprecation for details.
[INFO] ------------------------------------------------------------------------
[INFO] Reactor Summary for stockapp-spring-boot 1.2.2-SNAPSHOT:
[INFO] 
[INFO] stockapp-spring-boot ............................... SUCCESS [  0.090 s]
[INFO] stockapp ........................................... SUCCESS [ 21.988 s]
[INFO] ------------------------------------------------------------------------
[INFO] BUILD SUCCESS
[INFO] ------------------------------------------------------------------------
[INFO] Total time:  22.339 s
[INFO] Finished at: 2022-01-17T20:12:05+01:00
[INFO] ------------------------------------------------------------------------

Java 17 Cannot invoke &quot;java.lang.reflect.Method.invoke(Object, Object[])&quot; because com.sun.xml.bind.v2.runtime.reflect.opt.Injector.defineClass is null

copy iconCopydownload iconDownload
<dependency>
        <groupId>com.sun.xml.bind</groupId>
        <artifactId>jaxb-impl</artifactId>
        <version>2.3.1</version>
    </dependency>
    <dependency>
        <groupId>com.sun.xml.messaging.saaj</groupId>
        <artifactId>saaj-impl</artifactId>
        <version>1.5.1</version>
    </dependency>
-----------------------
<dependency>
    <groupId>com.sun.xml.bind</groupId>
    <artifactId>jaxb-impl</artifactId>
    <version>3.0.2</version>
</dependency>

An Authentication object was not found in the SecurityContext - Spring 5

copy iconCopydownload iconDownload
    @Override
    protected void configure(HttpSecurity httpSecurity) throws Exception {
        httpSecurity.csrf().disable().authorizeRequests()
                .anyRequest().permitAll();

    }
-----------------------
@Configuration
@EnableGlobalMethodSecurity(prePostEnabled = false, securedEnabled = true, proxyTargetClass = true)
public class MethodSecurityConfig extends GlobalMethodSecurityConfiguration {

}
@Configuration
@EnableGlobalMethodSecurity(prePostEnabled = false, jsr250Enabled = true, proxyTargetClass = true)
public class MethodSecurityConfig extends GlobalMethodSecurityConfiguration {

}
-----------------------
@Configuration
@EnableGlobalMethodSecurity(prePostEnabled = false, securedEnabled = true, proxyTargetClass = true)
public class MethodSecurityConfig extends GlobalMethodSecurityConfiguration {

}
@Configuration
@EnableGlobalMethodSecurity(prePostEnabled = false, jsr250Enabled = true, proxyTargetClass = true)
public class MethodSecurityConfig extends GlobalMethodSecurityConfiguration {

}
-----------------------
@RunWith(SpringJUnit4ClassRunner.class) // 1.
@ContextConfiguration // 2.
public class WithMockUserTests { ...
@Test(expected = AuthenticationCredentialsNotFoundException.class)
public void getMessageUnauthenticated() {
   messageService.getMessage();
}
-----------------------
@RunWith(SpringJUnit4ClassRunner.class) // 1.
@ContextConfiguration // 2.
public class WithMockUserTests { ...
@Test(expected = AuthenticationCredentialsNotFoundException.class)
public void getMessageUnauthenticated() {
   messageService.getMessage();
}

OAUTH2 user service with Custom Authentication Providers

copy iconCopydownload iconDownload
@Controller
public class Tenant1HomeController {

    @GetMapping("/tenant1/home")
    public String home() {
        return "tenant1Home";
    }

}
@Controller
public class Tenant2HomeController {

    @GetMapping("/tenant2/home")
    public String home() {
        return "tenant2Home";
    }

}
@Configuration
public class Tenant1SecurityConfiguration extends WebSecurityConfigurerAdapter {

    @Override
    protected void configure(HttpSecurity http) throws Exception {
        http
                .csrf().disable()
                .authorizeRequests()
                .antMatchers("/login**").permitAll()
                .antMatchers("/manage/**").permitAll()
                .antMatchers("/api/auth-info").permitAll()
                .antMatchers("/api/**").authenticated()
                .antMatchers("/management/health").permitAll()
                .antMatchers("/management/info").permitAll()
                .antMatchers("/management/prometheus").permitAll()
                .antMatchers("/management/**").hasAuthority("ADMIN")
                .antMatchers("/tenant1/**").authenticated()
                .and()
                .oauth2Login()
                .and()
                .cors()
                .disable();
    }
}
@Order(90)
@Configuration
public class Tenant2SecurityConfiguration extends WebSecurityConfigurerAdapter {

    @Override
    protected void configure(HttpSecurity http) throws Exception {
        http.requestMatcher(new AntPathRequestMatcher("/tenant2/**"))
                .csrf()
                .disable()
                .authorizeRequests()
                .antMatchers("/tenant2/**").hasAuthority("BASIC_USER")
                .and()
                .httpBasic();
        http.cors().disable();
    }

    @Override
    protected void configure(AuthenticationManagerBuilder auth) throws Exception {
        auth.inMemoryAuthentication()
                .withUser("user")
                .password("{noop}password")
                .roles("BASIC_USER");
    }
}
spring:
  security:
    oauth2:
      client:
        registration:
          keycloak:
            client-id: myclient
            client-secret: c6dce03e-ea13-4b76-8aab-c876f5c2c1d9
        provider:
          keycloak:
            issuer-uri: http://localhost:8180/auth/realms/myrealm
@Configuration
public class Tenant1SecurityConfiguration extends WebSecurityConfigurerAdapter {

    @Override
    protected void configure(HttpSecurity http) throws Exception {
        http.
            ...
            .and()
            .oauth2Login()
            .and()
            ...
            
@Order(90)
@Configuration
public class Tenant2SecurityConfiguration extends WebSecurityConfigurerAdapter {

    @Override
    protected void configure(HttpSecurity http) throws Exception {
        ...
    }

    @Override
    protected void configure(AuthenticationManagerBuilder auth) throws Exception {
        auth.userDetailsService(XXX)
-----------------------
@Controller
public class Tenant1HomeController {

    @GetMapping("/tenant1/home")
    public String home() {
        return "tenant1Home";
    }

}
@Controller
public class Tenant2HomeController {

    @GetMapping("/tenant2/home")
    public String home() {
        return "tenant2Home";
    }

}
@Configuration
public class Tenant1SecurityConfiguration extends WebSecurityConfigurerAdapter {

    @Override
    protected void configure(HttpSecurity http) throws Exception {
        http
                .csrf().disable()
                .authorizeRequests()
                .antMatchers("/login**").permitAll()
                .antMatchers("/manage/**").permitAll()
                .antMatchers("/api/auth-info").permitAll()
                .antMatchers("/api/**").authenticated()
                .antMatchers("/management/health").permitAll()
                .antMatchers("/management/info").permitAll()
                .antMatchers("/management/prometheus").permitAll()
                .antMatchers("/management/**").hasAuthority("ADMIN")
                .antMatchers("/tenant1/**").authenticated()
                .and()
                .oauth2Login()
                .and()
                .cors()
                .disable();
    }
}
@Order(90)
@Configuration
public class Tenant2SecurityConfiguration extends WebSecurityConfigurerAdapter {

    @Override
    protected void configure(HttpSecurity http) throws Exception {
        http.requestMatcher(new AntPathRequestMatcher("/tenant2/**"))
                .csrf()
                .disable()
                .authorizeRequests()
                .antMatchers("/tenant2/**").hasAuthority("BASIC_USER")
                .and()
                .httpBasic();
        http.cors().disable();
    }

    @Override
    protected void configure(AuthenticationManagerBuilder auth) throws Exception {
        auth.inMemoryAuthentication()
                .withUser("user")
                .password("{noop}password")
                .roles("BASIC_USER");
    }
}
spring:
  security:
    oauth2:
      client:
        registration:
          keycloak:
            client-id: myclient
            client-secret: c6dce03e-ea13-4b76-8aab-c876f5c2c1d9
        provider:
          keycloak:
            issuer-uri: http://localhost:8180/auth/realms/myrealm
@Configuration
public class Tenant1SecurityConfiguration extends WebSecurityConfigurerAdapter {

    @Override
    protected void configure(HttpSecurity http) throws Exception {
        http.
            ...
            .and()
            .oauth2Login()
            .and()
            ...
            
@Order(90)
@Configuration
public class Tenant2SecurityConfiguration extends WebSecurityConfigurerAdapter {

    @Override
    protected void configure(HttpSecurity http) throws Exception {
        ...
    }

    @Override
    protected void configure(AuthenticationManagerBuilder auth) throws Exception {
        auth.userDetailsService(XXX)
-----------------------
@Controller
public class Tenant1HomeController {

    @GetMapping("/tenant1/home")
    public String home() {
        return "tenant1Home";
    }

}
@Controller
public class Tenant2HomeController {

    @GetMapping("/tenant2/home")
    public String home() {
        return "tenant2Home";
    }

}
@Configuration
public class Tenant1SecurityConfiguration extends WebSecurityConfigurerAdapter {

    @Override
    protected void configure(HttpSecurity http) throws Exception {
        http
                .csrf().disable()
                .authorizeRequests()
                .antMatchers("/login**").permitAll()
                .antMatchers("/manage/**").permitAll()
                .antMatchers("/api/auth-info").permitAll()
                .antMatchers("/api/**").authenticated()
                .antMatchers("/management/health").permitAll()
                .antMatchers("/management/info").permitAll()
                .antMatchers("/management/prometheus").permitAll()
                .antMatchers("/management/**").hasAuthority("ADMIN")
                .antMatchers("/tenant1/**").authenticated()
                .and()
                .oauth2Login()
                .and()
                .cors()
                .disable();
    }
}
@Order(90)
@Configuration
public class Tenant2SecurityConfiguration extends WebSecurityConfigurerAdapter {

    @Override
    protected void configure(HttpSecurity http) throws Exception {
        http.requestMatcher(new AntPathRequestMatcher("/tenant2/**"))
                .csrf()
                .disable()
                .authorizeRequests()
                .antMatchers("/tenant2/**").hasAuthority("BASIC_USER")
                .and()
                .httpBasic();
        http.cors().disable();
    }

    @Override
    protected void configure(AuthenticationManagerBuilder auth) throws Exception {
        auth.inMemoryAuthentication()
                .withUser("user")
                .password("{noop}password")
                .roles("BASIC_USER");
    }
}
spring:
  security:
    oauth2:
      client:
        registration:
          keycloak:
            client-id: myclient
            client-secret: c6dce03e-ea13-4b76-8aab-c876f5c2c1d9
        provider:
          keycloak:
            issuer-uri: http://localhost:8180/auth/realms/myrealm
@Configuration
public class Tenant1SecurityConfiguration extends WebSecurityConfigurerAdapter {

    @Override
    protected void configure(HttpSecurity http) throws Exception {
        http.
            ...
            .and()
            .oauth2Login()
            .and()
            ...
            
@Order(90)
@Configuration
public class Tenant2SecurityConfiguration extends WebSecurityConfigurerAdapter {

    @Override
    protected void configure(HttpSecurity http) throws Exception {
        ...
    }

    @Override
    protected void configure(AuthenticationManagerBuilder auth) throws Exception {
        auth.userDetailsService(XXX)
-----------------------
@Controller
public class Tenant1HomeController {

    @GetMapping("/tenant1/home")
    public String home() {
        return "tenant1Home";
    }

}
@Controller
public class Tenant2HomeController {

    @GetMapping("/tenant2/home")
    public String home() {
        return "tenant2Home";
    }

}
@Configuration
public class Tenant1SecurityConfiguration extends WebSecurityConfigurerAdapter {

    @Override
    protected void configure(HttpSecurity http) throws Exception {
        http
                .csrf().disable()
                .authorizeRequests()
                .antMatchers("/login**").permitAll()
                .antMatchers("/manage/**").permitAll()
                .antMatchers("/api/auth-info").permitAll()
                .antMatchers("/api/**").authenticated()
                .antMatchers("/management/health").permitAll()
                .antMatchers("/management/info").permitAll()
                .antMatchers("/management/prometheus").permitAll()
                .antMatchers("/management/**").hasAuthority("ADMIN")
                .antMatchers("/tenant1/**").authenticated()
                .and()
                .oauth2Login()
                .and()
                .cors()
                .disable();
    }
}
@Order(90)
@Configuration
public class Tenant2SecurityConfiguration extends WebSecurityConfigurerAdapter {

    @Override
    protected void configure(HttpSecurity http) throws Exception {
        http.requestMatcher(new AntPathRequestMatcher("/tenant2/**"))
                .csrf()
                .disable()
                .authorizeRequests()
                .antMatchers("/tenant2/**").hasAuthority("BASIC_USER")
                .and()
                .httpBasic();
        http.cors().disable();
    }

    @Override
    protected void configure(AuthenticationManagerBuilder auth) throws Exception {
        auth.inMemoryAuthentication()
                .withUser("user")
                .password("{noop}password")
                .roles("BASIC_USER");
    }
}
spring:
  security:
    oauth2:
      client:
        registration:
          keycloak:
            client-id: myclient
            client-secret: c6dce03e-ea13-4b76-8aab-c876f5c2c1d9
        provider:
          keycloak:
            issuer-uri: http://localhost:8180/auth/realms/myrealm
@Configuration
public class Tenant1SecurityConfiguration extends WebSecurityConfigurerAdapter {

    @Override
    protected void configure(HttpSecurity http) throws Exception {
        http.
            ...
            .and()
            .oauth2Login()
            .and()
            ...
            
@Order(90)
@Configuration
public class Tenant2SecurityConfiguration extends WebSecurityConfigurerAdapter {

    @Override
    protected void configure(HttpSecurity http) throws Exception {
        ...
    }

    @Override
    protected void configure(AuthenticationManagerBuilder auth) throws Exception {
        auth.userDetailsService(XXX)
-----------------------
@Controller
public class Tenant1HomeController {

    @GetMapping("/tenant1/home")
    public String home() {
        return "tenant1Home";
    }

}
@Controller
public class Tenant2HomeController {

    @GetMapping("/tenant2/home")
    public String home() {
        return "tenant2Home";
    }

}
@Configuration
public class Tenant1SecurityConfiguration extends WebSecurityConfigurerAdapter {

    @Override
    protected void configure(HttpSecurity http) throws Exception {
        http
                .csrf().disable()
                .authorizeRequests()
                .antMatchers("/login**").permitAll()
                .antMatchers("/manage/**").permitAll()
                .antMatchers("/api/auth-info").permitAll()
                .antMatchers("/api/**").authenticated()
                .antMatchers("/management/health").permitAll()
                .antMatchers("/management/info").permitAll()
                .antMatchers("/management/prometheus").permitAll()
                .antMatchers("/management/**").hasAuthority("ADMIN")
                .antMatchers("/tenant1/**").authenticated()
                .and()
                .oauth2Login()
                .and()
                .cors()
                .disable();
    }
}
@Order(90)
@Configuration
public class Tenant2SecurityConfiguration extends WebSecurityConfigurerAdapter {

    @Override
    protected void configure(HttpSecurity http) throws Exception {
        http.requestMatcher(new AntPathRequestMatcher("/tenant2/**"))
                .csrf()
                .disable()
                .authorizeRequests()
                .antMatchers("/tenant2/**").hasAuthority("BASIC_USER")
                .and()
                .httpBasic();
        http.cors().disable();
    }

    @Override
    protected void configure(AuthenticationManagerBuilder auth) throws Exception {
        auth.inMemoryAuthentication()
                .withUser("user")
                .password("{noop}password")
                .roles("BASIC_USER");
    }
}
spring:
  security:
    oauth2:
      client:
        registration:
          keycloak:
            client-id: myclient
            client-secret: c6dce03e-ea13-4b76-8aab-c876f5c2c1d9
        provider:
          keycloak:
            issuer-uri: http://localhost:8180/auth/realms/myrealm
@Configuration
public class Tenant1SecurityConfiguration extends WebSecurityConfigurerAdapter {

    @Override
    protected void configure(HttpSecurity http) throws Exception {
        http.
            ...
            .and()
            .oauth2Login()
            .and()
            ...
            
@Order(90)
@Configuration
public class Tenant2SecurityConfiguration extends WebSecurityConfigurerAdapter {

    @Override
    protected void configure(HttpSecurity http) throws Exception {
        ...
    }

    @Override
    protected void configure(AuthenticationManagerBuilder auth) throws Exception {
        auth.userDetailsService(XXX)
-----------------------
@Controller
public class Tenant1HomeController {

    @GetMapping("/tenant1/home")
    public String home() {
        return "tenant1Home";
    }

}
@Controller
public class Tenant2HomeController {

    @GetMapping("/tenant2/home")
    public String home() {
        return "tenant2Home";
    }

}
@Configuration
public class Tenant1SecurityConfiguration extends WebSecurityConfigurerAdapter {

    @Override
    protected void configure(HttpSecurity http) throws Exception {
        http
                .csrf().disable()
                .authorizeRequests()
                .antMatchers("/login**").permitAll()
                .antMatchers("/manage/**").permitAll()
                .antMatchers("/api/auth-info").permitAll()
                .antMatchers("/api/**").authenticated()
                .antMatchers("/management/health").permitAll()
                .antMatchers("/management/info").permitAll()
                .antMatchers("/management/prometheus").permitAll()
                .antMatchers("/management/**").hasAuthority("ADMIN")
                .antMatchers("/tenant1/**").authenticated()
                .and()
                .oauth2Login()
                .and()
                .cors()
                .disable();
    }
}
@Order(90)
@Configuration
public class Tenant2SecurityConfiguration extends WebSecurityConfigurerAdapter {

    @Override
    protected void configure(HttpSecurity http) throws Exception {
        http.requestMatcher(new AntPathRequestMatcher("/tenant2/**"))
                .csrf()
                .disable()
                .authorizeRequests()
                .antMatchers("/tenant2/**").hasAuthority("BASIC_USER")
                .and()
                .httpBasic();
        http.cors().disable();
    }

    @Override
    protected void configure(AuthenticationManagerBuilder auth) throws Exception {
        auth.inMemoryAuthentication()
                .withUser("user")
                .password("{noop}password")
                .roles("BASIC_USER");
    }
}
spring:
  security:
    oauth2:
      client:
        registration:
          keycloak:
            client-id: myclient
            client-secret: c6dce03e-ea13-4b76-8aab-c876f5c2c1d9
        provider:
          keycloak:
            issuer-uri: http://localhost:8180/auth/realms/myrealm
@Configuration
public class Tenant1SecurityConfiguration extends WebSecurityConfigurerAdapter {

    @Override
    protected void configure(HttpSecurity http) throws Exception {
        http.
            ...
            .and()
            .oauth2Login()
            .and()
            ...
            
@Order(90)
@Configuration
public class Tenant2SecurityConfiguration extends WebSecurityConfigurerAdapter {

    @Override
    protected void configure(HttpSecurity http) throws Exception {
        ...
    }

    @Override
    protected void configure(AuthenticationManagerBuilder auth) throws Exception {
        auth.userDetailsService(XXX)
-----------------------
@Controller
public class Tenant1HomeController {

    @GetMapping("/tenant1/home")
    public String home() {
        return "tenant1Home";
    }

}
@Controller
public class Tenant2HomeController {

    @GetMapping("/tenant2/home")
    public String home() {
        return "tenant2Home";
    }

}
@Configuration
public class Tenant1SecurityConfiguration extends WebSecurityConfigurerAdapter {

    @Override
    protected void configure(HttpSecurity http) throws Exception {
        http
                .csrf().disable()
                .authorizeRequests()
                .antMatchers("/login**").permitAll()
                .antMatchers("/manage/**").permitAll()
                .antMatchers("/api/auth-info").permitAll()
                .antMatchers("/api/**").authenticated()
                .antMatchers("/management/health").permitAll()
                .antMatchers("/management/info").permitAll()
                .antMatchers("/management/prometheus").permitAll()
                .antMatchers("/management/**").hasAuthority("ADMIN")
                .antMatchers("/tenant1/**").authenticated()
                .and()
                .oauth2Login()
                .and()
                .cors()
                .disable();
    }
}
@Order(90)
@Configuration
public class Tenant2SecurityConfiguration extends WebSecurityConfigurerAdapter {

    @Override
    protected void configure(HttpSecurity http) throws Exception {
        http.requestMatcher(new AntPathRequestMatcher("/tenant2/**"))
                .csrf()
                .disable()
                .authorizeRequests()
                .antMatchers("/tenant2/**").hasAuthority("BASIC_USER")
                .and()
                .httpBasic();
        http.cors().disable();
    }

    @Override
    protected void configure(AuthenticationManagerBuilder auth) throws Exception {
        auth.inMemoryAuthentication()
                .withUser("user")
                .password("{noop}password")
                .roles("BASIC_USER");
    }
}
spring:
  security:
    oauth2:
      client:
        registration:
          keycloak:
            client-id: myclient
            client-secret: c6dce03e-ea13-4b76-8aab-c876f5c2c1d9
        provider:
          keycloak:
            issuer-uri: http://localhost:8180/auth/realms/myrealm
@Configuration
public class Tenant1SecurityConfiguration extends WebSecurityConfigurerAdapter {

    @Override
    protected void configure(HttpSecurity http) throws Exception {
        http.
            ...
            .and()
            .oauth2Login()
            .and()
            ...
            
@Order(90)
@Configuration
public class Tenant2SecurityConfiguration extends WebSecurityConfigurerAdapter {

    @Override
    protected void configure(HttpSecurity http) throws Exception {
        ...
    }

    @Override
    protected void configure(AuthenticationManagerBuilder auth) throws Exception {
        auth.userDetailsService(XXX)

How to authenticate a ldap user from any ldap server (except embedded server) using bind authentication mechanism in spring security

copy iconCopydownload iconDownload
@Component
public class CustomAuthoritiesPopulator implements LdapAuthoritiesPopulator {

    @Override
    public Collection<? extends GrantedAuthority> getGrantedAuthorities(DirContextOperations dco, String string) {
        Set<GrantedAuthority> grantedAuthorities = new HashSet<>();
        grantedAuthorities.add(new SimpleGrantedAuthority("ADMIN"));
        return grantedAuthorities;
    }
    
}
@Autowired
CustomAuthoritiesPopulator authoritiespopulator;
// I have mentioned only configure() method here, others code will be as it is

@Override
  public void configure(AuthenticationManagerBuilder auth) throws Exception {
    auth
    .ldapAuthentication()     
    .contextSource()
    .url("ServerUrl")
    .managerDn("BindUserDN") 
    .managerPassword("BindUserPassword")
    .and()
    .ldapAuthoritiesPopulator(authoritiespopulator)
    .userSearchFilter("sAMAccountName=UserName")
    
  }

@Bean
LdapContextSource ldapContextSource() {
   LdapContextSource ldapContextSource = new LdapContextSource();
   ldapContextSource.setUrl("ServerUrl");
   ldapContextSource.setUserDn("BindUserDN");
   dapContextSource.setPassword("BindUserPassword");
   ldapContextSource.afterPropertiesSet();
}

@Bean
public LdapAuthoritiesPopulator ldapAuthoritiesPopulator() throws Exception { 
DefaultLdapAuthoritiesPopulator authoritiespopulator= new DefaultLdapAuthoritiesPopulator(ldapContextSource(), "base");
        authoritiespopulator.setIgnorePartialResultException(true);
        return authoritiespopulator;
    }

@Override
  public void configure(AuthenticationManagerBuilder auth) throws Exception {
    auth
    .ldapAuthentication()     
    .contextSource()
    .url("ServerUrl")
    .managerDn("BindUserDN") 
    .managerPassword("BindUserPassword")
    .and()
    .ldapAuthoritiesPopulator(authoritiespopulator)
    .userSearchFilter("sAMAccountName=UserName")
    
  }
-----------------------
@Component
public class CustomAuthoritiesPopulator implements LdapAuthoritiesPopulator {

    @Override
    public Collection<? extends GrantedAuthority> getGrantedAuthorities(DirContextOperations dco, String string) {
        Set<GrantedAuthority> grantedAuthorities = new HashSet<>();
        grantedAuthorities.add(new SimpleGrantedAuthority("ADMIN"));
        return grantedAuthorities;
    }
    
}
@Autowired
CustomAuthoritiesPopulator authoritiespopulator;
// I have mentioned only configure() method here, others code will be as it is

@Override
  public void configure(AuthenticationManagerBuilder auth) throws Exception {
    auth
    .ldapAuthentication()     
    .contextSource()
    .url("ServerUrl")
    .managerDn("BindUserDN") 
    .managerPassword("BindUserPassword")
    .and()
    .ldapAuthoritiesPopulator(authoritiespopulator)
    .userSearchFilter("sAMAccountName=UserName")
    
  }

@Bean
LdapContextSource ldapContextSource() {
   LdapContextSource ldapContextSource = new LdapContextSource();
   ldapContextSource.setUrl("ServerUrl");
   ldapContextSource.setUserDn("BindUserDN");
   dapContextSource.setPassword("BindUserPassword");
   ldapContextSource.afterPropertiesSet();
}

@Bean
public LdapAuthoritiesPopulator ldapAuthoritiesPopulator() throws Exception { 
DefaultLdapAuthoritiesPopulator authoritiespopulator= new DefaultLdapAuthoritiesPopulator(ldapContextSource(), "base");
        authoritiespopulator.setIgnorePartialResultException(true);
        return authoritiespopulator;
    }

@Override
  public void configure(AuthenticationManagerBuilder auth) throws Exception {
    auth
    .ldapAuthentication()     
    .contextSource()
    .url("ServerUrl")
    .managerDn("BindUserDN") 
    .managerPassword("BindUserPassword")
    .and()
    .ldapAuthoritiesPopulator(authoritiespopulator)
    .userSearchFilter("sAMAccountName=UserName")
    
  }
-----------------------
@Component
public class CustomAuthoritiesPopulator implements LdapAuthoritiesPopulator {

    @Override
    public Collection<? extends GrantedAuthority> getGrantedAuthorities(DirContextOperations dco, String string) {
        Set<GrantedAuthority> grantedAuthorities = new HashSet<>();
        grantedAuthorities.add(new SimpleGrantedAuthority("ADMIN"));
        return grantedAuthorities;
    }
    
}
@Autowired
CustomAuthoritiesPopulator authoritiespopulator;
// I have mentioned only configure() method here, others code will be as it is

@Override
  public void configure(AuthenticationManagerBuilder auth) throws Exception {
    auth
    .ldapAuthentication()     
    .contextSource()
    .url("ServerUrl")
    .managerDn("BindUserDN") 
    .managerPassword("BindUserPassword")
    .and()
    .ldapAuthoritiesPopulator(authoritiespopulator)
    .userSearchFilter("sAMAccountName=UserName")
    
  }

@Bean
LdapContextSource ldapContextSource() {
   LdapContextSource ldapContextSource = new LdapContextSource();
   ldapContextSource.setUrl("ServerUrl");
   ldapContextSource.setUserDn("BindUserDN");
   dapContextSource.setPassword("BindUserPassword");
   ldapContextSource.afterPropertiesSet();
}

@Bean
public LdapAuthoritiesPopulator ldapAuthoritiesPopulator() throws Exception { 
DefaultLdapAuthoritiesPopulator authoritiespopulator= new DefaultLdapAuthoritiesPopulator(ldapContextSource(), "base");
        authoritiespopulator.setIgnorePartialResultException(true);
        return authoritiespopulator;
    }

@Override
  public void configure(AuthenticationManagerBuilder auth) throws Exception {
    auth
    .ldapAuthentication()     
    .contextSource()
    .url("ServerUrl")
    .managerDn("BindUserDN") 
    .managerPassword("BindUserPassword")
    .and()
    .ldapAuthoritiesPopulator(authoritiespopulator)
    .userSearchFilter("sAMAccountName=UserName")
    
  }
-----------------------
@Component
public class CustomAuthoritiesPopulator implements LdapAuthoritiesPopulator {

    @Override
    public Collection<? extends GrantedAuthority> getGrantedAuthorities(DirContextOperations dco, String string) {
        Set<GrantedAuthority> grantedAuthorities = new HashSet<>();
        grantedAuthorities.add(new SimpleGrantedAuthority("ADMIN"));
        return grantedAuthorities;
    }
    
}
@Autowired
CustomAuthoritiesPopulator authoritiespopulator;
// I have mentioned only configure() method here, others code will be as it is

@Override
  public void configure(AuthenticationManagerBuilder auth) throws Exception {
    auth
    .ldapAuthentication()     
    .contextSource()
    .url("ServerUrl")
    .managerDn("BindUserDN") 
    .managerPassword("BindUserPassword")
    .and()
    .ldapAuthoritiesPopulator(authoritiespopulator)
    .userSearchFilter("sAMAccountName=UserName")
    
  }

@Bean
LdapContextSource ldapContextSource() {
   LdapContextSource ldapContextSource = new LdapContextSource();
   ldapContextSource.setUrl("ServerUrl");
   ldapContextSource.setUserDn("BindUserDN");
   dapContextSource.setPassword("BindUserPassword");
   ldapContextSource.afterPropertiesSet();
}

@Bean
public LdapAuthoritiesPopulator ldapAuthoritiesPopulator() throws Exception { 
DefaultLdapAuthoritiesPopulator authoritiespopulator= new DefaultLdapAuthoritiesPopulator(ldapContextSource(), "base");
        authoritiespopulator.setIgnorePartialResultException(true);
        return authoritiespopulator;
    }

@Override
  public void configure(AuthenticationManagerBuilder auth) throws Exception {
    auth
    .ldapAuthentication()     
    .contextSource()
    .url("ServerUrl")
    .managerDn("BindUserDN") 
    .managerPassword("BindUserPassword")
    .and()
    .ldapAuthoritiesPopulator(authoritiespopulator)
    .userSearchFilter("sAMAccountName=UserName")
    
  }

Community Discussions

Trending Discussions on spring-security
  • Spring Security SAML and UserDetailsService
  • How to get JWT claims in a Spring Service or Controller
  • JHipster - Spring. Oauth2 resource server configuration. Create resource server
  • Spring Authorization Server: How to use login form hosted on a separate application?
  • How to fetch calendar events for a user using Microsoft Graph API with java
  • Calling javac the way Maven does
  • Java 17 Cannot invoke &quot;java.lang.reflect.Method.invoke(Object, Object[])&quot; because com.sun.xml.bind.v2.runtime.reflect.opt.Injector.defineClass is null
  • An Authentication object was not found in the SecurityContext - Spring 5
  • Spring aspects woven by AspectJ compiler working in Maven, but not in IntelliJ IDEA
  • OAUTH2 user service with Custom Authentication Providers
Trending Discussions on spring-security

QUESTION

Spring Security SAML and UserDetailsService

Asked 2022-Apr-01 at 10:02

I am integrating SAML into a Spring Boot application using the implementation built into Spring Security 5.6. Much of the online help references the now deprecated external library implementation (https://github.com/spring-projects/spring-security-saml) so I am following this document:

https://docs.spring.io/spring-security/reference/servlet/saml2/login/index.html

I have this interaction working and I am authenticating from SAML now. Here is the configuration:

spring:
  security:
    saml2:
      relyingparty:
        registration:
          adfs:
            signing:
              credentials:
                - private-key-location: "file:///C:/tmp/keys/private.key"
                  certificate-location: "file:///C:/tmp/keys/public.crt"
            identityprovider:
              entity-id: << SNIPPED >>
              verification.credentials:
                - certificate-location: "classpath:saml-certificate/adfs.crt"
              singlesignon:
                url: << SNIPPED >>
                sign-request: true

The code looks like this now:

@Configuration
@EnableWebSecurity
public class WebSecurityConfig extends WebSecurityConfigurerAdapter {

    private final RelyingPartyRegistrationRepository _relyingPartyRegistrationRepository;

    @Autowired
    public WebSecurityConfig(RelyingPartyRegistrationRepository relyingPartyRegistrationRepository {
        _relyingPartyRegistrationRepository = relyingPartyRegistrationRepository;
    }

    @Override
    protected void configure(HttpSecurity http) throws Exception {
        // add auto-generation of ServiceProvider Metadata at {baseUrl}/saml2/service-provider-metadata/ims-adfs
        RelyingPartyRegistrationResolver relyingPartyRegistrationResolver = new DefaultRelyingPartyRegistrationResolver(_relyingPartyRegistrationRepository);
        Saml2MetadataFilter filter = new Saml2MetadataFilter(relyingPartyRegistrationResolver, new OpenSamlMetadataResolver());

        http
                .authorizeRequests()
                .antMatchers("/seer.ico", "/monitor", "/**/check").permitAll()
                .anyRequest().authenticated()
                .and().sessionManagement()
                .and().csrf().ignoringAntMatchers("/servers/**/searches")
                .and()
                .saml2Login(withDefaults())
                .saml2Logout(withDefaults())
                .addFilterBefore(filter, Saml2WebSsoAuthenticationFilter.class);
    }

}

The issue is that I need to remap the user details to set up correct roles and also limit the logins to users who have the correct Linux permissions. The permissions are being correcting returned in the assertion; I just need to verify they are correct or fail the login.

The Spring Security documentation has a section on coordinating with a UserDetailsService which seems like exactly what I need.

https://docs.spring.io/spring-security/reference/servlet/saml2/login/authentication.html#servlet-saml2login-opensamlauthenticationprovider-userdetailsservice

However when I implement it like the example, I now get the following error from Spring:

No assertions found in response.

Here is the updated code:

@Configuration
@EnableWebSecurity
public class WebSecurityConfig extends WebSecurityConfigurerAdapter {

    private final RelyingPartyRegistrationRepository _relyingPartyRegistrationRepository;

    private final AuthenticationService _userDetailsService;

    @Autowired
    public WebSecurityConfig(RelyingPartyRegistrationRepository relyingPartyRegistrationRepository, AuthenticationService userDetailsService) {
        _relyingPartyRegistrationRepository = relyingPartyRegistrationRepository;
        _userDetailsService = userDetailsService;
    }

    @Override
    protected void configure(HttpSecurity http) throws Exception {
         OpenSaml4AuthenticationProvider authenticationProvider = new OpenSaml4AuthenticationProvider();
         authenticationProvider.setResponseAuthenticationConverter(responseToken -> {
             Saml2Authentication authentication = OpenSaml4AuthenticationProvider.createDefaultResponseAuthenticationConverter().convert(responseToken);

             Assertion assertion = responseToken.getResponse().getAssertions().get(0);
             String username = assertion.getSubject().getNameID().getValue();

             UserDetails userDetails = _userDetailsService.loadUserByUsername(username);
             authentication.setDetails(userDetails);

             return authentication;
         });

        // add auto-generation of ServiceProvider Metadata at {baseUrl}/saml2/service-provider-metadata/ims-adfs
        RelyingPartyRegistrationResolver relyingPartyRegistrationResolver = new DefaultRelyingPartyRegistrationResolver(_relyingPartyRegistrationRepository);
        Saml2MetadataFilter filter = new Saml2MetadataFilter(relyingPartyRegistrationResolver, new OpenSamlMetadataResolver());

        http
                .authorizeRequests()
                .antMatchers("/seer.ico", "/monitor", "/**/check").permitAll()
                .anyRequest().authenticated()
                .and().sessionManagement()
                .and().csrf().ignoringAntMatchers("/servers/**/searches")
                .and()
                .saml2Login(saml2 -> saml2.authenticationManager(new ProviderManager(authenticationProvider)))
                .saml2Logout(withDefaults())
                .addFilterBefore(filter, Saml2WebSsoAuthenticationFilter.class);
    }
}

So basically this gets a correct response from SAML:

.saml2Login(withDefaults())

and when I switch it to this then the SAML response is missing the Assertion:

.saml2Login(saml2 -> saml2.authenticationManager(new ProviderManager(authenticationProvider)))

I've been looking all over for other solutions but like I said there are very few examples that don't use the old deprecated SAML library for Spring.

Any thoughts?

ANSWER

Answered 2022-Apr-01 at 10:02

Check if Spring Boot is importing version 3 and version 4 of Open SAML. If it is use only version 4.

Spring Security Samples has an example for SAML2. The build.gradle in the project contains the following:

repositories {
    mavenCentral()
    maven { url "https://repo.spring.io/milestone" }
    maven { url "https://repo.spring.io/snapshot" }
    maven { url "https://build.shibboleth.net/nexus/content/repositories/releases/" }
}

dependencies {
    constraints {
        implementation "org.opensaml:opensaml-core:4.1.1"
        implementation "org.opensaml:opensaml-saml-api:4.1.1"
        implementation "org.opensaml:opensaml-saml-impl:4.1.1"
    }
    implementation 'org.springframework.boot:spring-boot-starter-security'
    implementation 'org.springframework.boot:spring-boot-starter-thymeleaf'
    implementation 'org.springframework.boot:spring-boot-starter-web'
    implementation 'org.springframework.security:spring-security-saml2-service-provider'
    implementation 'org.thymeleaf.extras:thymeleaf-extras-springsecurity6'

    testImplementation 'net.sourceforge.htmlunit:htmlunit:2.44.0'
    testImplementation 'org.springframework.boot:spring-boot-starter-test'
    testImplementation 'org.springframework.security:spring-security-test'
    testImplementation 'org.awaitility:awaitility:4.2.0'
}

Source https://stackoverflow.com/questions/71622213

Community Discussions, Code Snippets contain sources that include Stack Exchange Network

Vulnerabilities

No vulnerabilities reported

Install spring-security

See Hello Spring Security to get started with a "Hello, World" application.

Support

Be sure to read the Spring Security Reference. Extensive JavaDoc for the Spring Security code is also available in the Spring Security API Documentation.

DOWNLOAD this Library from

Find, review, and download reusable Libraries, Code Snippets, Cloud APIs from
over 430 million Knowledge Items
Find more libraries
Reuse Solution Kits and Libraries Curated by Popular Use Cases

Save this library and start creating your kit

Explore Related Topics

Share this Page

share link
Find, review, and download reusable Libraries, Code Snippets, Cloud APIs from
over 430 million Knowledge Items
Find more libraries
Reuse Solution Kits and Libraries Curated by Popular Use Cases

Save this library and start creating your kit

  • © 2022 Open Weaver Inc.