@Nightmare058

Как сделать аутентификацию без использования html формы?

Добрый день.
Хочу сделать аутентификацию, чтобы запрос приходил с фронта(я делаю только бэк).
Поэтому в WebSecurityConfig formLogin() мне не подходит.
Гугл подсказал, что в этом случае нужно использовать BasicAuthenticationEntryPoint.
https://www.baeldung.com/spring-security-basic-aut...
В этой статье показывается простой вариант, но там не описано, что делать с классом MyBasicAuthenticationEntryPoint.
Буду признателен, если опишите, в чем суть или ссылке на статью по этому моменту.
  • Вопрос задан
  • 201 просмотр
Решения вопроса 1
добавляете 2 конфигурационных класса в которых описываете и внедряете безопасность

package example.config;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Configuration;
import org.springframework.security.config.annotation.authentication.builders.AuthenticationManagerBuilder;
import org.springframework.security.config.annotation.web.builders.HttpSecurity;
import org.springframework.security.config.annotation.web.configuration.EnableWebSecurity;
import org.springframework.security.config.annotation.web.configuration.WebSecurityConfigurerAdapter;

@Configuration
@EnableWebSecurity
public class SecurityConfiguration extends WebSecurityConfigurerAdapter {

	private final static String username = "admin";
	private final static String password = "password";

	@Autowired
	private BasicAuthenticationPoint basicAuthenticationPoint;

	@Override
	protected void configure(HttpSecurity http) throws Exception {
		http.csrf().disable();
		http.authorizeRequests().antMatchers("/", "/api/**").permitAll()
				.anyRequest().authenticated();
		http.httpBasic().authenticationEntryPoint(basicAuthenticationPoint);
	}

	// https://spring.io/blog/2017/11/01/spring-security-5-0-0-rc1-released#password-storage-format
	@Autowired
	public void configureGlobal(AuthenticationManagerBuilder auth)
			throws Exception {
		auth.inMemoryAuthentication().withUser(username)
				.password(String.format("{noop}%s", password)).roles("USER");
	}

}

package example.config;

import org.springframework.context.annotation.Bean;
import org.springframework.security.core.AuthenticationException;
import org.springframework.security.crypto.factory.PasswordEncoderFactories;
import org.springframework.security.crypto.password.PasswordEncoder;
import org.springframework.security.web.authentication.www.BasicAuthenticationEntryPoint;
import org.springframework.stereotype.Component;

import java.io.IOException;
import java.io.PrintWriter;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

@Component
public class BasicAuthenticationPoint extends BasicAuthenticationEntryPoint {
	private static final String realName = "user";

	@Override
	public void commence(HttpServletRequest request, HttpServletResponse response,
			AuthenticationException e) throws IOException {
		response.addHeader("WWW-Authenticate", "Basic realm=" + getRealmName());
		response.setStatus(HttpServletResponse.SC_UNAUTHORIZED);

		PrintWriter writer = response.getWriter();
		writer.println("HTTP Status 401 - " + e.getMessage());

	}

	@Override
	public void afterPropertiesSet() {
		setRealmName(realName);
		super.afterPropertiesSet();
	}


}


после этого

mvn -Dmaven.test.skip=true clean spring-boot:run
curl --silent http://localhost:8080/
HTTP Status 401 - Full authentication is required to access this resource

curl --silent --user admin:wrong_password http://localhost:8080/employees

HTTP Status 401 - Bad credentials
curl -silent --user admin:password http://localhost:8080/employees

HTTP Status 200 OK
...
то что контроллер должен ответить


пароль нешифрованный:
Basic YWRtaW46cGFzc3dvcmQ=

echo 'YWRtaW46cGFzc3dvcmQ=' | base64 -d -
admin:password

я это вот использую для стаб сервера на который некое другое приложение которое я например отлаживаю постит всякую всячину но например не всем должно быть разрешено
Ответ написан
Пригласить эксперта
Ответы на вопрос 1
azerphoenix
@azerphoenix Куратор тега Java
Java Software Engineer
Хочу сделать аутентификацию, чтобы запрос приходил с фронта(я делаю только бэк).

По сути вы пишете REST сервис, а соответственно, вам нужно добавить аутентификацию с использованием jwt.
Вот, пример приложения - https://github.com/hantsy/spring-webmvc-jwt-sample
Прочитать можно тут:
https://www.bezkoder.com/spring-boot-security-post...
Ответ написан
Комментировать
Ваш ответ на вопрос

Войдите, чтобы написать ответ

Войти через центр авторизации
Похожие вопросы