Username Password Authentication error in spring boot using Bсrypt - spring-boot

I make Spring boot app.
Login with email = mail1#gmail.com and password bob.
I have password in BD which is HASH from bob.
I get this error on logging:
this = {DaoAuthenticationProvider#10456}
username = "mail1#gmail.com"
authentication = {UsernamePasswordAuthenticationToken#10457} "UsernamePasswordAuthenticationToken [Principal=mail1#gmail.com, Credentials=[PROTECTED], Authenticated=false, Details=WebAuthenticationDetails [RemoteIpAddress=0:0:0:0:0:0:0:1, SessionId=D7E584DE966931641FAB9DAB525EDC9E], Granted Authorities=[]]"
ex = {JpaSystemException#10458} "org.springframework.orm.jpa.JpaSystemException: collection was evicted; nested exception is org.hibernate.HibernateException: collection was evicted"
I'm reading the java.docs and can not understand what to do: The principal and credentials should be set with an Object that provides the respective property via its Object.toString() method. The simplest such Object to use is String.
Could you explain please?
My git: https://github.com/anatoliy19/3.1.2.git

I added annotations from Lombok to #manytomany and it came to work
#EqualsAndHashCode.Exclude
#ToString.Exclude

Related

Spring Boot #RequestScope and Hibernate schema based multi-tenancy

I'm working on a schema based multi-tenant app, in which I want to resolve the Tenant Identifier using a #RequestScope bean. My understanding is that #RequestScope uses/injects proxies for the request scoped beans, wherever they are referred (e.g. in other singleton beans). However, this is not working in the #Component that implements CurrentTenantIdentifierResolver and I get the following error when I start my service,
Caused by: org.springframework.beans.factory.support.ScopeNotActiveException: Error creating bean with name 'scopedTarget.userContext': Scope 'request' is not active for the current thread;
Caused by: java.lang.IllegalStateException: No thread-bound request found: Are you referring to request attributes outside of an actual web request, or processing a request outside of the originally receiving thread? If you are actually operating within a web request and still receive this message, your code is probably running outside of DispatcherServlet: In this case, use RequestContextListener or RequestContextFilter to expose the current request.
Following are the relevant pieces of code.
#Component
public class CurrentTenant implements CurrentTenantIdentifierResolver {
#Autowired
private UserContext userContext;
#Override
public String resolveCurrentTenantIdentifier() {
return Optional.of(userContext)
.map(u -> u.getDomain())
.get();
}
#Component
#RequestScope
public class UserContext {
private UUID id;
private String domain;
My questions,
Isn't the proxy for the #RequestScope injected (by default)? Do I need to do anything more?
Is Hibernate/Spring trying to establish a connection to the DB at startup (even when there is no tenant available)?
Hibernate properties:
HashMap<String, Object> properties = new HashMap<>();
properties.put("hibernate.dialect", env.getProperty("hibernate.dialect"));
properties.remove(AvailableSettings.DEFAULT_SCHEMA);
properties.put(AvailableSettings.MULTI_TENANT, MultiTenancyStrategy.SCHEMA);
properties.put(AvailableSettings.MULTI_TENANT_IDENTIFIER_RESOLVER, tenantResolver);
properties.put(AvailableSettings.MULTI_TENANT_CONNECTION_PROVIDER, connectionProvider);
For the time being, I'm preventing the NullPointerException by checking if we are in the RequestContext. However, a connection still gets established to the master database (although I've explicitly specified the dialect and am not specifying hbm2ddl.auto). Since this connection is not associated with any schema, I'd like to avoid making it, so that it does not look for any tables that it won't find anyways.
What seems to be happenning is that when a HTTP request is received, hibernate is trying to resolve the current tenant identifier, even before my #RequestScope bean is created (and even before my #RestController method is called.) If a provide the default connection to the databse, I then get the following error. If I don't provide a connection, it throws an exception and aborts.
2021-09-26 11:55:44.882 WARN 19759 --- [nio-8082-exec-2] o.h.engine.jdbc.spi.SqlExceptionHelper : SQL Error: 0, SQLState: 42P01
2021-09-26 11:55:44.882 ERROR 19759 --- [nio-8082-exec-2] o.h.engine.jdbc.spi.SqlExceptionHelper : ERROR: relation "employees" does not exist
Position: 301
2021-09-26 11:55:44.884 ERROR 19759 --- [nio-8082-exec-2] o.t.n.controller.EmployeeController : Exception: could not extract ResultSet; SQL [n/a]; nested exception is org.hibernate.exception.SQLGrammarException: could not extract ResultSet

Spring boot resource server with JWT base64 encoded Failed to authenticate since the JWT was invalid

I'm trying to use spring resource server starter with fusionauth.io. the fusion auth token is working just fine with postman and when I want to decode it in jwt.io I should check the secret base64 option to get the valid JWT.
application.yml:
spring:
security:
oauth2:
resourceserver:
jwt:
jwk-set-uri: http://localhost:9011/oauth2/token
SecurityConfig
#Configuration
public class SecurityConfig extends ResourceServerConfigurerAdapter {
#Bean
public JwtDecoder jwtDecoder(){
NimbusJwtDecoder jwtDecoder = NimbusJwtDecoder.withJwkSetUri(
"http://localhost:9011/oauth2/token").build();
return jwtDecoder;
}
#Override
public void configure(HttpSecurity http) throws Exception {
http
.authorizeRequests(authz -> authz
.antMatchers(HttpMethod.GET, "/user/**").permitAll()
.antMatchers(HttpMethod.POST, "/user/**").permitAll()
.anyRequest().authenticated()).csrf().disable()
.oauth2ResourceServer(OAuth2ResourceServerConfigurer::jwt);
}
}
sample jwt:
eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCIsImtpZCI6IjE1MDE1YWJiYyJ9.eyJhdWQiOiI1OTM4M2ViZS0zYjEzLTQ0YjktODM2MS0xZGQ0MWIxYzdlNDkiLCJleHAiOjE2MDgwODgwMjksImlhdCI6MTYwODA4NDQyOSwiaXNzIjoiYWNtZS5jb20iLCJzdWIiOiJiZGVhZDg5Yi1iNTQ3LTRlNDEtODJlMi1iMWIzNjkxZjA0Y2YiLCJqdGkiOiI3ZjZlYTgwMC1hZTgwLTQ0NzgtOWNmOC1mNzQ5ZTM3YjRlNzIiLCJhdXRoZW50aWNhdGlvblR5cGUiOiJQQVNTV09SRCIsImVtYWlsIjoidGVzdEBlbWFpbC5jb20iLCJlbWFpbF92ZXJpZmllZCI6ZmFsc2UsImFwcGxpY2F0aW9uSWQiOiI1OTM4M2ViZS0zYjEzLTQ0YjktODM2MS0xZGQ0MWIxYzdlNDkiLCJyb2xlcyI6WyJ1c2VyIl19.o9Qtj7tbqo_imkpNn0eKsg-Fhbn91yu5no1oVaXogNY
the error im getting:
2020-12-16 05:37:56.934 DEBUG 26116 --- [nio-8500-exec-3] w.c.HttpSessionSecurityContextRepository : Did not store empty SecurityContext
2020-12-16 05:37:56.934 DEBUG 26116 --- [nio-8500-exec-3] s.s.w.c.SecurityContextPersistenceFilter : Cleared SecurityContextHolder to complete request
2020-12-16 05:38:00.012 DEBUG 26116 --- [nio-8500-exec-2] o.s.security.web.FilterChainProxy : Securing GET /user/me
2020-12-16 05:38:00.012 DEBUG 26116 --- [nio-8500-exec-2] s.s.w.c.SecurityContextPersistenceFilter : Set SecurityContextHolder to empty SecurityContext
2020-12-16 05:38:00.020 DEBUG 26116 --- [nio-8500-exec-2] o.s.s.o.s.r.a.JwtAuthenticationProvider : Failed to authenticate since the JWT was invalid
2020-12-16 05:38:00.022 DEBUG 26116 --- [nio-8500-exec-2] w.c.HttpSessionSecurityContextRepository : Did not store empty SecurityContext
2020-12-16 05:38:00.022 DEBUG 26116 --- [nio-8500-exec-2] s.s.w.c.SecurityContextPersistenceFilter : Cleared SecurityContextHolder to complete request
The JwtDecoders.fromIssuerLocation will attempt to resolve the jwks_uri from the OpenID Connect discovery document found using the issuer URI.
https://github.com/spring-projects/spring-security/blob/848bd448374156020210c329b886fca010a5f710/oauth2/oauth2-jose/src/main/java/org/springframework/security/oauth2/jwt/JwtDecoders.java#L119
The FusionAuth JSON Web Key Set (JWKS) only publishes the public key from asymmetric key pairs. This means there are no public keys published and the Spring boot library cannot verify the token signature.
For example, if your issuerUri is https://example.com then the OpenID Discovery URL is https://example.com/.well-known/openid-configuration and the value for jwks_uri found in the JSON response from that URL will be https://example.com/.well-known/jwks.json. If you hit that URL you will see no public keys are being returned, this is the JSON that the library is consuming in an attempt to build the public key necessary to validate the JWT signature.
To use this strategy then you'll need to configure FusionAuth to sign the JWT using an RSA or ECDSA key pair instead of the default HMAC key which is symmetric.
Generate a new RSA or ECDA key pair in Key Master (Settings > Key Master) and then ensure you have your JWT signing configuration use that key. The primary JWT signing configuration will be found in the tenant, with optional application level overrides.
https://fusionauth.io/docs/v1/tech/core-concepts/tenants/#jwt
https://fusionauth.io/docs/v1/tech/core-concepts/applications/#jwt
Hope that helps. Once you modify your configuration so that public keys are returned in the JWKS response, and the library is still not validating the token, please re-open and we can go from there.
The reason may be that the JwtDecoder is not being referenced by the oauth2ResourceServer. Check this resource here to see the way they are setting up the ouath2ResourceSever: https://curity.io/resources/tutorials/howtos/writing-apis/spring-boot-api/
In general the token is probably failing the signature validation and so you need to make sure your trusted issuer is configured properly.

Spring Security : LDAP Authentication and Search

I want to convert a normal Spring LDAP integration to Spring Security application. I have the application context as this.
<ldap:context-source
url="ldap://euro.mo.xyz.com:389"
base="ou=prod,dc=euro,dc=mo,dc=xyz,dc=com"
username="mydomain\mohan06"
password="hotStar56" />
When I used passwordCompare and userDn, then I got the following exception
javax.naming.NamingException: [LDAP: error code 1 - 000004DC: LdapErr: DSID-0C09075A, comment: In order to perform this operation a successful bind must be completed on the connection., data 0, v1db1]
After seeing some advice online
I tried using managerDn like the following
protected void configure(AuthenticationManagerBuilder auth) throws Exception {
auth.ldapAuthentication()
.userDnPatterns("OU=prod,DC=euro,DC=mo,DC=xyz,DC=com")
.userSearchFilter("sAMAccountName={0}")
.userSearchBase("OU=prod,DC=euro,DC=mo,DC=xyz,DC=com")
.contextSource()
.url("ldap://ptklt.euro.mo.xyz.com:389")
.managerDn("CN=mydomain\\\\mohan06,OU=prod,DC=euro,DC=mo,DC=xyz,DC=com")
.managerPassword("hotStar56")
.root("OU=prod,DC=euro,DC=mo,DC=xyz,DC=com");
But now I get the following error, even though my credentials are fine.
AcceptSecurityContext error, data 52e, v1db1 ]; nested exception is javax.naming.AuthenticationException
Should I need to use different credentials for password compare and managerDn?

Keycloak Policy Enforcing

Application.properties:
server.port=8180
keycloak.realm = finaltest
keycloak.auth-server-url = http://localhost:8080/auth
keycloak.resource = ex
keycloak.public-client=false
keycloak.enabled=true
keycloak.credentials.secret=secret
keycloak.ssl-required = external
keycloak.cors=true
keycloak.use-resource-role-mappings=true
keycloak.security-constraints[0].auth-roles[0]=master
keycloak.security-constraints[0].security-collections[0].patterns[0]=/*
keycloak.policy-enforcer-config.enforcement-mode=ENFORCING
keycloak.policy-enforcer-config.lazy-load-paths=true
RESOURCES:
I have two resources namely
http://localhost:8180/flights.html
http://localhost:8180/hotels.html
I have protected these using the policies in keycloak admin console.How do I enforce these policies in the application?
keycloak.policy-enforcer-config.enforcement-mode=ENFORCING this line will enforce policies.But you must have spring boot version 2.0 and above.

Creating RDS Datasource fails with "AmazonRDSException: The security token included in the request is invalid"

I am unable to start an application with
#EnableRdsInstance(databaseName = "test",
dbInstanceIdentifier = "test",
password = "password",
username = "username",
readReplicaSupport = true
)
The exception I get is:
org.springframework.beans.factory.BeanCreationException: Error creating bean with name 'test': Invocation of init method failed; nested exception is com.amazonaws.services.rds.model.AmazonRDSException: The security token included in the request is invalid. (Service: AmazonRDS; Status Code: 403; Error Code: InvalidClientTokenId; Request ID: 925519ec-582e-11e7-8ca6-8159eafdc3e8)
at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.initializeBean(AbstractAutowireCapableBeanFactory.java:1628) ~[spring-beans-4.3.9.RELEASE.jar:4.3.9.RELEASE]
...
Caused by: com.amazonaws.services.rds.model.AmazonRDSException: The security token included in the request is invalid. (Service: AmazonRDS; Status Code: 403; Error Code: InvalidClientTokenId; Request ID: 925519ec-582e-11e7-8ca6-8159eafdc3e8)
at ...
Tried all configurations that are suggested in Spring Cloud AWS Docs including ENV variable, System.setProperties(), and in application.yml as below
cloud:
aws:
credentials:
accessKey: XXXXXXX
secretKey: XXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX
region:
static: us-east-2
also tried even hardcoding in in aws-beans
<beans ...>
<aws-context:context-credentials>
<aws-context:simple-credentials access-key="XXXXXXXXXX" secret-key="XXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX"/>
</aws-context:context-credentials>
<aws-context:context-resource-loader/>
<aws-context:context-region region="us-east-2" />
</beans>
and nothing works, help is appreciated....
Possible reasons to get this exception:
Make sure public access is enabled for RDS Instance and allow incoming traffic for your machine in Security Group.
Make sure internet gateway is attached with VPC and very importantly you have to use public subnet rather than private subnet.

Resources