|
| 1 | +package com.baeldung.spring.security.x509; |
| 2 | + |
| 3 | +import org.springframework.boot.SpringApplication; |
| 4 | +import org.springframework.boot.autoconfigure.SpringBootApplication; |
| 5 | +import org.springframework.context.annotation.Bean; |
| 6 | +import org.springframework.security.config.annotation.method.configuration.EnableGlobalMethodSecurity; |
| 7 | +import org.springframework.security.config.annotation.web.builders.HttpSecurity; |
| 8 | +import org.springframework.security.config.annotation.web.configuration.EnableWebSecurity; |
| 9 | +import org.springframework.security.config.annotation.web.configuration.WebSecurityConfigurerAdapter; |
| 10 | +import org.springframework.security.core.authority.AuthorityUtils; |
| 11 | +import org.springframework.security.core.userdetails.User; |
| 12 | +import org.springframework.security.core.userdetails.UserDetails; |
| 13 | +import org.springframework.security.core.userdetails.UserDetailsService; |
| 14 | +import org.springframework.security.core.userdetails.UsernameNotFoundException; |
| 15 | + |
| 16 | +@SpringBootApplication |
| 17 | +@EnableWebSecurity |
| 18 | +@EnableGlobalMethodSecurity(prePostEnabled = true) |
| 19 | +public class X509AuthenticationServer extends WebSecurityConfigurerAdapter { |
| 20 | + public static void main(String[] args) { |
| 21 | + SpringApplication.run(X509AuthenticationServer.class, args); |
| 22 | + } |
| 23 | + |
| 24 | + @Override |
| 25 | + protected void configure(HttpSecurity http) throws Exception { |
| 26 | + http.authorizeRequests().anyRequest().authenticated() |
| 27 | + .and() |
| 28 | + .x509().subjectPrincipalRegex("CN=(.*?)(?:,|$)").userDetailsService(userDetailsService()); |
| 29 | + } |
| 30 | + |
| 31 | + @Bean |
| 32 | + public UserDetailsService userDetailsService() { |
| 33 | + return new UserDetailsService() { |
| 34 | + @Override |
| 35 | + public UserDetails loadUserByUsername(String username) throws UsernameNotFoundException { |
| 36 | + if (username.equals("cid")) { |
| 37 | + return new User(username, "", AuthorityUtils.commaSeparatedStringToAuthorityList("ROLE_USER")); |
| 38 | + } |
| 39 | + throw new UsernameNotFoundException("User not found!"); |
| 40 | + } |
| 41 | + }; |
| 42 | + } |
| 43 | +} |
0 commit comments