powered by simpleCommunicator - 2.0.61     © 2026 Programmizd 02
Целевая тема:
Создать новую тему:
Автор:
Закрыть
Цитировать
Форумы / Java [игнор отключен] [закрыт для гостей] / Spring Boot Security
4 сообщений из 4, страница 1 из 1
Spring Boot Security
    #39532447
Фотография -=Koba=-
Скрыть профиль Поместить в игнор-лист Сообщения автора в теме
Участник
Взял за основу это приложение
https://github.com/monkey-codes/spring-boot-authentication

Хочу переписать его на использовании Eureka


Application.yml
Код: java
1.
2.
3.
4.
5.
6.
7.
8.
9.
10.
11.
12.
13.
14.
15.
16.
17.
18.
19.
20.
21.
22.
23.
24.
25.
26.
27.
28.
29.
30.
31.
32.
33.
34.
35.
36.
37.
38.
39.
40.
41.
42.
43.
44.
45.
46.
47.
48.
49.
50.
spring:
  application:
    name: security-auth
  datasource:
    url: jdbc:h2:mem:example;DB_CLOSE_DELAY=-1
    platform: h2
    username: sa
    password:
    driverClassName: org.h2.Driver
  jpa:
    database-platform: org.hibernate.dialect.H2Dialect
    hibernate:
      ddl-auto: none
  properties:
    hibernate:
      show_sql: true
      use_sql_comments: true
      format_sql: true
  h2:
    console:
      enabled: true

h2:
  console:
    enabled: true
    path: /console
    settings:
      trace: false
      web-allow-others: false

server:
  port: 9991
  contextPath: /auth

security:
  user:
    password: password
  sessions: if-required

eureka:
  instance:
    leaseRenewalIntervalInSeconds: 1
    leaseExpirationDurationInSeconds: 2
  client:
    serviceUrl:
      defaultZone: http://127.0.0.1:8761/eureka/
    healthcheck:
      enabled: true
    lease:
      duration: 5



SecurityAuth.java
Код: java
1.
2.
3.
4.
5.
6.
7.
8.
9.
10.
11.
12.
13.
14.
15.
16.
17.
18.
19.
20.
21.
22.
23.
24.
25.
26.
27.
28.
29.
30.
31.
32.
33.
34.
35.
36.
37.
38.
39.
40.
41.
42.
43.
44.
45.
46.
47.
48.
49.
50.
51.
52.
53.
54.
55.
56.
57.
58.
59.
60.
61.
62.
63.
64.
65.
66.
67.
68.
69.
70.
71.
72.
73.
74.
75.
76.
77.
78.
79.
80.
81.
82.
83.
84.
85.
86.
87.
88.
89.
90.
91.
92.
93.
94.
95.
96.
package com.example.security;

import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.cloud.client.discovery.EnableDiscoveryClient;
import org.springframework.cloud.netflix.eureka.EnableEurekaClient;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.core.annotation.Order;
import org.springframework.security.authentication.AuthenticationManager;
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.WebSecurityConfigurerAdapter;
import org.springframework.web.servlet.config.annotation.ViewControllerRegistry;
import org.springframework.web.servlet.config.annotation.WebMvcConfigurerAdapter;

@EnableEurekaClient
@EnableDiscoveryClient
@SpringBootApplication
public class SecurityAuth extends WebMvcConfigurerAdapter {

	@Override
	public void addViewControllers(ViewControllerRegistry registry) {
		registry.addViewController("/login").setViewName("login");
	}


	@Configuration
	@Order(-20)
	static class WebSecurityConfig extends WebSecurityConfigurerAdapter {


		@Override
		@Bean
		public AuthenticationManager authenticationManagerBean() throws Exception {
			return super.authenticationManagerBean();
		}

		@Override
		protected void configure(HttpSecurity http) throws Exception {
			http.formLogin().loginPage("/login").permitAll().and().httpBasic().and().requestMatchers().
					antMatchers("/login", "/oauth/authorize", "/oauth/confirm_access").
					antMatchers("/fonts/**", "/js/**", "/css/**").and().authorizeRequests().
					antMatchers("/fonts/**", "/js/**", "/css/**").permitAll().anyRequest().authenticated();
		}

		@Override
		protected void configure(AuthenticationManagerBuilder auth) throws Exception {
			auth.inMemoryAuthentication().withUser("reader").
					password("reader").authorities("ROLE_READER").
					and().withUser("writer").password("writer").
					authorities("ROLE_READER", "ROLE_WRITER").and().
					withUser("guest").password("guest").authorities("ROLE_GUEST");
		}
	}
/*
	@Configuration
	@EnableAuthorizationServer
	static class OAuth2Configuration extends AuthorizationServerConfigurerAdapter {

		@Autowired
		@Qualifier("authenticationManagerBean")
		AuthenticationManager authenticationManager;


		@Override
		public void configure(ClientDetailsServiceConfigurer clients) throws Exception {
			clients.inMemory().withClient("web-app").scopes("read").autoApprove(true).accessTokenValiditySeconds(600).
					refreshTokenValiditySeconds(600).authorizedGrantTypes("implicit", "refresh_token", "password", "authorization_code");
		}

		@Override
		public void configure(AuthorizationServerEndpointsConfigurer endpoints) throws Exception {
			endpoints.tokenStore(tokenStore()).tokenEnhancer(jwtTokenEnhancer()).authenticationManager(authenticationManager);
		}


		@Bean
		TokenStore tokenStore() {
			return new JwtTokenStore(jwtTokenEnhancer());
		}

		@Bean
		protected JwtAccessTokenConverter jwtTokenEnhancer() {
			KeyStoreKeyFactory keyStoreKeyFactory = new KeyStoreKeyFactory(new ClassPathResource("jwt.jks"), "mySecretKey".toCharArray());
			JwtAccessTokenConverter converter = new JwtAccessTokenConverter();
			converter.setKeyPair(keyStoreKeyFactory.getKeyPair("jwt"));
			return converter;
		}
	}
*/

	public static void main(String[] args) throws Exception {
		SpringApplication.run(SecurityAuth.class, args);
	}
}



При попытке перейти на страницу логина http://localhost:9991/auth/login получаю
Код: java
1.
2.
3.
4.
5.
6.
7.
Whitelabel Error Page

This application has no explicit mapping for /error, so you are seeing this as a fallback.

Fri Oct 06 18:05:28 MSK 2017
There was an unexpected error (type=Bad Request, status=400).
Failed to convert value of type 'java.lang.String' to required type 'java.lang.Integer'; nested exception is java.lang.NumberFormatException: For input string: "login"


Само приложение работает корректно
В ечм может быть ошибка?
...
Рейтинг: 0 / 0
Spring Boot Security
    #39533204
Фотография SQL2008
Скрыть профиль Поместить в игнор-лист Сообщения автора в теме
Участник
-=Koba=-Взял за основу это приложение
https://github.com/monkey-codes/spring-boot-authentication

Хочу переписать его на использовании Eureka


Application.yml
Код: java
1.
2.
3.
4.
5.
6.
7.
8.
9.
10.
11.
12.
13.
14.
15.
16.
17.
18.
19.
20.
21.
22.
23.
24.
25.
26.
27.
28.
29.
30.
31.
32.
33.
34.
35.
36.
37.
38.
39.
40.
41.
42.
43.
44.
45.
46.
47.
48.
49.
50.
spring:
  application:
    name: security-auth
  datasource:
    url: jdbc:h2:mem:example;DB_CLOSE_DELAY=-1
    platform: h2
    username: sa
    password:
    driverClassName: org.h2.Driver
  jpa:
    database-platform: org.hibernate.dialect.H2Dialect
    hibernate:
      ddl-auto: none
  properties:
    hibernate:
      show_sql: true
      use_sql_comments: true
      format_sql: true
  h2:
    console:
      enabled: true

h2:
  console:
    enabled: true
    path: /console
    settings:
      trace: false
      web-allow-others: false

server:
  port: 9991
  contextPath: /auth

security:
  user:
    password: password
  sessions: if-required

eureka:
  instance:
    leaseRenewalIntervalInSeconds: 1
    leaseExpirationDurationInSeconds: 2
  client:
    serviceUrl:
      defaultZone: http://127.0.0.1:8761/eureka/
    healthcheck:
      enabled: true
    lease:
      duration: 5




SecurityAuth.java
Код: java
1.
2.
3.
4.
5.
6.
7.
8.
9.
10.
11.
12.
13.
14.
15.
16.
17.
18.
19.
20.
21.
22.
23.
24.
25.
26.
27.
28.
29.
30.
31.
32.
33.
34.
35.
36.
37.
38.
39.
40.
41.
42.
43.
44.
45.
46.
47.
48.
49.
50.
51.
52.
53.
54.
55.
56.
57.
58.
59.
60.
61.
62.
63.
64.
65.
66.
67.
68.
69.
70.
71.
72.
73.
74.
75.
76.
77.
78.
79.
80.
81.
82.
83.
84.
85.
86.
87.
88.
89.
90.
91.
92.
93.
94.
95.
96.
package com.example.security;

import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.cloud.client.discovery.EnableDiscoveryClient;
import org.springframework.cloud.netflix.eureka.EnableEurekaClient;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.core.annotation.Order;
import org.springframework.security.authentication.AuthenticationManager;
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.WebSecurityConfigurerAdapter;
import org.springframework.web.servlet.config.annotation.ViewControllerRegistry;
import org.springframework.web.servlet.config.annotation.WebMvcConfigurerAdapter;

@EnableEurekaClient
@EnableDiscoveryClient
@SpringBootApplication
public class SecurityAuth extends WebMvcConfigurerAdapter {

	@Override
	public void addViewControllers(ViewControllerRegistry registry) {
		registry.addViewController("/login").setViewName("login");
	}


	@Configuration
	@Order(-20)
	static class WebSecurityConfig extends WebSecurityConfigurerAdapter {


		@Override
		@Bean
		public AuthenticationManager authenticationManagerBean() throws Exception {
			return super.authenticationManagerBean();
		}

		@Override
		protected void configure(HttpSecurity http) throws Exception {
			http.formLogin().loginPage("/login").permitAll().and().httpBasic().and().requestMatchers().
					antMatchers("/login", "/oauth/authorize", "/oauth/confirm_access").
					antMatchers("/fonts/**", "/js/**", "/css/**").and().authorizeRequests().
					antMatchers("/fonts/**", "/js/**", "/css/**").permitAll().anyRequest().authenticated();
		}

		@Override
		protected void configure(AuthenticationManagerBuilder auth) throws Exception {
			auth.inMemoryAuthentication().withUser("reader").
					password("reader").authorities("ROLE_READER").
					and().withUser("writer").password("writer").
					authorities("ROLE_READER", "ROLE_WRITER").and().
					withUser("guest").password("guest").authorities("ROLE_GUEST");
		}
	}
/*
	@Configuration
	@EnableAuthorizationServer
	static class OAuth2Configuration extends AuthorizationServerConfigurerAdapter {

	@Autowired
	@Qualifier("authenticationManagerBean")
	AuthenticationManager authenticationManager;


	@Override
	public void configure(ClientDetailsServiceConfigurer clients) throws Exception {
	clients.inMemory().withClient("web-app").scopes("read").autoApprove(true).accessTokenValiditySeconds(600).
	refreshTokenValiditySeconds(600).authorizedGrantTypes("implicit", "refresh_token", "password", "authorization_code");
	}

	@Override
	public void configure(AuthorizationServerEndpointsConfigurer endpoints) throws Exception {
	endpoints.tokenStore(tokenStore()).tokenEnhancer(jwtTokenEnhancer()).authenticationManager(authenticationManager);
	}


	@Bean
	TokenStore tokenStore() {
	return new JwtTokenStore(jwtTokenEnhancer());
	}

	@Bean
	protected JwtAccessTokenConverter jwtTokenEnhancer() {
	KeyStoreKeyFactory keyStoreKeyFactory = new KeyStoreKeyFactory(new ClassPathResource("jwt.jks"), "mySecretKey".toCharArray());
	JwtAccessTokenConverter converter = new JwtAccessTokenConverter();
	converter.setKeyPair(keyStoreKeyFactory.getKeyPair("jwt"));
	return converter;
	}
	}
*/

	public static void main(String[] args) throws Exception {
		SpringApplication.run(SecurityAuth.class, args);
	}
}




При попытке перейти на страницу логина http://localhost:9991/auth/login получаю
Код: java
1.
2.
3.
4.
5.
6.
7.
Whitelabel Error Page

This application has no explicit mapping for /error, so you are seeing this as a fallback.

Fri Oct 06 18:05:28 MSK 2017
There was an unexpected error (type=Bad Request, status=400).
Failed to convert value of type 'java.lang.String' to required type 'java.lang.Integer'; nested exception is java.lang.NumberFormatException: For input string: "login"



Само приложение работает корректно
В ечм может быть ошибка?
Покажите форму ввода пароля. Похоже, что там с типами что-то не так.
...
Рейтинг: 0 / 0
Spring Boot Security
    #39533877
Фотография -=Koba=-
Скрыть профиль Поместить в игнор-лист Сообщения автора в теме
Участник
Под линуксом завелся
...
Рейтинг: 0 / 0
Spring Boot Security
    #39533986
Фотография SQL2008
Скрыть профиль Поместить в игнор-лист Сообщения автора в теме
Участник
-=Koba=-Под линуксом завелся
Код: java
1.
Failed to convert value of type 'java.lang.String' to required type 'java.lang.Integer';


Видимо Линукс умеет конвертировать "раз два три" в 123.
...
Рейтинг: 0 / 0
4 сообщений из 4, страница 1 из 1
Форумы / Java [игнор отключен] [закрыт для гостей] / Spring Boot Security
Найденые пользователи ...
Разблокировать пользователей ...
Читали форум (0):
Пользователи онлайн (0):
x
x
Закрыть


Просмотр
0 / 0
Close
Debug Console [Select Text]