Spring Security SSL. Авторизация с помощью сертификата. – Блог – Tune IT

Spring Security SSL. Авторизация с помощью сертификата. - Блог - Tune IT Сертификаты

– spring security ssl. авторизация с помощью сертификата. – александр пашнин – tune it

Добрый день.

Сегодня мы рассмотрим такую возможность Spring security, как аутентификация пользователей с помощью TLS сертификата. Так называемая mutual authentication.

Для начала сгенерируем сертификаты для клиента и сервера. Примеров того, как это сделать в интернете достаточно, приведём один из них.

Генерируем сертификат сервера

Генерируем RSA ключ сервера

openssl genrsa -aes256 -out serverprivate.key 2048

Генерируем CA сертификат с использоваие данного ключа. Большинство полей можно заполнить на ваше усмотрение, кроме поля CN, который должен быть равен домену, который мы хотим защитить. В нашем случае – это localhost.

openssl req -x509 -new -nodes -key serverprivate.key -sha256 -days 1024 -out serverCA.crt

Импортируем сертификат в Java truststore. Задаём дефолтный пароль changeit

keytool -import -file serverCA.crt -alias serverCA -keystore truststore.jks

Экспортируем сертификат в keystore, пароль снова changeit

openssl pkcs12 -export -in serverCA.crt -inkey serverprivate.key -certfile serverCA.crt -out keystore.p12

Генерируем клиентский сертификат.

Создаём приватный ключ и запрос на получение сертификата. В поле CN указываем имя пользвателя. В нашем случае CN=’Alex.Pashnin’.

openssl genrsa -aes256 -out clientprivate.key 2048
openssl req -new -key clientprivate.key -out client.csr

Создаём сертификат.

openssl x509 -req -in client.csr -CA serverCA.crt -CAkey serverprivate.key -CAcreateserial -out client.crt -days 365 -sha256

Перейдём к созданию тестового приложения

Воспользуемся для этого gradle.

gradle.build

//Плангин для быстрого старта Spring Boot приложений. Работает только с gradle версии 4.4 .
//В случае проблем с версией закомментировать, выполнить gradle wrapper --gradle-version=4.10.2
//и раскомментировать обратно
plugins {
    id 'org.springframework.boot' version '2.1.0.RELEASE'
}

apply plugin: 'java'
apply plugin: 'io.spring.dependency-management'

repositories {
    jcenter()
    mavenCentral()
}

dependencies {
    compile 'org.slf4j:slf4j-api:1.7.21'
    compile 'org.springframework.boot:spring-boot-starter-security:2.1.0.RELEASE'
    compile 'org.springframework.boot:spring-boot-starter-web:2.1.0.RELEASE'
}

Далее создадим главный класс приложения

@EnableWebSecurity
@SpringBootApplication
@EnableGlobalMethodSecurity(prePostEnabled = true)
public class CertAuthServer extends WebSecurityConfigurerAdapter {
    public static void main(String[] args) {
        SpringApplication.run(CertAuthServer.class, args);
    }

    @Override
    protected void configure(HttpSecurity http) throws Exception {
        http.authorizeRequests().anyRequest().authenticated()
                .and().csrf().disable()
                .x509()
                .subjectPrincipalRegex("CN=(.*?),")
                .userDetailsService(userDetailsService());
    }

    @Bean
    public UserDetailsService userDetailsService() {
        return new UserDetailsService() {
            @Override
            public UserDetails loadUserByUsername(String username) {
                if (username.equals("Alex.Pashnin")) {
                    return new User(username, "",
                            AuthorityUtils
                                    .commaSeparatedStringToAuthorityList("ROLE_USER"));
                }
                return null;
            }
        };
    }
}

Создадим простой веб котроллер, который будет приветствовать авторизованного пользователя.

@RestController
@RequestMapping(value = "/test")
public class TestController {
    @PreAuthorize("hasAuthority('ROLE_USER')")
    @GetMapping("/hello")
    public String hello(Principal principal) {
        UserDetails currentUser
                = (UserDetails) ((Authentication) principal).getPrincipal();
        return "Hello "   currentUser.getUsername() "!";
    }
}

Конфигурационный файл application.properties

server.ssl.key-store = classpath:keystore.p12
server.ssl.trust-store = classpath:truststore.jks
server.ssl.trust-store-password = changeit
server.ssl.key-store-password = changeit
server.ssl.key-password = changeit
server.ssl.protocol = TLS
server.ssl.key-alias = 1
server.ssl.client-auth = need
server.ssl.enabled = true
server.port = 8443

Поскольку я не задал алиас для серверного ключа, посмотрим его в хранилище. Необходимое нам поле – Alias name, его и задаём в server.ssl.key-alias.

$ keytool -v -list -keystore keystore.p12 
Enter keystore password:  
Keystore type: JKS
Keystore provider: SUN

Your keystore contains 1 entry

Alias name: 1
Creation date: Nov 12, 2021
Entry type: PrivateKeyEntry
Certificate chain length: 1
Certificate[1]:
Owner: CN=localhost, OU=dev, O=tune-it, ST=Some-State, C=RU
Issuer: CN=localhost, OU=dev, O=tune-it, ST=Some-State, C=RU

ВАЖНО!

Для корректной работы данного приложения, отсутсвия неожиданных логов логов из разряда

Про сертификаты:  Эмиссионные ценные бумаги: виды, формы, признак эмиссионной ценной бумаги ::

 o.s.s.w.a.p.x.X509AuthenticationFilter   : No client certificate found in request. 

следует отключить csrf и добавить server.ssl.client-auth = need в application.properties

Запускаем наше приложение

$ gradle wrapper
$ ./gradlew bootRun

Убеждаемся в его работоспособности

$ curl -k --cert client.crt --key clientprivate.key -X GET 'https://localhost:8443/test/hello'

Hello Alex.Pashnin!

Таким, довольно нехитрым образом, мы произвели авторизацию и аутентификацию пользователя с помощью TLS сертификата. На этом всё, спасибо за внимание.

Are you paying for certification yourself or is your employer paying for it?

In case your employer pays for your education, I would go for it. In case you pay it yourself, you have to be much more careful which certifications to choose, but still, in general I think it is well worth it as you will learn a lot.

Do you want to change employer soon?

In that case, it might help you when searching for a new job. If you don´t want to switch – will it help you in your current position? Maybe you can use it as one of your arguments to get raise, maybe it is part of your yearly KPIs to study and improve, maybe it will show your employer how dedicated you are.

Domains covered in the spring professional exam

After reflecting on the exam information related to spring professional certification, let us find out the domains in the exam. Finding out the weight of individual topics in the exam can provide better guidance for your preparation. How?

Preparing for a Spring interview? Go through these frequently-asked Spring Framework Interview questions and get ready to crack the interview.

Github – mrr0807/springcertification5.0: my notes for preparing for spring professional certification

My notes for preparing for Spring Professional Certification.
These sources were used to compile them:

  • Spring 5 Design Patterns
  • Spring in Action 4th edition
  • Spring Security – Third Edition
  • Core Spring 5 Certification in Detail by Ivan Krizsan
  • Spring Documentation and Spring API javadocs

How well do you know that technology?

If you know it already very well and are getting certified just for sake of certification, it is much less valuable. I always pursued certifications in areas where I wanted or needed to expand my knowledge. In that case a certification is great motivation to actually learn that area on pretty deep level.

Preparing for the spring professional certification exam

The most important part of this discussion is the preparation guide for the spring professional v5.0 certification exam. Let us point out the milestones that you have to cross to succeed at the spring professional exam.

The priority of candidates must be the exam objectives. You need to take a closer look at the syllabus outlined for the spring professional exam. The study guide on the official website of Pivotal is a helpful instrument to learn more about the exam topics.

The next important step in your preparation journey for spring professional certification is a prolific training course. The recommended source to get a training course for spring professional exam is Pivotal. The “Core Spring” training course is a recommended training course in the exam brief on the official website of Pivotal.

Recommended reading materials can also be helpful in your preparation for spring professional exam. The “spring in Action”5th edition is ideally suited for spring v5.0. Another recommended read is the “Pivotal Certified Professional Spring Developer Exam:

Про сертификаты:  Нужен ли сертификат 3d дизайнеру?. Частные уроки

Check Here: Best Books to Learn Spring Framework

Practical experience is mandatory for scoring good marks in the spring professional certification exam. Therefore, you should try a spring v5.0 simulator to practice questions in the real exam like scenarios. Simply put, you should go for practice tests.

Finally, you need to engage in shared learning. The spring professional exam launched recently in May 2021 in a new form does not have many sources of guidance. Therefore, you need to participate in communities and forums. Learning communities and forums can help you interact with other candidates. As a result, you can contribute to the community as well as gain insights on better methods for preparation.

Spring certification

I attended official Spring Core Framework 3.2 Training (5.0 is already available now) last year. It was a four-day course with a certification. It was very professionally made training and I can recommend it. I think if there is a certification in java world to pursue (except for the traditional oracle java certifications), it is definitely Spring one.

Spring professional certification exam details

Now, let us find out more about the spring professional v5.0 exam in detail. The exam would consist of 50 questions. The format of the exam will be proctored, and candidates will get multiple-choice questions only. The exam launched in May 2021, has the code EDU-1202.

The duration of the exam would be around 90 minutes, i.e., one and a half-hour. The passing score for the exam is 76%. Therefore, you have to answer at least 38 questions correctly to qualify the examination. You can use the table presented below for an organized idea about the exam information for spring professional certification.

Subtopics in each domain of spring professional exam

For an effective preparation for the spring professional certification exam, you need to review the spring professional certification study guide. The study guide serves as a path on which candidates can recognize the essential concepts.

Furthermore, candidates could use it as an instrument for scheduling their preparations for the spring professional examination. Here, we have attempted to outline the different topics included in each domain of the spring professional exam.

The first domain in the spring professional certification exam deals with containers, dependency, and IOC. This domain accounts for almost 20% of the questions in the spring professional exam. Candidates have to learn about dependency injection and the use of the interface in Java. Other important topics include application context and the creation of a new instance of the application context.

Candidates should also cover dependency injection with the use of Java configurations and annotations. You will also learn about property source, Bean Factory Post Processor, and definition of static @bean method. The importance of the Bean Post Processor and Bean Factory Post Processor is also evident in this domain.

Component scanning is also a crucial addition in this domain of spring professional certification exam. Candidates should also learn about proxy objects and the use of @Bean and @Autowired annotations. The other important topics in this domain refer to the configuration of profiles and possible use cases for the same.

Про сертификаты:  Сколько стоит чашка кофе

Candidates should also cover injection of scalar or literal values into spring beans and uses of @Value annotation. Furthermore, candidates should also identify the difference in the use of $ and # in expressions having @Value. This domain also covers Spring Expression Language, Environment abstraction, and referencing using Spring Expression Language.

The second domain in the spring professional certification exam deals with Aspect-oriented programming. Candidates will find around 8% of questions from this domain. Some of the essential topics covered in this domain refer to the concept of AOP and the problems it solves.

You will also learn about cross-cutting concerns, weaving, pointcut, advice, aspect, and joinpoint in AOP. Another important topic is the process for enabling detecting of @Aspect annotation. Other important topics refer to the use of JoinPoint argument and the Proceeding JoinPoint.

Подготовка к spring professional certification. spring boot

Да. По умолчанию, сообщения с приоритетами ERROR, WARN, INFO будут выводится в приложении. Чтобы включить вывод уровней DEBUG или TRACE вы должны использовать ключи --debug/--trace или установить проперти-свойства debug/trace = true.

logging.level.root = WARN
logging.level.org.springframework.web = DEBUG
logging.level.org.hibernate = ERROR

По умолчанию Sprin Boot логирует только в консоль. Если вы хотите логировать события в файл, необходимо установить свойства logging.file или logging.path в true(например, в application.properties).

Цветной вывод сообщений в журнал

В консолях, поддерживающих ANSI, для улучшения читаемости сообщения различных уровней могут быть выделяться с помощью разных цветов. Вот как это настраивается в property-файле:

logging.pattern.console=%clr(%d{yyyy-MM-dd HH:mm:ss}) {yellow}

Если вы хотите, чтобы записать шла в другие файлы, вы также можете это настроить(YAML):

logging:
  path: /var/logs/
  file: bookWarn.log
  level: 
    root: WARN
    org.
      springframework:
        security: DEBUG

Сертификация или курсы для spring / hibernate, воспринимаемые рынком?

Промахнулся мимо кнопки ‘предпросмотр’, не дописав сообщение 🙂
Ну и не надо забывать про сертификации по Java от Sun/Oracle. По ним я тоже получал: ‘Sun Certified Java Programmer’, ‘Oracle Certified Java EE 6 Persistence API Developer’, ‘Oracle Certified Java EE 6 Web Services Developer’.
Java EE 6 Persistence API — как раз сертификация по JPA 2.0, который реализует Hibernate.

По результатам могу сказать, что логотипы этих сертификаций в резюме служат отличными КДПВ 😉

Final words

On a final note, success in the spring professional exam completely depends on your will and commitment. You do not have access to proven information regarding preparations for the exam now. However, observations from the experiences of successful candidates helped shape up this discussion. Therefore, you can find this discussion as a reliable guide for spring professional certification preparation.

The facility of the individual purchase option for spring certifications by Pivotal is a promising opportunity. The discussion reflected on exam information and topics covered in the exam comprehensively. Finally, the discussion outlined specific steps to ensure effective preparation for the final examination. So, if you have purchased your spring certification voucher, then it’s time to get ready!

If you don’t know much about Spring, then we would recommend you to enroll for our Spring basics online training course and understand the basic concepts of Spring. It will help you in your Spring Professional certification preparation and get you ready for the Spring Professional certification exam.

Оцените статью
Мой сертификат
Добавить комментарий