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