I'm trying to get SSL to work. I have generated my SSL file .p12 and now I have writen in the configuration inside my application.yml.
Still the port 8080 is used. Why?
server:
port: 8443
ssl:
key-store: classpath:myFile.p12
key-store-password: myPassword
key-store-type: PKCS12
key-alias: mySSLAlias
key-password: myPassword
And the terminal output:
Tomcat started on port(s): 8080 (http) with context path ''
So I can only still connect http://localhost:8080, not https://localhost:8443
Why?
I'm using Spring Security as well.
#Configuration
public class SecurityConfiguration extends WebSecurityConfigurerAdapter {
#Override
public void configure(HttpSecurity http) throws Exception {
http
.csrf().disable()
.authorizeRequests()
.antMatchers("/Intranet/AdminCrudView", "/Intranet/Bokning").authenticated()
.antMatchers("/**", "/Intranet**").permitAll()
.anyRequest().authenticated()
.and().logout().logoutSuccessUrl("/").permitAll()
.and()
.oauth2Login().defaultSuccessUrl("/Intranet");
}
}
Here is my complete application.yml file:
spring:
datasource:
driverClassName: com.mysql.cj.jdbc.Driver
url: jdbc:mysql://localhost:3306/spektrakonhemsida?serverTimezone=CET&createDatabaseIfNotExist=true
username: myUser
password: myPassword
jpa:
database-platform: org.hibernate.dialect.MySQL5InnoDBDialect
show-sql: false
hibernate:
ddl-auto: update
security:
oauth2:
client:
registration:
facebook:
clientId: myID
clientSecret: mySecret
accessTokenUri: https://graph.facebook.com/oauth/access_token
userAuthorizationUri: https://www.facebook.com/dialog/oauth
tokenName: oauth_token
authenticationScheme: query
clientAuthenticationScheme: form
resource:
userInfoUri: https://graph.facebook.com/me
mail:
host: smtp.gmail.com
port: 587
username: myGmail#gmail.com
password: myPassword
properties:
mail:
smtp:
auth: true
starttls:
enable: true
crud:
adminfacebookemail: myFacebookEmail#outlook.com
vaadin:
productionMode: true
server:
port: 8443
ssl:
key-store: classpath:mySSLFile.p12
key-store-password: myPassword
key-store-type: PKCS12
key-alias: myAlias
key-password: myPassword
Solved it!
It cannot be
server:
port: 8443
ssl:
key-store: classpath:mySSLFile.p12
key-store-password: myPassword
key-store-type: PKCS12
key-alias: myAlias
key-password: myPassword
It must be two less spaces, like this:
server:
port: 8443
ssl:
key-store: classpath:mySSLFile.p12
key-store-password: myPassword
key-store-type: PKCS12
key-alias: myAlias
key-password: myPassword
Related
I have following security configs in
Server application.yml
management:
security:
enabled: false
server:
port: 8888
spring:
cloud:
config:
server:
jdbc:
order: 1
sql: SELECT prop_key,value FROM xlabs.properties where application=?
and profile=? and label=?
datasource:
password: XXXXX
url: jdbc:postgresql://localhost:8000/finos?currentSchema=xlabs
username: XXXXX
profiles:
active: jdbc
security:
user:
name: mufg
password: mufg
In Client side.
client application.properties
server:
port: 8082
spring:
application:
name: config-server
cloud:
config:
label: latest
profile: development
uri: http://localhost:8888
username: mufg
password: mufg
With this settings
Config server security works fine I can access properties via http://localhost:8888/config-server/development/latest after entering username and passwords. But when I try to up client it says property not resolved. Any issue here?
Thanks.
After some times I am able to find out the answer. In Config server with only that configs the client side will be blocked. So have to disable csrf and allow any request like as follows.
just add sever side.
#Configuration
public class SecurityConfiguration extends WebSecurityConfigurerAdapter {
#Override
public void configure(HttpSecurity http) throws Exception {
http
.csrf()
.disable()
.httpBasic()
.and()
.authorizeRequests()
.antMatchers("/encrypt/**").authenticated()
.antMatchers("/decrypt/**").authenticated();
}
}
But Here default security will be disabled. Here problem is if username or password changed from client side authentication happens.
I am working on a spring boot app in order to communicate with another secured API.
For that, I implement a OAuth2RestTemplate with the following properties but it failed when I run the application.
#Configuration
#EnableOAuth2Client
class RestTemplateConfiguration {
#Bean
#ConfigurationProperties("oauth2")
public OAuth2ProtectedResourceDetails oAuth2ProtectedResourceDetails() {
return new ClientCredentialsResourceDetails();
}
#Bean
public OAuth2RestTemplate oAuth2RestTemplate(
#Qualifier("oAuth2ProtectedResourceDetails") OAuth2ProtectedResourceDetails oAuth2ProtectedResourceDetails) {
return new OAuth2RestTemplate(oAuth2ProtectedResourceDetails);
}
}
application.properties
spring:
security:
oauth2:
client:
registration:
clientId: xxxxxxxxxxxxxxxxxx
clientSecret: xxxxxxxxxxxxxxxxx
accessTokenUri: https://xxxxxx/oauth2/access_token
scope: openid profile xxxxxxxxxxx
authorizationGrantType: client_credentials
The exception I get when I run the code
Failed to bind properties under 'spring.security.oauth2.client.registration.clientid' to org.springframework.boot.autoconfigure.security.oauth2.client.OAuth2ClientProperties$Registration:
I think the problem is here
security:
oauth2:
client:
registration:
mb:
client-name: mb
client-id: ui
client-secret: secret
authorization-grant-type: authorization_code
redirect-uri: http:localhost:8084/ui/login/oauth2/code/
scope: openId
client-authentication-method: basic
provider:
mb:
token-uri: http://localhost:8181/oauth/token
authorization-uri: http:localhost:8181/oauth/authorize
user-info-uri: http:localhost:8181/oauth/userinfo
user-name-attribute: name
I ran into the same issue. The reference documentation mentions that you need to provide a registrationId within the property "path"
You application.properties should look like this:
spring:
security:
oauth2:
client:
registration:
YOUR_REGISTRATION_ID: # <----------
clientId: xxxxxxxxxxxxxxxxxx
clientSecret: xxxxxxxxxxxxxxxxx
accessTokenUri: https://xxxxxx/oauth2/access_token
scope: openid profile xxxxxxxxxxx
authorizationGrantType: client_credentials
I am trying to integrate my Sprint Boot applications with Keycloak, starting with secure swagger page.
keytool helped me to generate a selfsigned keystore
keytool -genkey -alias abcdef -storetype PKCS12 -keyalg RSA -keysize 2048 -keystore keystore.p12 -validity 3650
I use the above to setup ssl for the app
server:
port: "15700"
ssl:
enabled: true
key-store: classpath:keystore.p12
key-store-password: password
key-alias: abcdef
keyStoreType: PKCS12
Without keycloak, the https for swagger works as expected.
I started keycloak from their docker image as below, export http and https
services:
keycloak:
image: jboss/keycloak
environment:
DB_VENDOR: POSTGRES
DB_ADDR: my.ip.address
DB_PORT: 5432
DB_DATABASE: keycloak
DB_USER: username
DB_PASSWORD: password
KEYCLOAK_USER: admin
KEYCLOAK_PASSWORD: password
ports:
- 8443:8443
- 8080:8080
I ask user to login first when they want to access the swagger docs, so I configure keycloak as below:
keycloak:
auth-server-url: "https://192.168.1.15:8443/auth"
realm: "DemoRealm"
public-client: true
resource: demo-app
security-constraints[0]:
authRoles[0]: "user"
securityCollections[0]:
name: "Demo App"
patterns[0]: "/swagger-ui.html"
Now, not logged in user will be direct to keycloak login page, it works perfect. But after the successful login, when redirect back to the app's swagger page, I go the following error:
Caused by: sun.security.provider.certpath.SunCertPathBuilderException: unable to find valid certification path to requested target
If I configure the keycloak auth uri to http
keycloak:
auth-server-url: "http://192.168.1.15:8080/auth"
realm: "DemoRealm"
public-client: true
resource: demo-app
security-constraints[0]:
authRoles[0]: "user"
securityCollections[0]:
name: "Demo App"
patterns[0]: "/swagger-ui.html"
everything works perfectly.
Is this a configuration issue for keycloak or for the spring boot app? Any required steps I missed?
You can try to set up your Rest Template bean:
Add dependency:
implementation 'org.apache.httpcomponents:httpclient:4.5'
Provide RestTemplate bean:
#Bean
private RestTemplate restTemplate() {
SSLContext sslContext = buildSslContext();
SSLConnectionSocketFactory socketFactory = new SSLConnectionSocketFactory(sslContext);
HttpClient httpClient = HttpClients.custom()
.setSSLSocketFactory(socketFactory)
.build();
HttpComponentsClientHttpRequestFactory factory = new HttpComponentsClientHttpRequestFactory(httpClient);
return new RestTemplate(factory);
}
private SSLContext buildSslContext() {
try {
char[] keyStorePassword = sslProperties.getKeyStorePassword();
return new SSLContextBuilder()
.loadKeyMaterial(
KeyStore.getInstance(new File(sslProperties.getKeyStore()), keyStorePassword),
keyStorePassword
).build();
} catch (Exception ex) {
throw new IllegalStateException("Unable to instantiate SSL context", ex);
} finally {
sslProperties.setKeyStorePassword(null);
sslProperties.setTrustStorePassword(null);
}
}
Provide required SSL properties in your application.properties or application.yaml file:
server:
ssl:
enabled: true
key-store: /path/to/key.keystore
key-store-password: password
key-alias: alias
trust-store: /path/to/truststore
trust-store-password: password
Alternatively, you can use my spring boot starter
I am trying to configure the sample https://github.com/dsyer/spring-security-angular/tree/master/oauth2/ui to use eureka for the userAuthorizationUri part but with no luck so far. my oauth2 server is registered via eureka
server:
port: ${PORT:${SERVER_PORT:0}}
debug:
security:
user:
password: none
zuul:
routes:
resource:
path: /resource/**
url: http://localhost:9000/resource
user:
path: /user/**
serviceId: authentication-service/uaa/user
spring:
application:
name: ui-service
oauth2:
sso:
home:
secure: false
path: /,/**/*.html
client:
accessTokenUri: http://authentication-service/uaa/oauth/token
userAuthorizationUri: http://authentication-service/uaa/oauth/authorize
clientId: acme
clientSecret: acmesecret
resource:
serviceId: ${PREFIX:}resource
jwt:
keyValue: |
-----BEGIN PUBLIC KEY-----
MYKEY
-----END PUBLIC KEY-----
logging:
level:
org.springframework.security: DEBUG
eureka:
instance:
metadataMap:
instanceId: ${spring.application.name}:${spring.application.instance_id:${random.int(10000)}}
client:
serviceUrl:
defaultZone: http://localhost:8888/eureka/
I understand that a Spring Cloud Config Server can be protected using an user name and password , which has to be provided by the accessing clients.
How can i prevent the clients from storing these user name and
password as clear text in the bootstrap.yml files in the client
application/services ?
The very basic "basic authentication" (from here https://github.com/spring-cloud-samples/configserver)
You can add HTTP Basic authentication by including an extra dependency on Spring Security (e.g. via spring-boot-starter-security). The user name is "user" and the password is printed on the console on startup (standard Spring Boot approach). If using maven (pom.xml):
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-security</artifactId>
</dependency>
If you want custom user/password pairs, you need indicate in server configuration file
security:
basic:
enabled: false
and add this minimal Class in your code (BasicSecurityConfiguration.java):
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
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.WebSecurityConfigurerAdapter;
#Configuration
//#EnableGlobalMethodSecurity(prePostEnabled = true, securedEnabled = true)
public class BasicSecurityConfiguration extends WebSecurityConfigurerAdapter {
#Value("#{'${qa.admin.password:admin}'}") //property with default value
String admin_password;
#Value("#{'${qa.user.password:user}'}") //property with default value
String user_password;
#Autowired
public void configureGlobal(AuthenticationManagerBuilder auth) throws Exception {
auth
.inMemoryAuthentication()
.withUser("user").password(user_password).roles("USER")
.and()
.withUser("admin").password(admin_password).roles("USER", "ACTUATOR");
}
#Override
protected void configure(HttpSecurity http) throws Exception {
http
.csrf()
.disable()
.httpBasic()
.and()
.authorizeRequests()
.antMatchers("/encrypt/**").authenticated()
.antMatchers("/decrypt/**").authenticated()
//.antMatchers("/admin/**").hasAuthority("ROLE_ACTUATOR")
//.antMatchers("/qa/**").permitAll()
;
}
}
#Value("#{'${qa.admin.password:admin}'}") allow passwords to be defined in property configuration file, environment variables or command line.
For example (application.yml):
server:
port: 8888
security:
basic:
enabled: false
qa:
admin:
password: adminadmin
user:
password: useruser
management:
port: 8888
context-path: /admin
logging:
level:
org.springframework.cloud: 'DEBUG'
spring:
cloud:
config:
server:
git:
ignoreLocalSshSettings: true
uri: ssh://git#gitlab.server.corp/repo/configuration.git
This works for me.
Edit: Instead of the Class, you can put basic user configuration directly in application.yaml:
security:
basic:
enabled: true
path: /**
ignored: /health**,/info**,/metrics**,/trace**
user:
name: admin
password: tupassword
For Spring Boot 2 the configuration in application.yml are now under spring.security.* (https://docs.spring.io/spring-boot/docs/current/reference/html/appendix-application-properties.html#security-properties)
spring.security:
basic:
enabled: true
path: /**
ignored: /health**,/info**,/metrics**,/trace**
user:
name: admin
password: tupassword
Basic authentication configuration that works for me.
Server-side:
Needed depedency: org.springframework.boot:spring-boot-starter-security
bootstrap.yml
server:
port: 8888
spring:
cloud:
config:
server:
git:
uri: git#bitbucket.org:someRepo/repoName.git
hostKeyAlgorithm: ssh-rsa
hostKey: "general hostKey for bitbucket.org"
security:
user:
name: yourUser
password: yourPassword
Client-side:
bootstrap.yml
spring:
application:
name: config
profiles:
active: dev
cloud:
config:
uri: http://localhost:8888
username: yourUser
password: yourPassword
management:
security:
enabled: false
Sources: Spring doc security feautres, Spring cloud config client security
encrypted text can be placed in bootstrap.yml.
Check -> http://projects.spring.io/spring-cloud/spring-cloud.html#_encryption_and_decryption