com.xlrit.gears.server.security.oauth.OAuthWebSecurityConfiguration Maven / Gradle / Ivy
The newest version!
package com.xlrit.gears.server.security.oauth;
import java.util.Collection;
import java.util.List;
import java.util.Objects;
import com.xlrit.gears.engine.security.RoleAuthority;
import com.xlrit.gears.engine.util.EngineUtils;
import com.xlrit.gears.server.security.TokenManager;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.boot.autoconfigure.condition.ConditionalOnProperty;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.security.authentication.AbstractAuthenticationToken;
import org.springframework.security.config.annotation.web.builders.HttpSecurity;
import org.springframework.security.config.http.SessionCreationPolicy;
import org.springframework.security.core.GrantedAuthority;
import org.springframework.security.oauth2.jwt.Jwt;
import org.springframework.security.oauth2.server.resource.authentication.JwtAuthenticationToken;
import org.springframework.security.web.DefaultSecurityFilterChain;
@Configuration
@ConditionalOnProperty(name = "gears.auth.mode", havingValue = "external")
public class OAuthWebSecurityConfiguration {
private static final Logger LOG = LoggerFactory.getLogger(OAuthWebSecurityConfiguration.class);
@Value("${gears.security.content-policy}")
private String contentPolicy;
@Bean
public TokenManager tokenManager() {
return new TokenManagerImpl();
}
@Bean
public DefaultSecurityFilterChain securityFilterChain(HttpSecurity http) throws Exception {
LOG.info("Applying external authentication mode using OAuth");
http.cors();
http.csrf().disable();
http.logout().disable();
http.anonymous(a -> a.principal("anonymous"));
http.sessionManagement(sm -> sm.sessionCreationPolicy(SessionCreationPolicy.STATELESS));
http.authorizeRequests(requests -> requests.anyRequest().permitAll());
http.headers()
.contentSecurityPolicy(contentPolicy)
.and()
.xssProtection()
.and()
.frameOptions().sameOrigin();
http.oauth2ResourceServer(rs ->
rs.jwt().jwtAuthenticationConverter(this::createAuthenticationToken)
);
return http.build();
}
private AbstractAuthenticationToken createAuthenticationToken(Jwt jwt) {
// extract principal
String oid = Objects.requireNonNull(jwt.getClaimAsString("oid"));
String principal = EngineUtils.uuidToUlid(oid);
// extract authorities
List roles = jwt.getClaimAsStringList("roles");
Collection extends GrantedAuthority> authorities = RoleAuthority.fromRoleNames(roles);
// create the token
LOG.debug("createAuthenticationToken: oid={}, principal={}, authorities={}", oid, principal, authorities);
return new JwtAuthenticationToken(jwt, authorities, principal);
}
}